import React, { Component } from 'react';
// import { withRouter } from 'dva/router';
import SearchForm from './SearchForm';
// import PartmentButton from '../../../../components/PartmentButton';
import ExcelButtonOline from '../../../../components/ExcelButtonOline';
import PTable from '../../../../components/Pro/PTable';
import styles from './person.less';
import { TreeSelect, Alert, Table,Message, LocaleProvider } from 'antd';
import {
  taskGetStepThreeDetail,
  getTaskChargePer,
  getTreeperBydepart,
  updateTaskChargePer,
  removeTaskPer,
  addTaskPer
} from '../../../../services/api';
import zh_CN from "antd/lib/locale-provider/zh_CN";
import { checkMember } from '../../../../utils/utils';
import $nModal from "../../../../utils/modal/nModal"
import $perModal from "../../../../utils/modal/perModal"
import {
  Modal,
  Button
} from "antd";
import PersonRecord from './personRecord';
// @withRouter
export default class Uninsured extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      forceUpdate: false,
      pageParm: { //任务列表请求参数
        pageSize: '10',
        pageNumber: '1'
      },
      paramsInit: false, //参数是否准备好

      // treeData: [], //部门树
      taskPerArray: [],  //驻勤人员
      chargeInfo: null,  //任务详情

      selectedRowKeys: [],
      selectedRows: [],
      treePerIds: [],
    }
  }


  componentWillReceiveProps(props) {
    const { comTaskId, visible } = props;
    if(comTaskId && visible) {
      this._getTaskChargePerInfo(comTaskId);
      this.setState({
        pageParm: {
          ...this.state.pageParm,
          comTaskId
        }
      });
      taskGetStepThreeDetail({comTaskId}).then(res => {
        if(res) {
          this.setState({
            taskPerArray: res.data.taskPerArray
          });
        }
      });
    }
  }
  componentDidMount() {
    // getTreeperBydepart().then(
    //   response => {
    //     const responseData = checkMember(response.data);
    //     this.setState({ treeData: responseData });
    //   }
    // );
  }
  _getTaskChargePerInfo(comTaskId) {
    getTaskChargePer({ comTaskId }).then(
      response => {
        // const {
        //   chargePerId,
        //   chargePerName,
        //   taskPerArray
        // } = response.data;

        // this.setState({
        //   chargePerId,
        //   chargePerName,
        //   taskPerArray
        // });
        this.setState({
          chargeInfo: response.data
        });
        if (response.data) {
          
        }else {
          // Message.warning("该任务没有负责人，暂时无法查看")
          // this.props.onCancel && this.props.onCancel();
        }
      }
    );
  }
  _updateTable = () => {
    this.setState({
      forceUpdate: true,
      selectedRowKeys: [] // 重置选中项
    }, () => {
      this.setState({
        forceUpdate: false
      });
    });
  }
  _search = (values) => {
    this.setState({
      pageParm: {
        ...this.state.pageParm,
        ...values
      },
      paramsInit: true
    });
  }
  _renderConflictPerList = (conflictPerList, tableId) => {
    conflictPerList = conflictPerList.map((item, index) => {
      item.number = index + 1;
      return item;
    });
    const columns = [
      {
        title: '序号',
        dataIndex: 'number',
        key: 'number',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone',
      },
      {
        title: '已安排的驻勤点名称及负责人信息',
        dataIndex: 'taskInfos',
        key: 'taskInfos',
      },
    ];
    return (
      // <TableCon>
        <Table
          dataSource={conflictPerList}
          columns={columns}
          pagination={{ pageSize: 10 }}
        />
      // </TableCon>
    );
  }
  render() {
    const { chargeInfo, taskPerArray } = this.state;
    let rowSelection = null;
    if(this.props.taskStatusValue != '-1') {
      rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          this.setState({
            selectedRowKeys,
            selectedRows
          });
        },
        selectedRowKeys: this.state.selectedRowKeys
      };
    }
    const columns = [
      {
        title: '姓名',
        dataIndex: 'perName',
        key: 'perName'
      },
      {
        title: '所属部门',
        dataIndex: 'orgName',
        key: 'orgName'
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo'
      },
      {
        title: '手机号码',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone'
      },
      {
        title: '保安资格证号',
        dataIndex: 'bayzgzh',
        key: 'bayzgzh'
      },
      {
        title: '投保状态',
        dataIndex: 'tbzt',
        key: 'tbzt'
      },
    ]
    // if(chargeInfo) {
      return (
        <Modal
          destroyOnClose={true}
          title={`${this.props.taskName}-驻勤人员管理`}
          visible={this.props.visible}
          footer={null}
          width={'80%'}
          onCancel={this.props.onCancel}
        >
          <div className={styles.main_info}>
            <i>*</i>
            <span>驻勤负责人:</span> 
            {
              chargeInfo?<span>{chargeInfo.name}({`${chargeInfo.idCardNo} | ${chargeInfo.mobilePhone}`})</span>:'--'
            }
            {
              this.props.taskStatusValue != '-1' &&
              <Button 
                // disabled={this.props.taskStatusValue == '2' || this.props.taskStatusValue == '4' || this.props.taskStatusValue == '7'}
                type="primary" onClick={() => {
                $perModal({
                  type: 'radio',
                  fetchType: 'task',//驻勤的模块
                  value: [{
                    name: chargeInfo&&chargeInfo.name,
                    idCardNo: chargeInfo&&chargeInfo.idCardNo,
                    mobilePhone: chargeInfo&&chargeInfo.idCardNo,
                  }],
                  onOk: (values, close) => {
                    if(values[0]) {
                      const chargePerId = values.map(item => item.perId).join(',');
                      const { comTaskId } = this.state.pageParm;
                      updateTaskChargePer({ comTaskId, chargePerId }).then(res => {
                        close();
                        this._getTaskChargePerInfo(comTaskId);
                      });
                    }else {
                      close();
                    }
                  }
                });
              }}>修改</Button>
            }
          </div>
          <SearchForm 
            style={{ marginLeft: 10 }}
            onSearch={this._search}
          />
  
          <div className={styles.btns}>
            {
              this.props.taskStatusValue != '-1' &&
              <>
              <Button disabled={this.props.taskStatusValue == '2' || this.props.taskStatusValue == '4' || this.props.taskStatusValue == '7'} type="primary" onClick={() => {
              $perModal({
                fetchType: 'task',//驻勤的模块
                onOk: (values, close) => {
                  if(values.length <= 0) {
                    return Modal.warning({
                      title: '温馨提示',
                      content: '请选择人员'
                    });
                  }
                  const { comTaskId } = this.state.pageParm;
                  const petIds = values.map(item => item.perId).join(',');
                  addTaskPer({petIds, comTaskId}).then((res) => {
                    close();
                    const conflictPerList = res.data.conflictPerList;
                    if(res.data.conflictPerList.length>0){//如果有存在重复的人员，再显示弹窗
                        $nModal({
                        width: 650,
                        title: '存在重复安排驻勤点人员',
                        footer: null,
                        content: (
                          <div>
                            <p style={{color: 'orange'}}>
                              以下人员已被安排在其他驻勤点中，无法再被安排；若需要调整，请先到其他驻勤点移除该人员。
                            </p>
                            {this._renderConflictPerList(conflictPerList)}
                          </div>
                        ),
                      });
                    }
                    // 更新人员列表
                    this._updateTable();
                    // 更新任务列表
                    this.props.updateTable && this.props.updateTable();
                  });
                }
              })
            }}>添加</Button>
                   <Button type="danger"
              disabled={this.props.taskStatusValue == '2' || this.props.taskStatusValue == '4' || this.props.taskStatusValue == '7'}
              onClick={() => {
                const { selectedRows } = this.state;
                if(selectedRows.length == 0) {
                  return Modal.warning({
                    title: '温馨提示',
                    content: '请选择人员'
                  });
                }else {
                  Modal.confirm({
                    title: '即将移除人员',
                    content: '人员移除后，今日排班的打卡记录及之后的排班信息将被删除。是否继续？',
                    okText: '继续',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                      const { comTaskId } = this.state.pageParm;
                      const perIdArray = selectedRows.map(item => {
                        return item.perId
                      });
                      const petIds = perIdArray.join(',');
                      removeTaskPer({petIds, comTaskId}).then(() => {
                        // 更新人员列表
                        this._updateTable();
                        // 更新任务列表
                        this.props.updateTable && this.props.updateTable();
                      });
                    }
                  });
                }
                
              }}
            >移除</Button>
              </>
            }
            
     
            <ExcelButtonOline 
              params={this.state.pageParm}
              apiurl={'/task/export-task-per'} 
              downloadname={'驻勤人员管理表格'}
            >
              导出
            </ExcelButtonOline>
            <Button type='primary' onClick={()=>{
              // this.setState
              PersonRecord({
                comTaskId:this.props.comTaskId
              })
            }}>人员安排记录</Button>
          </div>

          {
            this.state.paramsInit &&
            <LocaleProvider locale={zh_CN}>

              <PTable
                style={{ marginTop: 10 }}
                columns={columns}
                url="taskGetTaskPer"
                pageParm={this.state.pageParm}
                forceUpdate={this.state.forceUpdate}
                rowSelection={rowSelection}
                pagination={{ showTotal: total => `总共 ${total} 条` }}
              />
            </LocaleProvider>
          }

        </Modal>
      );
    // }
  }
}
