import React from 'react';
import {Table, Modal,Input} from 'antd';
import { PageControl } from "@/components";
import CourseService from "@/domains/course-domain/CourseService";
import PlanService from "@/domains/plan-domain/planService";
import User from '@/common/js/user'
import './RelatedPlanModal.less';
import _ from "underscore";
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,totalCount} = 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;
        item.taskId  = selectPlanList[key].taskBaseVOList[0].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){
        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="icon iconfont tip">&#xe6f2;</span>
            <span className="text">已选择{this.getSelectLength(selectPlanList)}个任务</span>
            <span className="clear" onClick={this.clearSelect}>清空</span>
          </div>
          <div>
            <Table
              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>
                            <Table
                              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) => {
                                  // let _list = [];
                                  // if (selected) {
                                  //     _list = _.uniq(selectVideo.concat(changeRows), false, (item) => item.id);
                                  // } else {
                                  //     _list = _.reject(selectVideo, (item) => _.find(changeRows, (data) => data.id === item.id));
                                  // }
                                  // this.setState({selectVideo:_list});
                                },
                              }}
                            />
                      </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}
                  toPage={(page) => {
                    const _query = {...query, current: page + 1};
                    this.setState({
                      query:_query
                    },()=>{ this.handleFetchDataList()})
                  }}
                  onShowSizeChange={this.onShowSizeChange}
                />
              </div>
            }
          </div>
        </Modal>
    )
  }
}

export default RelatedPlanModal;