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 TaskCenterService from '@/domains/task-center-domain/TaskCenterService';
import { Input, Modal, Tooltip } 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(),
    };
    TaskCenterService.getStoreTaskAll(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();
      }
    );
  };

  renderTitle = () => {
    return (
      <div className='tip-title'>
        <p>为了不影响学员学习，系统已对数据进行筛选</p>
        <p>1、课程不能直接关联「已发布」的培训任务筛选；</p>
        <p>2、一个课程不能重复出现在同一培训任务中</p>
      </div>
    );
  };

  renderTableTitle = () => {
    return (
      <div>
        <Tooltip title={this.renderTitle()} overlayClassName='table-title-tooltip'>
          培训任务<span className='icon iconfont table-title'>&#xe6f2;</span>
        </Tooltip>
      </div>
    );
  };

  // 请求表头
  parsePlanColumns = () => {
    const columns = [
      {
        title: this.renderTableTitle(),
        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, taskId) => {
    const { selectPlanList } = this.props;
    let _selectPlanList = { ...selectPlanList };

    if (selected) {
      if (!_selectPlanList[taskId]) {
        _selectPlanList[taskId] = {};
      }
      _selectPlanList[taskId].taskBaseVOList = [];
      _selectPlanList[taskId].taskId = taskId;
      _selectPlanList[taskId].taskBaseVOList.push(record);
    } else {
      console.log(_selectPlanList[taskId]);
      if (!_selectPlanList[taskId]) {
        _selectPlanList[taskId] = {};
      }
      _selectPlanList[taskId].taskBaseVOList = [];
      _selectPlanList[taskId].taskId = taskId;
    }
    this.props.onChange(_selectPlanList);
  };
  handleSelectPlanListData(selectPlanList) {
    let _selectPlanList = [];
    for (let key in selectPlanList) {
      let item = {};
      if (selectPlanList[key].taskBaseVOList) {
        item.taskId = selectPlanList[key].taskId;
        if (selectPlanList[key].taskBaseVOList[0]) {
          item.stageId = selectPlanList[key].taskBaseVOList[0].taskId;
        }
      }
      if (item.stageId) {
        _selectPlanList.push(item);
      }
    }
    return _selectPlanList;
  }
  confirmRelatedPlan = () => {
    const { selectPlanList } = this.props;
    const params = {
      courseId: this.props.selectCourseId,
      relatedTaskList: this.handleSelectPlanListData(selectPlanList),
      storeId: User.getStoreId(),
    };
    TaskCenterService.relatedCourseToTask(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;
    console.log('selectPlanListselectPlanListselectPlanListselectPlanListselectPlanList', selectPlanList);
    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.taskId}
            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.taskId];
                let taskBaseVOList = [];
                if (selectPlan) {
                  taskBaseVOList = selectPlan.taskBaseVOList;
                }

                console.log('selectPlan==============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.taskId);
                        },
                        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;
