import Service from '@/common/js/service';
import User from '@/common/js/user';
import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import Breadcrumbs from '@/components/Breadcrumbs';
import { Checkbox, Input, Tooltip } from 'antd';
import moment from 'moment';
import React from 'react';
import _ from 'underscore';
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(),
      },
      loading: false,
      data: [],
      total: 0,
      courseName: '',
      calendarTime: [],
      currentIndex: 0,
      fullJoin: 0,
      totalJoin: 0,
      fullJoinNum: 0,
      joinInNum: 0,
      joinNum: 0,
      joinOutNum: 0,
    };
  }

  componentDidMount() {
    this.getOfflineBasic();
  }

  getOfflineBasic = () => {
    const { courseId, currentIndex } = this.state;
    Service.Hades('public/hades/getOfflineCourseJoinBase', { courseId }).then((res) => {
      if (res.success) {
        const { result } = res;
        const group = _.groupBy(result.calendarTime, (item) => moment(item).format('YYYY-MM'));
        const calendarTime = _.map(group, (value, key) => ({ key, value }));
        const currentDate = calendarTime[currentIndex].value[0];
        this.setState(
          {
            courseName: result.courseName,
            fullJoin: result.fullJoin || 0,
            totalJoin: result.totalJoin || 0,
            calendarTime,
            currentDate,
            offlineCourseType: result.offlineCourseType,
            whetherSetSignIn: result.whetherSetSignIn,
            whetherSetSignOut: result.whetherSetSignOut,
            whetherSetSignInOut: result.whetherSetSignInOut,
            whetherSetApply: result.whetherSetApply,
          },
          () => 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 { whetherSetSignIn, whetherSetSignOut, whetherSetApply } = this.state;
    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>;
        },
      },
    ];
    whetherSetApply === 'YES' &&
      columns.push({
        title: '报名时间',
        key: 'joinTime',
        dataIndex: 'joinTime',
        render: (val, item) => {
          return <div>{formatDate('YYYY-MM-DD H:i', item.joinTime)}</div>;
        },
      });
    whetherSetSignIn === 'YES' &&
      columns.push({
        title: '签到时间',
        key: 'joinInTime',
        dataIndex: 'joinInTime',
        sorter: true,
        render: (val) => {
          return val ? formatDate('YYYY-MM-DD H:i', val) : '-';
        },
      });
    whetherSetSignOut === 'YES' &&
      columns.push({
        title: '签退时间',
        key: 'joinOutTime',
        dataIndex: 'joinOutTime',
        sorter: true,
        render: (val) => {
          return val ? formatDate('YYYY-MM-DD H:i', val) : '-';
        },
      });
    return columns;
  };

  handleChangeTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.state;
    let orderEnum;
    // 按创建时间升序排序
    if (columnKey === 'joinInTime' && order === 'ascend') {
      orderEnum = 'JOIN_IN_ASC';
    } else if (columnKey === 'joinOutTime' && order === 'ascend') {
      orderEnum = 'JOIN_OUT_ASC';
    } else if (columnKey === 'joinInTime' && order === 'descend') {
      orderEnum = 'JOIN_IN_DESC';
    } else if (columnKey === 'joinOutTime' && order === 'descend') {
      orderEnum = 'JOIN_OUT_DESC';
    }
    const _query = {
      ...query,
      orderEnum,
    };
    this.setState({ query: _query }, () => {
      this.getDateDetail(_query.current);
    });
  };

  render() {
    const {
      query,
      loading,
      data,
      total,
      courseName,
      fullJoin,
      totalJoin,
      calendarTime,
      currentIndex,
      currentDate,
      fullJoinNum,
      joinInNum,
      joinNum,
      joinOutNum,
      offlineCourseType,
      whetherSetApply,
      whetherSetSignIn,
      whetherSetSignOut,
      whetherSetSignInOut,
    } = 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>
          {whetherSetApply === 'YES' && <div className='offline-application'>报名总人数：{totalJoin}</div>}
          {whetherSetSignInOut === 'YES' && (
            <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].value[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].value[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'>{moment(currentDate).format('MM-DD')}</div>
            <div className='detail-data'>
              {offlineCourseType !== 'ALL_DAY_OFFLINE' && whetherSetApply === 'YES' && <span className='icon iconfont'>&#xe89f;</span>}
              {offlineCourseType !== 'ALL_DAY_OFFLINE' && whetherSetApply === 'YES' && <span className='data-text'>报名人数：{joinNum}</span>}
              {whetherSetSignInOut === 'YES' && <span className='icon iconfont'>&#xe89e;</span>}
              {whetherSetSignInOut === 'YES' && (
                <span className='data-text'>
                  完成考勤数
                  <Tooltip title='当日在规定时间内完成签到和签退的学员数'>
                    <span className='icon iconfont'>&#xe7c4;</span>
                  </Tooltip>
                  ：{fullJoinNum}
                </span>
              )}
              {whetherSetSignIn === 'YES' && <span className='icon iconfont'>&#xe8a0;</span>}
              {whetherSetSignIn === 'YES' && <span className='data-text'>签到人数：{joinInNum}</span>}
              {whetherSetSignOut === 'YES' && <span className='icon iconfont'>&#xe89d;</span>}
              {whetherSetSignOut === 'YES' && <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());
                }}
              />
              {whetherSetSignInOut === 'YES' && (
                <div className='filter-box'>
                  <span className='label'>签到情况：</span>
                  <Checkbox
                    checked={query.joinInState === 'YES'}
                    onChange={(e) => {
                      if (e.target.checked) {
                        this.setState({ query: { ...query, joinInState: 'YES' } }, () => this.getDateDetail());
                      } else {
                        delete query.joinInState;
                        this.setState({ query }, () => this.getDateDetail());
                      }
                    }}>
                    已签到
                  </Checkbox>
                  <Checkbox
                    checked={query.joinInState === 'NO'}
                    onChange={(e) => {
                      if (e.target.checked) {
                        this.setState({ query: { ...query, joinInState: 'NO' } }, () => this.getDateDetail());
                      } else {
                        delete query.joinInState;
                        this.setState({ query }, () => this.getDateDetail());
                      }
                    }}>
                    未签到
                  </Checkbox>
                </div>
              )}
              {whetherSetSignOut === 'YES' && (
                <div className='filter-box'>
                  <span className='label'>签退情况：</span>
                  <Checkbox
                    checked={query.joinOutState === 'YES'}
                    onChange={(e) => {
                      if (e.target.checked) {
                        this.setState({ query: { ...query, joinOutState: 'YES' } }, () => this.getDateDetail());
                      } else {
                        delete query.joinOutState;
                        this.setState({ query }, () => this.getDateDetail());
                      }
                    }}>
                    已签退
                  </Checkbox>
                  <Checkbox
                    checked={query.joinOutState === 'NO'}
                    onChange={(e) => {
                      if (e.target.checked) {
                        this.setState({ query: { ...query, joinOutState: 'NO' } }, () => this.getDateDetail());
                      } else {
                        delete query.joinOutState;
                        this.setState({ query }, () => this.getDateDetail());
                      }
                    }}>
                    未签退
                  </Checkbox>
                </div>
              )}
            </div>
            <XMTable
              renderEmpty={{
                image: college,
                description: '暂无数据',
              }}
              bordered
              size='middle'
              pagination={false}
              columns={this.getColumns()}
              loading={loading}
              dataSource={data}
              onChange={this.handleChangeTable}
              rowKey={(row) => row.userId}
            />
            <PageControl
              current={query.current - 1}
              pageSize={query.size}
              total={total}
              toPage={(page) => {
                this.getDateDetail(page + 1);
              }}
            />
          </div>
        </div>
      </div>
    );
  }
}
