/*
 * @Author: 吴文洁
 * @Date: 2020-08-14 17:02:59
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2020-12-25 14:35:38
 * @Description: 视频课学员名单
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react';
import { Modal, Table, Button, Input, Popconfirm, message } from 'antd';

import Bus from '@/core/bus';
import { PageControl } from "@/components";

// import SelectStudent from "../../modal/select-student";
import hasExportPermission from '../../utils/hasExportPermission';
import dealTimeDuration from '../../utils/dealTimeDuration';

import './StudentListModal.less'

const { Search } = Input;

const STATUS_ENUM = {
  'NORMAL': '在读',
  'POTENTIAL': '潜在',
  'HISTORY': '历史',
  'ABANDON': '废弃',
};

class StudentListModal extends React.Component {
  constructor(props) {
    super(props);
    const { id } = props.data;
    this.state = {
      studentList: [],             // 学员列表
      query: {
        size: 10,
        current: 1,
        queryText: null,
        scheduleId: id,
      },
      total: 0,                    // 学员总数
    }
  }

  componentWillMount() {
    this.handleFetchStuList();
  }

  handleFetchStuList = (current = 1) => {
    const { query } = this.state;
    window.axios.Apollo('public/apollo/getLessonScheduleStuPage', query)
      .then((res) => {
        const { result = {} } = res || {};
        const { records = [], total = 0 } = result;

        this.setState({
          total: Number(total),
          studentList: records,
        })
      })
  }

  // 获取对应课次所有相关学生
  // handleAllSelectStuId = () => {
  //   const { id } = this.props.data;
  //   return axios.Apollo("public/apollo/getLessonStuIdListByScheduleId", { scheduleId: id }).then(res => {
  //     const tempArray = [];
  //     res.data.map(current => {
  //       tempArray.push({studentId: current})
  //     })
  //     this.setState({
  //       _studentList :tempArray
  //     }, () => {
  //         const { query: { scheduleId }, _studentList, allSelectStuId = [] } = this.state;
  //         let { type = '' } = this.props;
  //         const studentModal = (
  //           <SelectStudent
  //             after={true}
  //             showTabs={true}
  //             // type="videoCourse"
  //             type={type}
  //             liveCourseId={scheduleId}
  //             allSelectStuId={allSelectStuId}
  //             studentList={_studentList}
  //             onSelect={this.handleSelectStudent}
  //             close={() => {
  //               this.setState({
  //                 studentModal: null,
  //               });
  //             }}
  //           />
  //         )
  //       this.setState({ studentModal });
  //     })
  //   })
  // }

  parseColumns = () => {
    const { NewVersion, currentUserInstInfo } = window;
    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        key: "name"
      },
      {
        title: "手机号",
        dataIndex: "phone",
        width: 150,
        key: "phone",
        render: (val, record) => {
          if ((!NewVersion && !currentUserInstInfo.teacherId) ||
            (NewVersion && Permission.hasEduStudentPhone())) {
            return val;
          } else {
            return val.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
          }
        }
      },
      {
        title: '学员类型',
        key: 'statusEnum',
        dataIndex: 'statusEnum',
        render: (val) => {
          return STATUS_ENUM[val];
        }
      },
      {
        title: '首次观看时间',
        key: 'firstWatch',
        dataIndex: 'firstWatch',
        width: '20%',
        sorter: true,
        render: (val) => {
          return val ? formatDate('YYYY-DD-MM H:i:s', val) : '-';
        }
      },
      {
        title: '观看时长',
        key: 'watchDuration',
        dataIndex: 'watchDuration',
        width: '15%',
        sorter: true,
        render: (val) => {
          return val ? dealTimeDuration(val) : '-';
        }
      },
      {
        title: "操作",
        dataIndex: "operate",
        key: "operate",
        align:'right',
        render: (text, record) => {
          return (
            <Popconfirm
              title={<span>你确定要移出这个学员吗?<br />移出的学员将无法观看视频</span>}
              onConfirm={() => {
                this.handleRemoveStudent(record);
              }}
            >
              <span className="operate__item">移出</span>
            </Popconfirm>
          );
        },
      }
    ];

    return columns;
  }

  // 移出学员
  handleRemoveStudent = (record) => {
    const { instId } = window.currentUserInstInfo;
    const { id } = this.props.data;
    const { studentId } = record;

    const params = {
      instId,
      scheduleId: id,
      studentIds: [studentId],
    }
    window.axios.Apollo('public/apollo/removeLessonScheduleStu', params)
      .then((res) => {
        message.success("移除学员成功");
        this.handleFetchStuList();
        this.props.refresh();
      })
  }

  // 按照名称或者手机号搜索学员
  handleChangeQueryText = (value) => {
    const query = _.clone(this.state.query);
    query.queryText = value;
    query.pageNo = 0;
    if (isNaN(value)) {
      query.name = value
      delete query.phone
    } else {
      query.phone = value
      delete query.name
    }
    this.setState({ query }, () => this.handleFetchStuList());
  }

  // 排序
  handleChagneTable = (pagination, filters, sorter) => {
    const { columnKey, order } = sorter;
    const { query } = this.state;
    let { order: _order } = query;
    
    if (columnKey === 'firstWatch' && order === 'ascend') { _order = 'FIRST_WATCH_ASC'; }
    if (columnKey === 'firstWatch' && order === 'descend') { _order = 'FIRST_WATCH_DESC'; }
    if (columnKey === 'watchDuration' && order === 'ascend') { _order = 'WATCH_DURATION_ASC'; }
    if (columnKey === 'watchDuration' && order === 'descend') { _order = 'WATCH_DURATION_DESC'; }
    
    const _query = {
      ...query,
      order: _order
    }
    this.setState({ query: _query }, () => this.handleFetchStuList());
  }

  hanldSelect = () => {
    const { query: { scheduleId }, studentList, allSelectStuId = [] } = this.state;
    let { type = '' } = this.props;
    
    type = !!type ? type : 'videoCourse';
    if (type === 'videoCourseList') {
      // this.handleAllSelectStuId();
      return;
    }
    // const studentModal = (
    //   <SelectStudent
    //     after={true}
    //     showTabs={true}
    //     // type="videoCourse"
    //     type={type}
    //     liveCourseId={scheduleId}
    //     allSelectStuId={allSelectStuId}
    //     studentList={studentList}
    //     onSelect={this.handleSelectStudent}
    //     close={() => {
    //       this.setState({
    //         studentModal: null,
    //       });
    //     }}
    //   />
    // )

    this.setState({ studentModal });
  };

  handleSelectStudent = (studentList, consumeStudentList, savedSelectedRows) => {
    const { id } = this.props.data;
    const { instId } = window.currentUserInstInfo;
    studentList = studentList.filter(item => !!item)
    const param = {
      instId,
      scheduleId: id,
      studentIds: studentList
    };
    this.setState({
      savedSelectedRows
    })
    
    axios.Apollo("public/apollo/addLessonScheduleStu", param).then(res => {
      if (res.success) {
        message.success("学员变更成功");
        this.setState({ studentModal: null });
        this.handleFetchStuList();
        this.props.refresh();
      }
    });
  }

  // 导5.0出
  handleExportV5 = () => {
    const { id } = this.props.data;
    window.axios.Apollo('public/apollo/exportVideoScheduleSync', {
      liveCourseId: id
    }).then((res) => { 
      Bus.trigger('get_download_count');
      Modal.success({
        title: '导出任务提交成功',
        content: '请前往右上角的“任务中心”进行下载',
        okText: '我知道了',
      });
    })
  }

  // 4.0导出
  handleExport = () => {
    const { id } = this.props.data;
    window.axios.post('api-b/b/lesson/exportVideoScheduleSync', {
      liveCourseId: id
    }).then((res) => { 
      Bus.trigger('get_download_count');
      Modal.success({
        title: '导出任务提交成功',
        content: '请前往右上角的“导出中心”进行下载',
        okText: '我知道了',
      });
    })
  }

  render() {
    const isTeacher = !!window.currentUserInstInfo.teacherId;
    const { studentList, total, query } = this.state;
    const { current, size, queryText } = query;
    
    return (
      <Modal
        title="查看学员名单"
        visible={true}
        width={680}
        footer={null}
        className="video-course-student-list-modal"
        onCancel={this.props.close}
      >
        {/* 任意状态都可以添加学员 */}
        <div className="video-course-student-list-modal__operate">
          {
            !isTeacher &&
              <Button type="primary" onClick={this.hanldSelect}>
              添加上课学员
            </Button>
          }
          {
            // 有导出权限的机构显示导出按钮
            hasExportPermission('videoClass') &&
            <Button onClick={() => {
              if (!studentList.length) {
                message.warning('暂无数据可导出');
                return;
              }
              if (window.NewVersion) {
                this.handleExportV5();
              } else {
                this.handleExport();
              }
            }} className="export-btn">导出</Button>
          }
          <Search
            placeholder="搜索学员姓名/手机号"
            style={{ width: 200 }}
            onSearch={this.handleChangeQueryText}
            className="search"
          />
        </div>
        <Table
          size="small"
          columns={this.parseColumns()}
          dataSource={studentList}
          pagination={false}
          scroll={{ y: 400 }}
          onChange={this.handleChagneTable}
        />
        <PageControl
          size="small"
          current={current - 1}
          pageSize={size}
          total={total}
          toPage={(page) => {
            query.current = page + 1;
            this.handleFetchStuList();
          }}
        />

        {this.state.studentModal}

      </Modal>
    )
  }
}

export default StudentListModal;
