import User from '@/common/js/user';
import college from '@/common/lottie/college';
import { PageControl, XMTable } from '@/components';
import CourseService from '@/domains/course-domain/CourseService';
import PlanService from '@/domains/plan-domain/planService';
import { Input, Modal } from 'antd';
import React from 'react';
import _ from 'underscore';
import './RelatedPlanModal.less';
const { Search } = Input;
class RelatedPlanModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      size: 10,
      query: {
        current: 1,
      },
      totalCount: 0,
      selectPlanList: {},
    };
  }

  componentDidMount() {
    this.handleFetchDataList();
  }
  // 获取培训计划列表
  handleFetchDataList = () => {
    const { query, size } = this.state;
    const params = {
      ...query,
      size,
      storeId: User.getStoreId(),
    };
    PlanService.getStorePlanAll(params).then((res) => {
      const { result = {} } = res;
      const { records = [], total = 0 } = result;
      this.setState({
        dataSource: records,
        totalCount: Number(total),
      });
    });
  };
  handleChangePlanName = (value) => {
    const { query } = this.state;
    query.planName = value;
    query.current = 1;
    this.setState({
      query,
    });
  };

  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    this.setState(
      {
        size,
      },
      () => {
        this.handleFetchDataList();
      }
    );
  };

  // 请求表头
  parsePlanColumns = () => {
    const columns = [
      {
        title: '培训任务',
        key: 'planName',
        dataIndex: 'planName',
        render: (val, record) => {
          return <span>{val}</span>;
        },
      },
    ];
    return columns;
  };

  parseTaskColumns = (parentIndex) => {
    const columns = [
      {
        title: '任务名称',
        key: 'taskName',
        dataIndex: 'taskName',
        render: (val, record) => {
          return <span>{val}</span>;
        },
      },
    ];
    return columns;
  };
  selectPlanList = (record, selected, planId) => {
    const { selectPlanList } = this.props;
    let _selectPlanList = { ...selectPlanList };

    if (selected) {
      if (!_selectPlanList[planId]) {
        _selectPlanList[planId] = {};
      }
      _selectPlanList[planId].taskBaseVOList = [];
      _selectPlanList[planId].planId = planId;
      _selectPlanList[planId].taskBaseVOList.push(record);
    } else {
      if (!_selectPlanList[planId]) {
        _selectPlanList[planId] = {};
      }
      _selectPlanList[planId].taskBaseVOList = [];
      _selectPlanList[planId].planId = planId;
    }
    this.props.onChange(_selectPlanList);
    // this.setState({selectPlanList:_selectPlanList});
  };
  handleSelectPlanListData(selectPlanList) {
    let _selectPlanList = [];
    for (let key in selectPlanList) {
      let item = {};
      if (selectPlanList[key].taskBaseVOList) {
        item.planId = selectPlanList[key].planId;
        if (selectPlanList[key].taskBaseVOList[0]) {
          item.taskId = selectPlanList[key].taskBaseVOList[0].taskId;
        }
      }
      if (item.taskId) {
        _selectPlanList.push(item);
      }
    }
    return _selectPlanList;
  }
  confirmRelatedPlan = () => {
    const { selectPlanList } = this.props;
    const params = {
      courseId: this.props.selectCourseId,
      relatedPlanList: this.handleSelectPlanListData(selectPlanList),
      storeId: User.getStoreId(),
    };
    CourseService.relatedCourseToPlan(params).then((res) => {
      this.props.onConfirm();
    });
  };
  getSelectLength = (selectList) => {
    let num = 0;
    for (let key in selectList) {
      if (selectList[key].taskBaseVOList.length > 0) {
        num = num + 1;
      }
    }
    return num;
  };
  clearSelect = () => {
    const _selectPlanList = {};
    this.props.onChange(_selectPlanList);
  };
  render() {
    const { size, dataSource, totalCount, query } = this.state;
    const { visible, selectPlanList } = this.props;
    return (
      <Modal
        title='关联培训任务'
        onCancel={this.props.onClose}
        maskClosable={false}
        visible={visible}
        className='related-plan-modal'
        closable={true}
        width={800}
        onOk={() => this.confirmRelatedPlan()}
        closeIcon={<span className='icon iconfont modal-close-icon'>&#xe6ef;</span>}>
        <div className='search-container'>
          <Search
            placeholder='搜索培训任务名称'
            style={{ width: 207 }}
            onChange={(e) => {
              this.handleChangePlanName(e.target.value);
            }}
            onSearch={() => {
              this.handleFetchDataList();
            }}
            enterButton={<span className='icon iconfont'>&#xe832;</span>}
          />
        </div>
        <div className='select-container'>
          <span className='con'>
            <div>
              <span className='icon iconfont tip'>&#xe6f2;</span>
              <span className='text'>已选择{this.getSelectLength(selectPlanList)}个任务</span>
            </div>
            <div>
              <span className='clear' onClick={this.clearSelect}>
                清空
              </span>
            </div>
          </span>
        </div>
        <div>
          <XMTable
            renderEmpty={{
              image: college,
              description: '暂无数据',
            }}
            rowKey={(record) => record.planId}
            className='plan-table'
            dataSource={dataSource}
            columns={this.parsePlanColumns()}
            pagination={false}
            expandedRowRender={(_record, index) => {
              if (!_record.taskBaseVOList) {
                return;
              }
              if (_record.taskBaseVOList.length !== 0) {
                const selectPlan = selectPlanList[_record.planId];
                let taskBaseVOList = [];
                if (selectPlan) {
                  taskBaseVOList = selectPlan.taskBaseVOList;
                }

                console.log('taskBaseVOList', taskBaseVOList);

                return (
                  <div>
                    <XMTable
                      renderEmpty={{
                        image: college,
                        description: '暂无数据',
                      }}
                      rowKey={(record) => record.taskId}
                      pagination={false}
                      dataSource={_record.taskBaseVOList}
                      columns={this.parseTaskColumns(index)}
                      className='child-table'
                      rowSelection={{
                        type: 'checkbox',
                        selectedRowKeys: _.pluck(taskBaseVOList, 'taskId'),
                        onSelect: (record, selected) => {
                          this.selectPlanList(record, selected, _record.planId);
                        },
                        onSelectAll: (selected, _selectedRows, changeRows) => {},
                      }}
                    />
                  </div>
                );
              }
            }}
            rowClassName={(record, index) => {
              if (index % 2 === 0) {
                return 'odd-row';
              } else {
                return 'even-row';
              }
            }}
          />
          {dataSource.length > 0 && (
            <div className='box-footer'>
              <PageControl
                current={query.current - 1}
                pageSize={size}
                total={totalCount}
                size='small'
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 };
                  this.setState(
                    {
                      query: _query,
                    },
                    () => {
                      this.handleFetchDataList();
                    }
                  );
                }}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
        </div>
      </Modal>
    );
  }
}

export default RelatedPlanModal;
