/*
 * @Author: 吴文洁
 * @Date: 2020-08-07 16:28:49
 * @LastEditors: wufan
 * @LastEditTime: 2020-12-11 17:49:17
 * @Description: 选择学员-学员列表组件
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import { Dropdown, Menu, Tooltip } from 'antd';
import React from 'react';
import _ from 'underscore';

let resourceData = {};
_.map(window.RESOURCE, (item) => {
  resourceData[item.code] = item.name;
});

const isNewVersion = window.NewVersion;

class StudentList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showDegiest: false,
      selectedRows: [],
      prevSelectRows: props.savedSelectedRows || [],
      savedSelectedRows: props.savedSelectedRows || [],
    };
  }

  parseColumns = () => {
    const {
      query: { status },
      type,
      studentType,
    } = this.props;
    // 是否是在读学员
    const isNormal = status === 'NORMAL' || status === 1;
    // 是否是潜在学员
    const isPotential = status === 'POTENTIAL' || status === 2;
    // 是否是历史学员
    const isHistory = status === 'HISTORY' || status === 4;

    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        width: 150,
        render: (text, record) => {
          const { studentBasicVO = {}, name } = record;
          return studentBasicVO.name || name;
        },
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        render: (text, record) => {
          const { type } = this.props;
          const { studentBasicVO = {}, phone, weChatStatus, wechatStatus } = record;
          const {
            NewVersion,
            currentUserInstInfo: { teacherId },
          } = window;
          return (
            <div className='record__item'>
              {!((!NewVersion && !teacherId) || (NewVersion && Permission.hasEduStudentPhone()))
                ? (studentBasicVO.phone || phone).replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
                : studentBasicVO.phone || phone}
              {type !== 'videoCourse' && (
                // 此处为了兼容4.0 和 5.0的扣课 不扣课学员的绑定微信
                <Tooltip title={`${studentBasicVO.weChatStatus || weChatStatus || wechatStatus ? '已绑定微信' : '未绑定微信'}`}>
                  <span
                    className='iconfont icon'
                    style={
                      studentBasicVO.weChatStatus || weChatStatus || wechatStatus
                        ? {
                            color: '#00D20D',
                            fontSize: '16px',
                            marginLeft: 6,
                          }
                        : {
                            fontSize: '16px',
                            color: '#BFBFBF',
                            marginLeft: 6,
                          }
                    }>
                    &#xe68d;
                  </span>
                </Tooltip>
              )}
            </div>
          );
        },
      },
    ];

    // 扣课时学员显示消耗课程和剩余课时
    if (studentType === 'DEDUCTION') {
      const { consumeStudentList } = this.props;

      columns.push(
        {
          title: (
            <div className='consumption-course'>
              <span className='text'>消耗课程</span>
              <Tooltip title='学员在这上课所消耗的课程'>
                <span className='icon iconfont'>&#xe6f2;</span>
              </Tooltip>
            </div>
          ),
          key: 'courseName',
          dataIndex: 'courseName',
          render: (val, record) => {
            const { consumeStudentList } = this.props;
            const { digestHourVOS, studentId } = record;

            if (!digestHourVOS || !digestHourVOS.length) {
              return <span className='digest-hour--empty'>无可消耗课程</span>;
            } else if (digestHourVOS.length === 1) {
              return <span className='course-name'>{digestHourVOS[0].courseName}</span>;
            } else {
              const { showDegiest, currentCourse } = this.state;
              // 默认显示第一个课程包的名称
              let _currentCourse = digestHourVOS[0];

              // 判断学员是否被勾选了
              const hasSelect = _.find(consumeStudentList, (item) => {
                return item.studentId === studentId;
              });

              // 如果被勾选了，再判断选中的课时包是哪个
              if (hasSelect) {
                const hasSelectCourse = _.find(digestHourVOS, (item) => {
                  return item.courseId === hasSelect.classHourId;
                });
                if (hasSelectCourse) {
                  _currentCourse = hasSelectCourse;
                }
              }
              // 选择课时包之后， 根据学员ID判断选择的是哪个学员的课时包
              if (currentCourse && currentCourse.studentId === studentId) {
                _currentCourse = currentCourse;
              }

              if (this.isDisabledRow(record)) {
                return <span className='course-name'>{_currentCourse.courseName}</span>;
              } else {
                return (
                  <Dropdown overlay={this.renderCourseMenu(digestHourVOS)} placement='bottomCenter' arrow>
                    <div
                      className='digest-hour'
                      onMouseEnter={() => {
                        this.setState({ showDegiest: true });
                      }}>
                      <span className='course-name'>{_currentCourse.courseName}</span>
                      {digestHourVOS.length > 1 && !this.isDisabledRow(record) && (
                        <span className={`icon iconfont ${showDegiest ? 'show' : 'hidden'}`}>&#xe6fa;</span>
                      )}
                    </div>
                  </Dropdown>
                );
              }
            }
          },
        },
        {
          title: '剩余课时',
          key: 'leftLessons',
          dataIndex: 'leftLessons',
          render: (val, record) => {
            const { consumeStudentList } = this.props;
            const { digestHourVOS, studentId } = record;

            if (!digestHourVOS || !digestHourVOS.length) {
              return '-';
            } else if (digestHourVOS.length === 1) {
              return digestHourVOS[0].leftLessons;
            } else {
              const { currentCourse } = this.state;
              let _currentCourse = digestHourVOS[0];
              // 判断学员是否被选中了
              const hasSelect = _.find(consumeStudentList, (item) => {
                return item.studentId === studentId;
              });
              // 如果学员被勾选了，再判断该学员选择的课程包是哪个
              if (hasSelect) {
                const hasSelectCourse = _.find(digestHourVOS, (item) => {
                  return item.courseId === hasSelect.classHourId;
                });
                if (hasSelectCourse) {
                  _currentCourse = hasSelectCourse;
                }
              }
              // 选择课时包之后， 根据学员ID判断选择的是哪个学员的课时包
              if (currentCourse && currentCourse.studentId === studentId) {
                _currentCourse = currentCourse;
              }

              return _currentCourse.leftLessons;
            }
          },
        }
      );
    }
    // 在读学员显示年级
    if (type === 'videoCourse' && isNormal) {
      columns.push({
        title: '年级',
        dataIndex: 'gradeName',
        render: (text, record) => {
          const { studentBasicVO = {}, gradeName } = record;
          return studentBasicVO.gradeName || gradeName;
        },
      });
    }

    // 潜在学员显示跟进人和学员来源
    if (isPotential) {
      columns.push(
        {
          title: '跟进人',
          dataIndex: 'saleName',
          render: (val, record) => {
            const { studentSaleVO = {}, saleName } = record;
            return studentSaleVO.saleName || saleName;
          },
        },
        {
          title: '学员来源',
          dataIndex: 'resourceType',
          render: (val, record) => {
            const { studentSaleVO = {}, resourceType } = record;
            return resourceData[studentSaleVO.resourceType || resourceType];
          },
        }
      );
    }

    // 历史学员显示结业时间和报读课程
    if (isHistory) {
      columns.push(
        {
          title: '结业时间',
          key: 'graduationTime',
          dataIndex: 'graduationTime',
          width: 200,
          render: (val, record) => {
            const { studentHistoryVO = {}, graduationTime } = record;
            return formatDate('YYYY-MM-DD', studentHistoryVO.graduationTime || graduationTime);
          },
        },
        {
          title: '报读课程',
          key: 'lostCourseName',
          dataIndex: 'lostCourseName',
          width: 150,
          render: (val, record) => {
            const { studentHistoryVO = {}, lostCourseName } = record;
            return studentHistoryVO.lostCourseName || lostCourseName;
          },
        }
      );
    }
    return columns;
  };

  // 课程下拉选项
  renderCourseMenu = (courseList) => {
    return (
      <Menu>
        {_.map(courseList, (item) => {
          return (
            <Menu.Item
              onClick={(e) => {
                this.handleSelectCourse(e, item);
              }}>
              {item.courseName}
            </Menu.Item>
          );
        })}
      </Menu>
    );
  };

  // 选择当前课程
  handleSelectCourse = (e, currentCourse) => {
    e.domEvent.stopPropagation();
    this.setState(
      {
        currentCourse,
        showDegiest: false,
      },
      () => {
        const { consumeStudentList = [], studentIds, excludeIds } = this.props;
        const { prevSelectRows } = this.state;
        const { studentId, courseId, leftLessons, name, phone } = currentCourse;
        let _consumeStudentList = consumeStudentList;
        // 选完课时包之后，自动勾选当前学员
        const _studentIds = [...studentIds, studentId];

        const hasExist = _.find(consumeStudentList, (item) => {
          return item.studentId === studentId;
        });

        if (hasExist) {
          _consumeStudentList = _.map(consumeStudentList, (item) => {
            if (item.studentId === studentId) {
              item.classHourId = courseId;
            }
            return item;
          });
        } else {
          _consumeStudentList.push({
            name,
            phone,
            studentId,
            classHourId: courseId,
            consumeHourNum: leftLessons,
          });
        }

        this.props.onSelect(_studentIds, _consumeStudentList, prevSelectRows);
      }
    );
  };

  handleSelect = (selectedRowKeys, selectedRows) => {
    const { studentType, allstudentList, consumeStudentList } = this.props;
    const studentIds = _.uniq([].concat(selectedRowKeys));
    let allStudentIds = _.pluck(allstudentList, 'studentId');
    let allSelectRows = [];

    if (studentType === 'DEDUCTION') {
      let { currentCourse, prevSelectRows } = this.state;

      prevSelectRows = _.filter(prevSelectRows, (item) => {
        return allStudentIds.indexOf(item.studentId) === -1;
      });

      const savedSelectedRows = [...prevSelectRows, ...selectedRows];
      allSelectRows = savedSelectedRows.map((item) => {
        const { studentId, digestHourVOS = [], name, phone } = item;
        // 如果该学员已经被选择了
        const hasSelectItem = _.find(consumeStudentList, (_item) => {
          return _item.studentId === item.studentId;
        });
        if (hasSelectItem) {
          return hasSelectItem;
        }
        return {
          name,
          phone,
          studentId,
          classHourId: digestHourVOS[0].courseId,
          consumeHourNum: digestHourVOS[0].leftLessons,
        };
      });

      this.setState(
        {
          selectedRows,
          savedSelectedRows,
        },
        () => {
          this.props.onSelect(studentIds, allSelectRows, savedSelectedRows);
        }
      );
    } else {
      this.props.onSelect(studentIds);
    }
  };

  isDisabledRow = (record) => {
    // 扣课时的情况下, 无消耗课程的禁用
    const { after, excludeIds, studentType, studentList = [], consumeStudentList = [] } = this.props;
    const { digestHourVOS } = record;
    const hasDigestHours = digestHourVOS && digestHourVOS.length;

    // 已经入库的学员不可再选择
    const hasSelect = _.find(excludeIds, (item) => {
      return item == record.studentId;
    });
    let disabled = false;
    // 扣课时学员课时为0的情况下禁止选择
    if (studentType === 'DEDUCTION') {
      // 判断是否已经在不扣课时里
      if (_.find(studentList, (item) => item.studentId === record.studentId)) {
        disabled = true;
      } else if (!hasDigestHours || (after && !!hasSelect)) {
        disabled = true;
      }
    } else {
      if (_.find(consumeStudentList, (item) => item.studentId === record.studentId)) {
        disabled = true;
      } else if (after && !!hasSelect) {
        disabled = true;
      }
    }

    return disabled;
  };

  render() {
    const { after, query, totalCount, studentIds, allstudentList } = this.props;

    const { prevSelectRows, selectedRows } = this.state;
    const { current, size, pageNo, pageSize } = query;

    const rowSelection = {
      selectedRowKeys: studentIds,
      onChange: this.handleSelect,
      getCheckboxProps: (record) => {
        return {
          disabled: this.isDisabledRow(record),
        };
      },
    };

    return (
      <div className='student-list'>
        <XMTable
          renderEmpty={{
            image: college,
            description: '暂无数据',
          }}
          bordered
          size={'small'}
          rowKey={(item) => item.studentId}
          dataSource={allstudentList}
          columns={this.parseColumns()}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: (e) => {
              e.currentTarget.getElementsByClassName('ant-checkbox-wrapper')[0].click();
            },
          })}
          scroll={{ y: 350 }}
          pagination={false}
        />

        {isNewVersion ? (
          <PageControl
            size='small'
            current={current - 1}
            pageSize={size}
            total={totalCount}
            showSizeChanger={true}
            toPage={(page) => {
              this.state.prevSelectRows = this.state.savedSelectedRows;
              this.props.onChange('current', page + 1);
            }}
            onShowSizeChange={(current, size) => {
              this.props.onChange('size', size);
            }}
          />
        ) : (
          <PageControl
            size='small'
            current={pageNo}
            pageSize={pageSize}
            total={totalCount}
            showSizeChanger={true}
            toPage={(page) => {
              this.props.onChange('pageNo', page);
            }}
            onShowSizeChange={(pageNo, pageSize) => {
              this.props.onChange('pageNo', pageSize);
            }}
          />
        )}
      </div>
    );
  }
}

export default StudentList;
