/*
 * @Author: 吴文洁
 * @Date: 2020-08-07 16:23:27
 * @LastEditors: 吴文洁
 * @LastEditTime: 2020-09-27 19:33:20
 * @Description: 选择学员组件
 * @Copyright: 杭州杰竞科技有限公司 版权所有
 */

import React from 'react';
import { Modal, Radio, message } from 'antd';

import Bus from '@/core/bus';
import ShowTips from "@/components/ShowTips";

import FilterContent from './FilterContent';
import StudentList from './StudentList';

import './index.less';

const isNewVersion = window.NewVersion;

const DEFAULT_NEW_QUERY = {
  size: 10,
  current: 1,
  status: 'NORMAL', // 学员类型, 默认显示在读学员
};

const DEFAULT_NEW_DEDUCTION_QUERY = {
  size: 10,
  current: 1,
  status: 'NORMAL', // 学员类型, 默认显示在读学员
}

const DEFAULT_OLD_QUERY = {
  pageNo: 0,
  pageSize: 10,
  status: 1,
}

const OLD_URL = {
  1: 'api-b/b/student/list',
  2: 'api-b/b/potential/list',
  4: 'api-b/b/student/history/list'
}

class SelectStudent extends React.Component {

  constructor(props) {
    super(props);
    const {
      studentType,
      // 扣课时学员列表
      consumeStudentList = [],
      // 不扣课时学员列表
      studentList = [],
      // 不扣课时学员ID列表（已经入库的）
      excludeStudentIds = [],
      // 扣课时学员ID列表（已经入库的）
      excludeConsumeStudentIds = []
    } = props;
    const _studentList = studentType === 'DEDUCTION' ? consumeStudentList : studentList;
    const excludeIds = studentType === 'DEDUCTION' ? excludeConsumeStudentIds : excludeStudentIds;

    this.state = {
      newQuery: { ...DEFAULT_NEW_QUERY },
      oldQuery: { ...DEFAULT_OLD_QUERY } ,
      newDeductionQuery: { ...DEFAULT_NEW_DEDUCTION_QUERY },
      totalCount: 0,
      allstudentList: [],                      // 学员列表
      excludeIds,                              // 已经入库的学员
      consumeStudentList: [].concat(consumeStudentList),                      // 扣课时学员列表
      studentIds: _.pluck(_studentList, 'studentId'),
    }
  }

  componentDidMount() {
    this.handleFetchStudentList();
  }

  // 获取学员列表
  handleFetchStudentList = () => {
    // 5.0和4.0请求学员列表的接口不一样
    if (isNewVersion) {
      const { studentType } = this.props;
      // 扣课时学员
      if (studentType === 'DEDUCTION') {
        this.handleFetchNewDeductionStudentList();
      } else {
        // 不扣课时学员
        this.handleFetchNewStudentList();
      }
    } else {
      this.handleFetchOldStudentList();
    }
  }

  // 获取不扣课时学员列表
  handleFetchNewStudentList = () => {
    const { adminId, instId } = window.currentUserInstInfo;
    const { studentType } = this.props;
    const { newQuery } = this.state;
    const {
      current, size, status, courseId, saleId,
      classId, teacherId, nameOrPhone, resourceType
    } = newQuery;
    const _query = {
      size,
      current,
      status,
      instId,
      adminId,
      expandRequest: {
        courseId,
        classId,
        teacherId,
      },
      basicRequest: {},
      filterRequest: {
        saleId,
        resourceType,
      }
    };

    if ((nameOrPhone || '').match(/[^0-9]/)) {
      _query.basicRequest.nameLike = nameOrPhone;
    } else {
      _query.basicRequest.phoneLike = nameOrPhone;
    }
    
    window.axios.Business('public/student/getLearningStudentPage', _query)
      .then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0 } = result;
        const studentVOList = records;

        let allstudentList = [];

        allstudentList = _.map(studentVOList, item => {
          const { studentBasicVO: { studentId } } = item;
          return {
            ...item,
            studentId,
            key: studentId
          }
        });

        this.setState({
          allstudentList,
          totalCount: Number(total),
        });
      });
  }

  // 获取扣课时学员列表
  handleFetchNewDeductionStudentList = () => {
    const { newDeductionQuery } = this.state;
    const { size, current, courseId, classId, nameOrPhone } = newDeductionQuery;

    const _query = {
      size,
      current,
      classId,
      courseId,
    }

    if ((nameOrPhone || '').match(/[^0-9]/)) {
      _query.nameLike = nameOrPhone;
    } else {
      _query.phoneLike = nameOrPhone;
    }

    window.axios.Business('public/student/getStudentListWithUseAbleAccount', _query)
      .then((res) => {
        const { result = {} } = res;
        const { records = [], total = 0 } = result;

        const allstudentList = _.map(records, item => ({
          ...item,
          key: item.studentId,
        }));

        this.setState({
          allstudentList,
          totalCount: Number(total),
        })
      });
  }

  handleFetchOldStudentList = () => {
    const { oldQuery } = this.state;
    const { studentType } = this.props;
    const {
      pageNo, pageSize, courseId, saleId, status,
      classId, teacherId, nameOrPhone, resourceType
    } = oldQuery;
    
    const _query = {
      pageNo,
      pageSize,
      saleId,
      courseId,
      classId,
      teacherId,
      nameOrPhone,
      resourceType,
    }

    window.axios.post(OLD_URL[status], _query)
      .then((res) => {
        let studentVOList = [];
        let totalCount = 0;
        if (status !== 4) {
          const { data = {} } = res || {};
          studentVOList = data.studentVOList;
          totalCount = data.totalCount;
        } else {
          studentVOList = res.data;
          totalCount = res.totalCount;
        }

        const allstudentList = _.map(studentVOList, item => ({
          ...item,
          key: item.studentId,
          studentId: item.studentId
        }));

        this.setState({
          totalCount,
          allstudentList,
        })
      })
  }

  // 修改学员类型,清空搜索条件
  handleChangeStatus = (e) => {
    const { value } = e.target;
    Bus.trigger('resetSearchBar');
    this.setState({
      newQuery: {
        size: 10,
        current: 1,
        status: value,
      },
      oldQuery: {
        pageNo: 0,
        pageSize: 10,
        status: value,
      },
      newDeductionQuery: {
        size: 10,
        current: 1
      }
    }, () => {
      this.handleFetchStudentList();
    })
  }

  handleChangeQuery = (field, value) => {
    const { newQuery, oldQuery, newDeductionQuery } = this.state;

    const _newQuery = {
      ...newQuery,
      [field]: value
    };

    if (field === 'size') {
      _newQuery.current = 1;
    }

    
    const _oldQuery = {
     ...oldQuery,
      [field]: value
    };

    if (field === 'size') {
      _oldQuery.pageNo = 0;
    }

    const _newDeductionQuery = {
      ...newDeductionQuery,
      [field]: value
    };

    if (field === 'size') {
      _newDeductionQuery.current = 1;
    }

    this.setState({
      newQuery: {
        ..._newQuery,
      },
      oldQuery: {
        ..._oldQuery,
      },
      newDeductionQuery: {
        ..._newDeductionQuery,
      }
    }, () => {
      this.handleFetchStudentList();
    });
  }
  
  // 重置搜索条件
  handleReset = () => {
    const { newQuery, oldQuery } = this.state;
    this.setState({
      newQuery: {
        ...DEFAULT_NEW_QUERY,
        status: newQuery.status
      },
      oldQuery: {
        ...DEFAULT_OLD_QUERY,
        status: oldQuery.status
      },
      newDeductionQuery: {
        ...DEFAULT_NEW_DEDUCTION_QUERY
      }
    }, () => {
      this.handleFetchStudentList();
    })
  }

  // 勾选学员
  handleSelect = (studentIds, consumeStudentList = [], savedSelectedRows) => {
    const { studentType } = this.props;
    const _studentIds = _.uniq([].concat(studentIds));
    const _consumeStudentList = _.uniq([].concat(consumeStudentList));
    this.setState({
      savedSelectedRows,
      studentIds: _studentIds,
      consumeStudentList: studentType === 'DEDUCTION' ? _consumeStudentList : this.state.consumeStudentList
    });
  }

  // 确定选择学员
  handleSelectDone = () => {
    const { studentIds, consumeStudentList, excludeIds, savedSelectedRows } = this.state;
    if (!_.isEqual(studentIds, excludeIds)){
      this.props.onSelect(studentIds, consumeStudentList, savedSelectedRows);
    } else {
      message.warning('请选择学员')
    }
  }

  render() {
    const {
      type,
      after,
      showTabs,
      studentType,
      studentList,
      savedSelectedRows
    } = this.props;
    const {
      newQuery,
      oldQuery,
      newDeductionQuery,
      totalCount,
      studentIds,
      excludeIds,
      allstudentList,
      consumeStudentList
    } = this.state;

    const { status: newStatus } = newQuery;
    const { status: oldStatus } = oldQuery
    const status = isNewVersion ? newStatus : oldStatus;

    const query = isNewVersion ? studentType === 'DEDUCTION' ? newDeductionQuery : newQuery : oldQuery;

    return (
      <Modal
        title="选择学员"
        visible={true}
        width={720}
        onCancel={this.props.close}
        className="livecourse__select-student-modal"
        onOk={this.handleSelectDone}
      >

        {
          showTabs &&
          <Radio.Group
            onChange={this.handleChangeStatus}
            value={status}
          >
            <Radio.Button value={isNewVersion ? 'POTENTIAL' : 2}>潜在学员</Radio.Button>
            <Radio.Button value={isNewVersion ? 'NORMAL' : 1}>在读学员</Radio.Button>
            <Radio.Button value={isNewVersion ? 'HISTORY' : 4}>历史学员</Radio.Button>
          </Radio.Group> 
        }

        {
          studentType === 'DEDUCTION' &&
          <div className="show-tips">
            <ShowTips message="只支持选择有剩余课时的在读学员" />
          </div>
        }

        <FilterContent
          type={type}
          query={query}
          studentType={studentType}
          onReset={this.handleReset}
          onChange={this.handleChangeQuery}
        />

        <StudentList
          type={type}
          after={after}
          query={query}
          savedSelectedRows={savedSelectedRows}
          studentType={studentType}
          allstudentList={allstudentList}
          totalCount={totalCount}
          studentIds={studentIds}
          excludeIds={excludeIds}
          studentList={studentList}
          consumeStudentList={consumeStudentList}
          onSelect={this.handleSelect}
          onChange={this.handleChangeQuery}
        />
      </Modal>
    )
  }
}

export default SelectStudent;