import React from 'react';
import { Tooltip, Input, Radio, Table } from 'antd';
import moment from 'moment';
import _ from 'underscore';
import Breadcrumbs from "@/components/Breadcrumbs";
import PageControl from '@/components/PageControl';
import Service from "@/common/js/service";
import User from '@/common/js/user';
import './OfflineCourseData.less';

const { Search } = Input;

export default class OfflineCourseData extends React.Component {
  constructor(props) {
    super(props);
    const courseId = window.getParameterByName('id');
    this.state = {
      courseId,
      query: {
        size: 10,
        current: 1,
        courseId,
        storeId: User.getStoreId(),
        joinInState: 'YES',
        joinOutState: 'YES',
      },
      loading: false,
      data: [],
      total: 0,
      courseName: '',
      calendarTime: [],
      currentIndex: 0,
      fullJoin: 0,
      totalJoin: 0,
      fullJoinNum: 0,
      joinInNum: 0,
      joinNum: 0,
      joinOutNum: 0,
    }
  }

  componentDidMount() {
    this.getOfflineBasic();
    this.getOfflineCalendar();
  }

  getOfflineBasic = () => {
    const { courseId } = this.state;
    Service.Hades('public/hades/getOfflineCourseJoinBase', { courseId }).then((res) => {
      if (res.success) {
        const { result } = res;
        this.setState({
          courseName: result.courseName,
          fullJoin: result.fullJoin || 0,
          totalJoin: result.totalJoin || 0,
        });
      }
    })
  }

  getOfflineCalendar = () => {
    const { courseId, currentIndex } = this.state;
    Service.Hades('public/customerHades/offlineDateList', { courseId }).then((res) => {
      if (res.success) {
        const timeList = _.sortBy(_.pluck(res.result, 'date'));
        const group = _.groupBy(timeList, item => moment(item).format('YYYY年M月'));
        const calendarTime = _.map(group, (value, key) => ({ key, value }));
        const currentDate = calendarTime[currentIndex].value[0];
        this.setState({
          calendarTime,
          currentDate,
        }, () => this.getDateDetail())
      }
    });
  }

  getDateDetail = (current = 1) => {
    const { query, currentDate, courseId } = this.state;
    if (currentDate !== query.date) {
      Service.Hades('public/hades/getOfflineDateJoinStatistics', { courseId, date: currentDate }).then((res) => {
        if (res.success) {
          this.setState({
            fullJoinNum: res.result.fullJoinNum || 0,
            joinInNum: res.result.joinInNum || 0,
            joinNum: res.result.joinNum || 0,
            joinOutNum: res.result.joinOutNum || 0,
          })
        }
      })
    }
    query.current = current;
    query.date = currentDate;
    Service.Hades('public/hades/getOfflineDateJoinPage', query).then((res) => {
      if (res.success) {
        this.setState({ data: res.result.records, total: res.result.total });
      }
    })
  }

  getColumns = () => {
    const columns = [
      {
        title: '用户姓名',
        key: 'name',
        dataIndex: 'name',
        render: (val, record) => {
          return (
            <div>{record.name}</div>
          )
        }
      },
      {
        title: "手机号",
        key: "phone",
        dataIndex: "phone",
        render: (val, item) => {
          return (
            <div>{item.phone}</div>
          )
        },
      },
      {
        title: '报名时间',
        key: 'joinTime',
        dataIndex: 'joinTime',
        render: (val, item) => {
          return <div>{formatDate('YYYY-MM-DD H:i', item.joinTime)}</div>
        }
      },
      {
        title: '签到时间',
        key: 'joinInTime',
        dataIndex: 'joinInTime',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
      {
        title: '签退时间',
        key: 'joinOutTime',
        dataIndex: 'joinOutTime',
        sorter: true,
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val) 
        }
      },
    ];
    return columns;
  }

  handleChangeTable = () => {

  }

  render() {
    const {
      query,
      loading,
      data,
      total,
      courseName,
      fullJoin,
      totalJoin,
      calendarTime,
      currentIndex,
      currentDate,
      fullJoinNum,
      joinInNum,
      joinNum,
      joinOutNum,
    } = this.state;
    const calendarLength = calendarTime.length;
    const dateList = (calendarTime[currentIndex] || {}).value || [];
    return (
      <div className="page offline-course-data">
        <Breadcrumbs
          navList="参与数据"
          goBack={() => {
            window.RCHistory.goBack();
          }}
        />
        <div className="box">
          <div className="offline-name">课程名称：{courseName}</div>
          <div className="offline-application">报名总人数：{totalJoin}</div>
          <div className="offline-application">
            完成考勤总人数<Tooltip title="根据上课日期，在规定时间内完成签到和签退的用户数"><span className="icon iconfont">&#xe7c4;</span></Tooltip>：{fullJoin}
          </div>
        </div>
        <div className="box data-box">
          <div className="left-box">
            <div className="left-title">上课日期</div>
            <div className="left-calendar">
              <div
                className="icon-box"
                onClick={() => {
                  const index = currentIndex - 1;
                  if (index >= 0 && index < calendarLength) {
                    this.setState({ currentIndex: index, currentDate: calendarTime[index][0] }, () => {
                      this.getDateDetail();
                    });
                  }
                }}
              >
                <span className="icon iconfont">&#xe79c;</span>
              </div>
              <div className="calendar-text">{(calendarTime[currentIndex] || {}).key}</div>
              <div
                className="icon-box"
                onClick={() => {
                  const index = currentIndex + 1;
                  if (index >= 0 && index < calendarLength) {
                    this.setState({ currentIndex: index, currentDate: calendarTime[index][0] }, () => {
                      this.getDateDetail();
                    });
                  }
                }}
              >
                <span className="icon iconfont">&#xe79b;</span>
              </div>
            </div>
            <div className="date-list">
              {dateList.map(item => (
                <div
                  className={`date-item${item === currentDate ? ' selected' : ''}`}
                  key={item}
                  onClick={() => {
                    this.setState({ currentDate: item }, () => {
                      this.getDateDetail();
                    })
                  }}
                >{window.formatDate('MM月DD日（WW）', item)}</div>
              ))}
            </div>
          </div>
          <div className="right-box">
            <div className="selected-date">5月1日</div>
            <div className="detail-data">
              <span className="icon iconfont">&#xe89f;</span>
              <span className="data-text">报名人数：{joinNum}</span>
              <span className="icon iconfont">&#xe89e;</span>
              <span className="data-text">完成考勤数<Tooltip title="当日在规定时间内完成签到和签退的用户数"><span className="icon iconfont">&#xe7c4;</span></Tooltip>：{fullJoinNum}</span>
              <span className="icon iconfont">&#xe8a0;</span>
              <span className="data-text">签到人数：{joinInNum}</span>
              <span className="icon iconfont">&#xe89d;</span>
              <span className="data-text">签退人数：{joinOutNum}</span>
            </div>
            <div className="detail-filter">
              <Search
                className="search-input"
                placeholder="搜索用户姓名/手机号"
                style={{ width: 200, marginRight: 24 }}
                enterButton={<span className="icon iconfont">&#xe832;</span>}
                onSearch={(value) => {
                  const _query = { ...query };
                  if (value) {
                    const isPhone = (value || "").match(/^\d+$/);
                    const name = isPhone ? "storeCustomerPhone" : "storeCustomerName";
                    _query.storeCustomerName = "";
                    _query.storeCustomerPhone = "";
                    _query[name] = value;
                  } else {
                    _query.storeCustomerName = "";
                    _query.storeCustomerPhone = "";
                  }
                  this.setState({ query: _query }, () => this.getDateDetail());
                }}
              />
              <div className="filter-box">
                <span className="label">签到情况：</span>
                <Radio.Group
                  value={query.joinInState}
                  onChange={(e) => {
                    this.setState({ query: { ...query, joinInState: e.target.value } }, () => this.getDateDetail());
                  }}
                >
                  <Radio value="YES">已签到</Radio>
                  <Radio value="NO">未签到</Radio>
                </Radio.Group>
              </div>
              <div className="filter-box">
                <span className="label">签退情况：</span>
                <Radio.Group
                  value={query.joinOutState}
                  onChange={(e) => {
                    this.setState({ query: { ...query, joinOutState: e.target.value } }, () => this.getDateDetail());
                  }}
                >
                  <Radio value="YES">已签退</Radio>
                  <Radio value="NO">未签退</Radio>
                </Radio.Group>
              </div>
            </div>
            <Table
              bordered
              size="middle"
              pagination={false}
              columns={this.getColumns()}
              loading={loading}
              dataSource={data}
              onChange={this.handleChangeTable}
              rowKey={(row) => row.liveCourseId}
            />
            <PageControl
              current={query.current}
              pageSize={query.size}
              total={total}
              toPage={(page) => {
                this.getDateDetail(page);
              }}
            />
          </div>
        </div>
      </div>
    )
  }
}