/*
 * @Description: 上课记录
 * @Author: zhangyi
 * @Date: 2020-05-12 09:43:48
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2021-02-01 14:00:19
 */

import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import Bus from '@/core/bus';
import { Button, Checkbox, Input, message, Modal, Tooltip } from 'antd';
import React from 'react';
import dealTimeDuration from '../utils/dealTimeDuration';
import hasExportPermission from '../utils/hasExportPermission';
import './ClassRecordModal.less';

const { Search } = Input;

class ClassRecordModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teacherData: [],
      classList: [],
      query: {
        current: 1,
        size: 10,
        nameOrPhone: '',
        liveSignState: '',
        durationSort: null,
        liveCourseId: props.liveItem.liveCourseId,
      },
    };
  }
  componentDidMount() {
    this.fetchClassList();
    this.fetchTeacherData();
  }

  fetchClassList = (page = 1) => {
    const params = _.clone(this.state.query);
    if (!params.liveSignState) {
      delete params.liveSignState;
    }
    params.current = page;
    window.axios.Apollo('public/businessLive/queryStudentVisitData', params).then((res) => {
      if (res.result) {
        const { records = [], total } = res.result;
        this.setState({
          classList: records,
          total,
          query: params,
        });
      }
    });
  };
  fetchTeacherData = () => {
    const { liveCourseId } = this.props.liveItem;
    window.axios.Apollo('public/businessLive/queryTeacherVisitData', { liveCourseId }).then((res) => {
      if (res.result) {
        const teacherData = [res.result];
        this.setState({
          teacherData,
        });
      }
    });
  };

  getColumns = (type) => {
    const { consumeClassTime } = this.props.liveItem;
    const source = this.props.type;
    const columns = [
      {
        title: type == 'student' ? '学生姓名' : '老师姓名',
        dataIndex: 'userName',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        render: (text, record) => {
          return (
            <p>
              {!((!window.NewVersion && !window.currentUserInstInfo.teacherId) || (window.NewVersion && Permission.hasEduStudentPhone())) && type == 'student'
                ? (text || '').replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
                : text}
            </p>
          );
        },
      },
      {
        title: type == 'student' ? '观看直播次数' : '进入直播间次数',
        dataIndex: 'entryNum',
        align: 'right',
      },
      {
        title: '累计上课时长',
        dataIndex: type == 'student' ? 'watchDuration' : 'totalDuration',
        sorter: type == 'student' ? (a, b) => a.watchDuration - b.watchDuration : null,
        sortDirections: ['descend', 'ascend'],
        render: (text, record) => {
          //如无离开时间，就置空
          return <span>{text ? dealTimeDuration(text) : '00:00:00'}</span>;
        },
      },
    ];
    if (type == 'student') {
      columns.push({
        title: (
          <span>
            到课状态
            <Tooltip
              title={
                <div>
                  学员累计上课时长达到<span className='bulge'>{consumeClassTime}</span>分钟，即视为学员“到课”
                </div>
              }>
              <span className='iconfont'>&#xe6f2;</span>
            </Tooltip>
          </span>
        ),
        width: 100,
        dataIndex: 'signState',
        render: (text) => {
          if (text) {
            return <span>{text === 'ABSENT' ? '未到' : '到课'}</span>;
          } else {
            return <span>-</span>;
          }
        },
      });
      if (source) {
        columns.push({
          title: '获得奖杯数',
          dataIndex: 'trophyNum',
          align: 'right',
          render: (text) => {
            return <span>{text ? text : 0}</span>;
          },
        });
      }
    }
    return columns;
  };

  handleTableChange = (pagination, filters, sorter) => {
    const query = this.state.query;
    if (!_.isEmpty(sorter)) {
      if (sorter.columnKey === 'totalDuration') {
        if (sorter.order === 'ascend') {
          query.durationSort = 'SORT_ASC';
        } else if (sorter.order === 'descend') {
          query.durationSort = 'SORT_DESC';
        }
        this.setState({ query }, this.fetchClassList);
      }
    }
  };

  // 5.0导出
  handleExportV5 = () => {
    const { liveItem, type } = this.props;
    const { liveCourseId } = liveItem;
    const url = !type ? 'public/businessLive/exportLargeClassLiveAsync' : 'public/businessLive/exportClassInteractionLiveSync';

    window.axios
      .Apollo(url, {
        liveCourseId,
        exportLiveType: 'VISITOR',
      })
      .then((res) => {
        Bus.trigger('get_download_count');
        Modal.success({
          title: '导出任务提交成功',
          content: '请前往右上角的“任务中心”进行下载',
          okText: '我知道了',
        });
      });
  };

  // 4.0导出
  handleExport = () => {
    const { liveItem, type } = this.props;
    const { liveCourseId } = liveItem;
    const url = !type ? 'api-b/b/lesson/exportLargeClassLiveAsync' : 'api-b/b/lesson/exportClassInteractionLiveSync';

    window.axios
      .post(url, {
        liveCourseId,
        exportLiveType: 1,
      })
      .then((res) => {
        Bus.trigger('get_download_count');
        Modal.success({
          title: '导出任务提交成功',
          content: '请前往右上角的“导出中心”进行下载',
          okText: '我知道了',
        });
      });
  };

  render() {
    const { type } = this.props;
    const { query, total, teacherData, classList } = this.state;
    const expandedColumns = [
      {
        title: '进入时间',
        dataIndex: 'entryTime',
        key: 'entryTime',
        render: (text) => <span>{formatDate('YYYY-MM-DD H:i', parseInt(text))}</span>,
      },
      {
        title: '离开时间',
        dataIndex: 'leaveTime',
        key: 'leaveTime',
        render: (text) => <span>{formatDate('YYYY-MM-DD H:i', parseInt(text))}</span>,
      },
      {
        title: '上课时长',
        dataIndex: 'lookingDuration',
        key: 'lookingDuration',
        render: (text, record) => {
          return <span>{text ? dealTimeDuration(text) : '-'}</span>;
        },
      },
    ];
    return (
      <Modal
        title='上课记录'
        visible={true}
        footer={null}
        width={680}
        maskClosable={false}
        closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}
        className='class-record-modal'
        onCancel={() => {
          this.props.close();
        }}>
        <div>
          <p className='class-record-title' style={{ marginBottom: 18 }}>
            老师上课数据
          </p>
          <XMTable
            renderEmpty={{
              image: college,
              description: '暂无数据',
            }}
            size='small'
            columns={this.getColumns('teacher')}
            dataSource={teacherData}
            pagination={false}
            className='table-no-scrollbar'
            expandedRowRender={(record) => {
              if (record.visitorInfoVOList && record.visitorInfoVOList.length > 0) {
                return (
                  <XMTable
                    renderEmpty={{
                      image: college,
                      description: '暂无数据',
                    }}
                    columns={expandedColumns}
                    dataSource={record.visitorInfoVOList}
                    size={'small'}
                    className='no-scrollbar expanded-table'
                    pagination={false}
                  />
                );
              } else {
                return <div className='live-table--empty'>暂无上课数据</div>;
              }
            }}
          />
          <div className='student-wrapper'>
            <section className='class-record-title'>学员上课数据</section>
            <section>
              <Checkbox
                style={{ lineHeight: '33px' }}
                onChange={(e) => {
                  const param = _.clone(this.state.query);
                  param.current = 1;
                  param.liveSignState = e.target.checked ? 'SIGN' : '';
                  this.setState(
                    {
                      query: param,
                    },
                    () => {
                      this.fetchClassList();
                    }
                  );
                }}>
                只看“到课”学员
              </Checkbox>
              <Search
                className='student-wrapper__search'
                placeholder='搜索学员姓名/手机号'
                style={{ width: 200, marginBottom: 0 }}
                onSearch={(value) => {
                  const param = _.clone(this.state.query);
                  param.nameOrPhone = value;
                  param.current = 1;
                  this.setState(
                    {
                      query: param,
                    },
                    () => {
                      this.fetchClassList();
                    }
                  );
                }}
              />
              {hasExportPermission(type) && (
                <Button
                  onClick={_.debounce(
                    () => {
                      if (!classList.length) {
                        message.warning('暂无数据可导出');
                        return;
                      }
                      if (window.NewVersion) {
                        this.handleExportV5();
                      } else {
                        this.handleExport();
                      }
                    },
                    500,
                    true
                  )}>
                  导出
                </Button>
              )}
            </section>
          </div>
          <div>
            <XMTable
              renderEmpty={{
                image: college,
                description: '暂无数据',
              }}
              size='small'
              columns={this.getColumns('student')}
              dataSource={classList}
              pagination={false}
              className='table-no-scrollbar'
              onChange={this.handleTableChange}
              expandedRowRender={(record) => {
                if (record.visitorInfoVOList && record.visitorInfoVOList.length > 0) {
                  return (
                    <XMTable
                      renderEmpty={{
                        image: college,
                        description: '暂无数据',
                      }}
                      columns={expandedColumns}
                      dataSource={record.visitorInfoVOList}
                      size={'small'}
                      className='no-scrollbar expanded-table'
                      pagination={false}
                    />
                  );
                } else {
                  return <div className='live-table--empty'>暂无上课数据</div>;
                }
              }}
            />
            <PageControl
              size='small'
              current={query.current - 1}
              pageSize={query.size}
              total={total}
              toPage={(page) => {
                this.fetchClassList(page + 1);
              }}
            />
          </div>
        </div>
      </Modal>
    );
  }
}
export default ClassRecordModal;
