import React, { Component } from 'react';
import moment from 'moment';
import "moment/locale/zh-cn";
import { connect } from 'dva';
import store from 'store';
import axios from 'axios';
import $loading from '../../../utils/loading';
import { withRouter } from 'react-router-dom';
import {
  Form,
  Input,
  Calendar,
  Badge,
  Radio,
  Button,
  Icon,
  Table,
  DatePicker,
  Tabs,
  Message,
  Popconfirm,
  message,
  Modal,
  Alert,
  Upload,
  notification
} from 'antd';
import LetterElment from '../../../components/LetterElment';
import * as ajax from '../../../services/api';
import { getFormatDate } from '../../../utils/utils';

import NewShift from '../../../routes/AttendanceManagement/NewShift';
import '../Task.less';
import PTable from '../../../components/Pro/PTable';

const FormItem = Form.Item;
const { Search } = Input;
const { TabPane } = Tabs;
const monthFormat = 'YYYY-MM';
const { MonthPicker } = DatePicker;
// const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const { confirm } = Modal;
const dateFormat = 'YYYY-MM-DD';
const currentDate = moment().format('YYYY-MM');

@withRouter
@Form.create()
@connect()
export default class TaskDetailBasicInfomation extends Component {
  state = {
    whetherToEdit: true, //点击编辑按钮时的反应。12-4，去掉编辑，默认就是编辑按钮后的展示
    popconfirmVisible: {}, //用于手动控制浮层显隐,Popconfirmz组件是否显示
    popconfirmVisible1: {}, //深拷贝后的暂存数据
    endDate: '', //循环截止日期，周期排班设置
    initPopValue: '', //单元格点击的初始值，是否修改比较用
    date: currentDate, //测试的月份
    dateValue: 0, //某年某月的天数
    dataValueArray: [],
    comTaskId: this.props.comTaskId, //驻勤的id
    shiftAliasAlphaMap: '', //返回班次的英文别名，如 A,B,C
    shiftList: [], //返回班次的信息
    cycleList: [], //返回周期的信息
    allCycleDetailMap: {}, //排班周期id所对应的的每天班次名称
    perShiftAllMap: [], //排班人员的本月排班情况
    checkedValues: [], //某一个排班的选中情况
    radioChecked: '', //周期排班选中情况的值
    monthChangeTip: false, //切换月份是否需要提示
    cancelChangeTip: false, //点击取消时是否需要提示
    personMessage: '', //人员投保提示信息，
    personMessageArr: [], //人员投保提示信息,成员名单
    personMessageVisible: false, //人员投保提示信息Modal
    addExistingShiftVisible: false, // 添加已有班次
    deleteVisible:false,//移除班次
    errFile: null,
    pagenav: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: total => `总共 ${total} 条`,
      onShowSizeChange: (current, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        // pagenav.current = current;
        pagenav.current = 1;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav }, () => this.searchContent());
      },
      onChange: (page, pageSize) => {
        const pagenav = Object.assign({}, this.state.pagenav);
        pagenav.current = page;
        pagenav.pageSize = pageSize;
        this.setState({ pagenav }, () => this.searchContent());
      },
      total: 0
    },
    resetMonth: '', //具体重置月份
    startDateValue: '', //驻勤开始时间
    endDateValue: '', //驻勤结束时间
    turnOutType: '1', // 驻勤出勤方式，默认为固定班制
    loading: true, // 表格是否时loading状态
    taskComShiftData: [], //班次列表

    comInfo: { comTaskId: "" },
    //添加已有班次
    pbzDataSourceCache: {
      comShifts: [],
      returnComTaskSchedulCycleList: [],
      returnComTaskAttendAddressList: []
    },
    addressRange: '300',
    attendType: '2',

    // 新增班次
    addShiftVisible: false,
    noSchedulShiftListTotal:null,//未排班数量

    // selectedRowKeys: [],
  };

  componentDidMount() {
    this._init();
  }
  componentWillReceiveProps(props) {
    if (props.visible && props.comTaskId) {
      this.setState({
        comTaskId: props.comTaskId,
        pagenav: {
          ...this.state.pagenav,
          current: 1,
          pageSize: 10
        }
      }, () => {
        this._init();
      });
    }
  }
  _init = () => {
    this.getDateAndMonth(); //得到当前的年月
    this.renderTaskGetTaskById(); //获得驻勤的开始结束时间，做不可点击作用
    this.renderInPeriodAndResetMonthData(); //当查看模式下切换月份时要获取的数据
    this.taskPerShiftListShift(() => {
      this._getTaskComShiftPage();
    }); //获得驻勤的班次和排班周期
    this.taskComTaskPer();//获得人员指定月的排班情况
    this.getTaskGetTaskUnInsPerInfoList(); //获取驻勤未进行投保人员列
    this._getTaskDetail();
  }
  _getTaskDetail() {
    //驻勤详情
    ajax.taskGetStepTwoDetail({ comTaskId: this.state.comTaskId }).then(res => {
      const { PBZ } = res.data;
      this.setState({
        pbzDataSourceCache: PBZ
      });
      // if(PBZ && Object.prototype.toString.call(PBZ.comShifts).slice(8, -1) == 'Array') {
      //   this.setState({
      //     selectedRowKeys: PBZ.comShifts.map(val => val.shiftId)
      //   });
      // }
      if (
        PBZ.returnComTaskAttendAddressList &&
        PBZ.returnComTaskAttendAddressList.length
      ) {
        this.setState({
          addressRange: PBZ.returnComTaskAttendAddressList[0].addressRange,
          attendType: PBZ.attendType
        });
      }
    });
  }
  // 获取添加班次按钮里面的列表
  _getTaskComShiftPage = () => {
    ajax.taskComShiftPage({ pageSize: 5000, pageNumber: 1, shiftType: 2 }).then(
      ({ data: { data = [] } }) => {
        const { shiftList } = this.state;
        data = data.map(val => ({ ...val, ...{ key: val.shiftId } }));
        // 过滤掉已经添加的班次
        const filterArr = data.filter(val => !shiftList.some(item => item.shiftId == val.shiftId));
        this.setState({ taskComShiftData: filterArr });
      },
      err => {
        console.log(err, 'taskComShiftPage-获取班次分页查询-err');
      }
    );
  }
  getDateAndMonth = () => {
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = month < 10 ? '0' + month : month;
    const mydate = year.toString() + '-' + month.toString();
    const dateValue = this.getDaysInOneMonth(year, month);
    this.renderDateArray(dateValue);
    this.setState({
      date: mydate,
      dateValue
    });
  };

  renderDateArray = sValue => {
    const sWed = [];
    for (let i = 1; i <= sValue; i++) {
      i = i < 10 ? '0' + i.toString() : i.toString();
      sWed.push(i);
    }
    sWed.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
    this.setState(
      {
        dataValueArray: sWed
      },
      () => {
        const popData = this.renderTableHeadList();
        this.setState({
          popData
        });
      }
    );
  };

  // 表格单元格点击是否开启pop
  openPopconfirm = id => {
    let { popconfirmVisible } = this.state;
    const popconfirmVisible1 = JSON.parse(JSON.stringify(popconfirmVisible));
    popconfirmVisible1[id] = true;
    this.setState({
      popconfirmVisible1
    });
  };

  //获取驻勤未进行投保人员列
  getTaskGetTaskUnInsPerInfoList = () => {
    ajax
      .getTaskGetTaskUnInsPerInfoList({ comTaskId: this.state.comTaskId })
      .then(data => {
        if (data.data && data.data.length !== 0) {
          const responseData = data.data;
          const personMessage = `有${
            responseData.length
            }个驻勤成员未购买保险,执行驻勤可能存在风险，请点击【金融保险】购买保险保障。`;

          let num = 1;
          const personMessageArr = responseData.map(v => {
            return {
              name: v,
              id: num++
            };
          });
          this.setState({
            personMessage,
            personMessageArr
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  };


  taskPerShiftListShift = (cb) => {
    ajax
      .taskComTaskPerShiftListShift({ comTaskId: this.state.comTaskId })
      .then(data => {
        if (data.data) {
          this.setState({
            shiftAliasAlphaMap: data.data.shiftAliasAlphaMap || {},
            shiftList: data.data.shiftList || [],
            cycleList: data.data.cycleList || [],
            allCycleDetailMap: data.data.allCycleDetailMap || {}
          }, () => {
            cb && cb();
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  };

  taskComTaskPer = () => {
    this.setState({
      loading: true
    });
    ajax
      .taskComTaskPerShiftListPerShift({
        month: this.state.date,
        comTaskId: this.state.comTaskId
      })
      .then(data => {
        if (data.data.perShiftAllMap.length > 0) {
          this.setState({
            perShiftAllMap: data.data.perShiftAllMap,
            whetherToEdit: true
          });
        }else {
          this.setState({
            perShiftAllMap: []
          });
        }
        this.setState({
          loading: false
        });
      })
      .catch(err => {
        this.setState({
          loading: false
        });
      });
  };

  renderInPeriodAndResetMonthData = () => {
    ajax
      .taskComTaskPerShiftPagePerShift({
        comTaskId: this.state.comTaskId,
        key: '',
        month: this.state.date,
        pageSize: '10',
        pageNumber: '1'
      })
      .then(data => {
        if (data.data) {
          this.setState({
            isInPeriod: data.data.isInPeriod,
            isResetMonth: data.data.isResetMonth,
            resetMonth: data.data.resetMonth
          });
        }
        if (data.data.resetMonth !== '') {
          let sValYears = data.data.resetMonth.slice(0, 4);
          let sValMonth = data.data.resetMonth.slice(5);
          let dateValue = this.getDaysInOneMonth(sValYears, sValMonth);
          this.renderDateArray(dateValue);
          this.setState(
            {
              date: data.data.resetMonth,
              dateValue: dateValue
            },
            () => {
              this.taskComTaskPer(); //获得人员指定月的排班情况
            }
          );
        }
      })
      .catch(err => {
        console.log(err, 'renderInPeriodAndResetMonthData');
      });
  };

  renderTaskGetTaskById = () => {
    ajax
      .taskGetTaskById({
        comTaskId: this.state.comTaskId
      })
      .then(data => {
        if (data.data) {
          this.setState({
            startDateValue: data.data.startDate,
            endDateValue: data.data.endDate,
            turnOutType: data.data.attendType
          });
        }
      })
      .catch(err => {
        console.log(err, 'renderTaskGetTaskById');
      });
  };

  //获得某年某月的天数
  getDaysInOneMonth = (year, month) => {
    month = parseInt(month, 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  };

  getListData = value => {
    let listData;
    switch (value.date()) {
      case 8:
        listData = [
          { type: 'warning', content: 'This is warning event.' },
          { type: 'success', content: 'This is usual event.' }
        ];
        break;
      case 10:
        listData = [
          { type: 'warning', content: 'This is warning event.' },
          { type: 'success', content: 'This is usual event.' },
          { type: 'error', content: 'This is error event.' }
        ];
        break;
      case 15:
        listData = [
          { type: 'warning', content: 'This is warning event' },
          { type: 'success', content: 'This is very long usual event。。....' },
          { type: 'error', content: 'This is error event 1.' },
          { type: 'error', content: 'This is error event 2.' },
          { type: 'error', content: 'This is error event 3.' },
          { type: 'error', content: 'This is error event 4.' }
        ];
        break;
      default:
    }
    return listData || [];
  };

  getMonthData = value => {
    if (value.month() === 8) {
      return 1394;
    }
  };

  monthCellRender = value => {
    const num = this.getMonthData(value);
    return num ? (
      <div className='notes-month'>
        <section>{num}</section>
        <span>Backlog number</span>
      </div>
    ) : null;
  };

  dateCellRender = value => {
    const listData = this.getListData(value);
    return (
      <ul className='events'>
        {listData.map(item => (
          <li key={item.content}>
            <Badge status={item.type} text={item.content} />
          </li>
        ))}
      </ul>
    );
  };

  //时间年月的变化
  dateValueChange = (date, dateString) => {
    console.log(dateString, '右侧时间年月的变化');
    this.setState(
      {
        date: dateString
      },
      () => {
        ajax
          .taskComTaskPerShiftPagePerShift({
            comTaskId: this.state.comTaskId,
            key: '',
            month: dateString.toString(),
            pageSize: '10',
            pageNumber: '1'
          })
          .then(data => {
            if (
              data.data.isInPeriod === '1' &&
              data.data.perShiftAllMap.length <= 0
            ) {
              message.warning('该月暂无排班数据，请点击单元格开始排班');
              return;
            }
            if (data.data.isResetMonth === '1') {
              message.warning('已超过驻勤期间范围，默认重置为驻勤的截止月');
              const sd = this.state.resetMonth;
              this.setState({
                date: sd
              });
              return;
            }
            if (data.data) {
              this.setState({
                isInPeriod: data.data.isInPeriod,
                isResetMonth: data.data.isResetMonth,
                resetMonth: data.data.resetMonth
              });
            }
            if (data.data.resetMonth !== '') {
              let sValYears = data.data.resetMonth.slice(0, 4);
              let sValMonth = data.data.resetMonth.slice(5);
              let dateValue = this.getDaysInOneMonth(sValYears, sValMonth);
              this.renderDateArray(dateValue);
              this.setState(
                {
                  date: data.data.resetMonth,
                  dateValue: dateValue
                },
                () => {
                  this.taskComTaskPer(); //获得人员指定月的排班情况
                }
              );
            }
          })
          .catch(err => {
            console.log(err, 'renderInPeriodAndResetMonthData');
          });
      }
    );

    // 需求更改，pop确定直接保存，没有中间表，上面代码代替
    // if (this.state.monthChangeTip && !this.state.whetherToEdit) {
    //   let _this = this;
    //   confirm({
    //     title: '您当前修改的信息未保存，确认切换？',
    //     okText: '保存并切换',
    //     cancelText: '直接切换',
    //     onOk() {
    //       _this.saveAndSwitch();
    //       _this.getNewMonthData(dateString);
    //     },
    //     onCancel() {
    //       _this.getNewMonthData(dateString);
    //     }
    //   });
    // } else {
    //   this.getNewMonthData(dateString);
    // }
  };

  getNewMonthData = dateString => {
    ajax
      .taskComTaskPerShiftPagePerShift({
        comTaskId: this.state.comTaskId,
        key: '',
        month: dateString.toString(),
        // pageSize: '10',
        // pageNumber: '1'
        pageSize: this.state.pagenav.pageSize,
        pageNumber: this.state.pagenav.current
      })
      .then(data => {
        if (
          data.data.isInPeriod === '1' &&
          data.data.perShiftAllMap.length <= 0
        ) {
          message.warning('该月暂无排班数据，请点击【编辑】开始排班');
          return;
        }
        if (data.data.isResetMonth === '1') {
          message.warning('已超过驻勤期间范围，默认重置为驻勤的截止月');
          const sd = this.state.resetMonth;
          this.setState({
            date: sd
          });
          return;
        }
        if (data.data) {
          this.setState({
            resetMonth: data.data.resetMonth,
            perShiftAllMap: data.data.perShiftAllMap || []
          });
        }
        if (data.data.resetMonth !== '') {
          const sValYears = data.data.resetMonth.slice(0, 4);
          const sValMonth = data.data.resetMonth.slice(5);
          const dateValue = this.getDaysInOneMonth(sValYears, sValMonth);
          this.renderDateArray(dateValue);
          this.setState({
            date: data.data.resetMonth,
            dateValue
          });
        }
        this.setState({
          monthChangeTip: false,
          cancelChangeTip: false
        });
      })
      .catch(err => {
        console.log(err, 'getNewMonthData');
      });
  };

  saveAndSwitch = () => {
    ajax
      .taskComTaskPerShiftSetSinglePerShift({
        comTaskId: this.state.comTaskId,
        month: this.state.date
      })
      .then(() => {
        this.setState({
          monthChangeTip: false,
          cancelChangeTip: false
        });
      })
      .catch(err => {
        console.log(err, 'saveAndSwitch');
      });
  };

  renderShiftList = () => {
    return this.state.shiftList.map((val, key) => {
      return (
        <b
          key={key}
          style={{
            display: 'inline-block',
            fontWeight: 'normal',
            padding: '3px 8px'
          }}
        >
          <LetterElment
            name={this.state.shiftAliasAlphaMap[val.shiftId]}
            type='tag'
          />
          <span id={val.shiftId}>{val.shiftAlias}</span>
        </b>
      );
    });
  };

  renderCycleList = () => {
    return this.state.cycleList.map((val, key) => {
      return (
        <div key={key}>
          <p
            className='item b-color-orange'
            style={{ marginTop: '0px', paddingTop: '0px' }}
          >
            {val.cycleAlias}
          </p>
          <p
            className='item b-color-green'
            style={{ marginTop: '0px', paddingTop: '0px' }}
          >
            {val.cycleShiftName}
          </p>
        </div>
      );
    });
  };

  /*
   * 编辑模式
   * */
  //编辑模式下的数据和表头
  renderTableHeadList = () => {
    const columnsData = [];
    this.state.dataValueArray.map((v, k) => {
      columnsData.push({
        title: v,
        dataIndex: this.state.date.toString() + '-' + v,
        key: this.state.date.toString() + '-' + v,
        width: 80,
        render: (text, record, index) => {
          const { popconfirmVisible } = this.state;
          popconfirmVisible[`${v}${record.key}`] = false;
          let isInterval = false; //判断当前时间是否在驻勤期间内
          let startTime = new Date(
            Date.parse(
              this.state.startDateValue.substring(0, 10).replace('-', '/')
            )
          );
          let today = new Date(
            Date.parse(
              getFormatDate()
                .substring(0, 10)
                .replace('-', '/')
            )
          );
          let endTime = new Date(
            Date.parse(
              this.state.endDateValue.substring(0, 10).replace('-', '/')
            )
          );
          let currentTime = new Date(
            Date.parse((this.state.date.toString() + '-' + v).replace('-', '/'))
          );
          if (currentTime >= startTime && currentTime <= endTime) {
            isInterval = true;
          }
          let disable = false;

          if (today > currentTime) {
            disable = true;
          }
          if(this.props.taskStatusValue == 2 || this.props.taskStatusValue == 4 || this.props.taskStatusValue == 7) {
            disable = true;
          }
          const wed = text !== '' && text !== undefined ? text.split(',') : [];
          const content = (
            <Tabs className='popover-paibang' defaultActiveKey='a1'>
              <TabPane tab='排班' key='a1'>
                {/* <CheckboxGroup
                  value={this.state.checkedValues}
                  defaultValue={wed}
                  options={this.renderOptions()}
                  onChange={this.onchangeSchedule}
                /> */}
                <RadioGroup
                  onChange={this.onchangeSchedule}
                  value={this.state.checkedValues.toString()}
                >
                  {this.renderCheckboxDataList()}
                </RadioGroup>
                {/*{wed[0] === '0'?  <p id={`lmb-popover-p-${index}-${k}`} className="lmb-popover-p p-clicked" onClick={this.renderRestClick.bind(this, k, index)}>{this.renderRest()}</p> :*/}
                {/*<p id={`lmb-popover-p-${index}-${k}`} className="lmb-popover-p" onClick={this.renderRestClick.bind(this, k, index)}>{this.renderRest()}</p>}*/}
              </TabPane>
              {this.state.turnOutType === '2' && (this.state.cycleList && this.state.cycleList.length > 0) ? (
                <TabPane tab='周期排班' key='a2'>
                  <RadioGroup
                    onChange={this.onChangeRadioData}
                    value={this.state.radioChecked}
                  >
                    {this.renderRadioDataList()}
                  </RadioGroup>
                  <div style={{ marginTop: '20px' }}>
                    <span>循环截止日期:</span>
                    <div style={{ marginTop: '10px' }}>
                      <DatePicker
                        placeholder='请选择循环截止日期'
                        allowClear={false}
                        value={
                          this.state.endDate === ''
                            ? null
                            : moment(this.state.endDate, dateFormat)
                        }
                        onChange={date => {
                          const endDate = moment(date).format(dateFormat);
                          this.setState({ endDate });
                        }}
                      />
                    </div>
                  </div>
                </TabPane>
              ) : null}
            </Tabs>
          );


          return isInterval ? (
            disable ? (
              <div
                style={{ background: '#ddd' }}
                className='paneltablecolor-list paneltablecolor-list-more'
              >
                {wed[0] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[0]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[1] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[1]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[2] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[2]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[3] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[3]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[4] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[4]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[5] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[5]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[6] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[6]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
                {wed[7] !== undefined ? (
                  <LetterElment
                    name={this.state.shiftAliasAlphaMap[wed[7]]}
                    type='tag'
                  />
                ) : (
                    ''
                  )}
              </div>
            ) : (
                <Popconfirm
                  title={content}
                  trigger='click'
                  okText='确定'
                  cancelText='取消'
                  onConfirm={this.handlePopconfimTask.bind(
                    this,
                    k,
                    index,
                    `${v}${record.key}`
                  )}
                  onCancel={this.handleCancelPopconfimTask.bind(
                    this,
                    `${v}${record.key}`
                  )}
                  onClick={this.renderRestClickLmb.bind(this, k, index)}
                  // 之前开发人员代码，影响循环日期的添加，注释掉
                  // onVisibleChange={visible => {
                  //   !visible ? this.setState({ radioChecked: '' }) : null;
                  // }}
                  visible={this.state.popconfirmVisible1[`${v}${record.key}`]}
                >
                  <div
                    className='paneltablecolor-list'
                    onClick={() => {
                      this.openPopconfirm(`${v}${record.key}`);
                    }}
                  >
                    {wed[0] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[0]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[1] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[1]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[2] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[2]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[3] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[3]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[4] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[4]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[5] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[5]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[6] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[6]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                    {wed[7] !== undefined ? (
                      <LetterElment
                        name={this.state.shiftAliasAlphaMap[wed[7]]}
                        type='tag'
                      />
                    ) : (
                        ''
                      )}
                  </div>
                </Popconfirm>
              )
          ) : (
              <div
                className='paneltablecolor-list paneltablecolor-list-more'
                style={{ background: '#ddd', cursor: 'not-allowed' }}
              />
            );
        }
      });
    });
    columnsData.sort((a, b) => parseInt(a.title, 10) - parseInt(b.title, 10));
    columnsData.splice(0, 0, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 130,
      fixed: 'left'
    });
    /**
     * 需求更改，不需要重置
     */
    // columnsData.push({
    //   title: '操作',
    //   dataIndex: 'cao',
    //   key: 'cao',
    //   render: (text, record, index) => {
    //     return (
    //       <span
    //         className='span_hover'
    //         style={{ fontSize: '12px', color: '#0e6bf2' }}
    //         onClick={this.resetShifts.bind(this, record.perId, index)}
    //       >
    //         重置
    //       </span>
    //     );
    //   },
    //   width: 80,
    //   fixed: 'right'
    // });
    return columnsData;
  };
  renderTableContentList = () => {
    const dataSourceList = this.state.perShiftAllMap.map((v, k) => {
      const value = v;
      value.key = v.perId;
      return value;
    });
    return dataSourceList;
  };

  //弹窗点击确认选择
  handlePopconfimTask = (visible, key, id) => {
       
    const { perId } = this.state.perShiftAllMap[key];
    const s = parseInt(visible, 10) + 1;

    const w_data = s < 10 ? '0' + s.toString() : s.toString();
    const lmb_data = this.state.date + '-' + w_data;

    let taskShiftType;
    let ids;

    //接口请求参数
    let ajaxData = {
      comTaskId: this.state.comTaskId,
      perId: perId,
      date: lmb_data
    };
    if (this.state.checkedValues.length > 0) {
      taskShiftType = 1;
      ids = this.state.checkedValues.toString();

      ajaxData.taskShiftType = taskShiftType;
      ajaxData.ids = ids;
    }

    if (this.state.radioChecked !== '') {
      taskShiftType = 2;
      ids = this.state.radioChecked;

      //周期排班添加循环截止日期值
      ajaxData.taskShiftType = taskShiftType;
      ajaxData.ids = ids;
      ajaxData.endDate = this.state.endDate;
    }

    //未修改禁止提交
    if (this.state.initPopValue === ids && this.state.radioChecked === '') {
      message.warning('班次未修改！');
      return;
    }

    //要是一进来就点击确定
    if (
      this.state.checkedValues.length === 0 &&
      this.state.radioChecked === ''
    ) {
      message.warning('请先选择班次！');
      return;
    }

    // 循环截止日期不能小于所点击日期
    if (taskShiftType === 2 && moment(this.state.endDate).isBefore(lmb_data)) {
      message.warn('请选择不小于所点击的日期！');
      return;
    }

    //对选择的时间段进行是否时间冲突的判断，在提交数据(把时间段取出来进行比较))
    ajax.taskComTaskPerShiftValidateSinglePerShift(ajaxData).then(
      data => {
        const perShiftAllMap = this.state.perShiftAllMap;
        if (this.state.checkedValues.length > 0) {
          perShiftAllMap[key][lmb_data] = this.state.checkedValues.toString();
          this.setState({
            perShiftAllMap,
            // pagenav: {
            //   ...this.state.pagenav,
            //   current: 1,
            //   pageSize: 10,
            // },
            monthChangeTip: true,
            cancelChangeTip: true
          });
        }

        //需求更改，添加循环截止日期，确定保存后直接获取新数据，不需要前端暂时渲染，注释掉
        // const { radioChecked } = this.state;
        // if (radioChecked !== '') {
        //   let s_index;
        //   for (let i in this.state.cycleList) {
        //     if (this.state.cycleList[i].taskSchedulCycleId === radioChecked) {
        //       s_index = i;
        //     }
        //   }
        //   let s_day = this.state.cycleList[s_index].cycleDays;

        //   let differ_date = parseInt(this.state.dateValue - s + 1);

        //   let s_shiftname = this.state.allCycleDetailMap[radioChecked];
        //   let k = 1;
        //   for (let j = 0; j < differ_date; j++) {
        //     let sdf = s + j;
        //     let sdfg_data = sdf < 10 ? '0' + sdf.toString() : sdf.toString();
        //     let erty_data = this.state.date + '-' + sdfg_data;
        //     perShiftAllMap[key][erty_data] = s_shiftname[k];
        //     k++;
        //     if (k === s_day + 1) {
        //       k = 1;
        //     }
        //     this.setState({
        //       perShiftAllMap
        //     });
        //   }
        // }

        //关闭pop
        const { popconfirmVisible1 } = this.state;
        for (const key in popconfirmVisible1) {
          if (key === id) {
            popconfirmVisible1[key] = false;
          }
        }
        this.setState({
          checkedValues: [],
          radioChecked: '',
          l_index: 0,
          l_key: 0,
          monthChangeTip: true,
          cancelChangeTip: true,
          popconfirmVisible1,
          endDate: ''
        });
        
        this.getNewMonthData(this.state.date); //保存成功后刷新，循环截止日期的周期排班
        this.renderTableContentList();
        this.renderTableContentListExamine();
      },
      err => {
        console.log('errerr', err);
      }
    );
  };

  //弹窗点击取消选择
  handleCancelPopconfimTask = id => {
    //关闭pop
    const { popconfirmVisible1 } = this.state;
    for (const key in popconfirmVisible1) {
      if (key === id) {
        popconfirmVisible1[key] = false;
      }
    }
    this.setState({
      checkedValues: [],
      radioChecked: '',
      popconfirmVisible1,
      endDate: ''
    });
    this.renderTableContentList();
    this.renderTableContentListExamine();
  };

  //排班的选择
  // onchangeSchedule = checkedValues => {
  //   if (checkedValues.length > 1 && checkedValues.includes('0')) {
  //     message.error('班次与休息不能同时选中');
  //     checkedValues.splice(checkedValues.length - 1, 1);
  //     this.setState({
  //       checkedValues,
  //       radioChecked: ''
  //     });
  //   } else {
  //     checkedValues.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
  //     this.setState({
  //       checkedValues,
  //       radioChecked: ''
  //     });
  //   }
  // };
  onchangeSchedule = e => {
    const checkedValues = [e.target.value];
    this.setState(
      {
        radioChecked: '',
        checkedValues
      },
      () => {
        console.log(this.state.checkedValues);
      }
    );
  };

  //编辑模式下的排版周期的单选
  onChangeRadioData = e => {
    this.setState({
      radioChecked: e.target.value,
      checkedValues: []
    });
  };

  renderOptions = () => {
    const erty = [];
    this.state.shiftList.map((val, key) => {
      // if(val.shiftId !== '0'){
      erty.push({
        label: (
          <b key={key}>
            <LetterElment
              name={this.state.shiftAliasAlphaMap[val.shiftId]}
              type='tag'
            />
            <span id={val.shiftId}>{val.shiftAlias}</span>
          </b>
        ),
        value: val.shiftId
      });
      // }
    });
    return erty;
  };

  // 监听时间点击事件
  renderRestClickLmb = (visible, key) => {
    let visiblewed = visible + 1;
    let visible1 =
      visiblewed < 10 ? '0' + visiblewed.toString() : visiblewed.toString();
    let dayValue = this.state.date + '-' + visible1;
    let s_value = this.state.perShiftAllMap[key][dayValue]
      ? this.state.perShiftAllMap[key][dayValue].split(',')
      : [];
    this.setState({
      l_index: key,
      l_key: visible,
      checkedValues: s_value, // 日期的值
      initPopValue: s_value.toString()
    });
  };

  resetShifts = (perId, index) => {
    let _this = this;
    confirm({
      title: '您确定取消本次操作？',
      okText: '确定',
      cancelText: '继续排班',
      onOk() {
        _this.resetShiftsData(perId, index);
      },
      onCancel() { }
    });
  };

  resetShiftsData = (perId, index) => {
    ajax
      .taskComTaskPerShiftResetSinglePerShift({
        comTaskId: this.state.comTaskId,
        month: this.state.date,
        perId
      })
      .then(data => {
        const { perShiftAllMap } = this.state;
        if (data.data) {
          const dataMore = data.data.perShiftAllMap[0];
          perShiftAllMap[index] = dataMore;
          this.setState({
            perShiftAllMap,
            checkedValues: '',
            monthChangeTip: false,
            cancelChangeTip: false
          });
        }
      })
      .catch(() => { });
  };

  renderRadioDataList = () => {
    return this.state.cycleList.map((v, k) => {
      return (
        <Radio key={k} value={v.taskSchedulCycleId}>
          <span style={{ whiteSpace: 'pre-wrap' }}>{v.cycleAlias}</span>
        </Radio>
      );
    });
  };

  renderCheckboxDataList = () => {
    return this.state.shiftList.map((v, k) => {
      return (
        <Radio key={k} value={v.shiftId}>
          <LetterElment
            name={this.state.shiftAliasAlphaMap[v.shiftId]}
            type='tag'
          />
          <span style={{ whiteSpace: 'pre-wrap' }}>{v.shiftAlias}</span>
        </Radio>
      );
    });
  };

  /*
   * 查看模式
   * */
  renderTableHeadListExamine = () => {
    const columnsData = [];
    this.state.dataValueArray.map((v, k) => {
      columnsData.push({
        title: v,
        dataIndex: this.state.date.toString() + '-' + v,
        key: this.state.date.toString() + '-' + v,
        width: 80,
        render: (text, record, index) => {
          let isInterval = false; //判断当前时间是否在驻勤期间内
          let startTime = new Date(
            Date.parse(
              this.state.startDateValue.substring(0, 10).replace('-', '/')
            )
          );
          let endTime = new Date(
            Date.parse(
              this.state.endDateValue.substring(0, 10).replace('-', '/')
            )
          );
          let currentTime = new Date(
            Date.parse((this.state.date.toString() + '-' + v).replace('-', '/'))
          );
          if (currentTime >= startTime && currentTime <= endTime) {
            isInterval = true;
          }

          const wed = text !== '' && text !== undefined ? text.split(',') : [];
          return isInterval ? (
            <div className='paneltablecolor-list wed'>
              {wed[0] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[0]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[1] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[1]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[2] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[2]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[3] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[3]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[4] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[4]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[5] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[5]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[6] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[6]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[7] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[7]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[8] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[8]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
              {wed[9] !== undefined ? (
                <LetterElment
                  name={this.state.shiftAliasAlphaMap[wed[9]]}
                  type='tag'
                />
              ) : (
                  ''
                )}
            </div>
          ) : (
              <div
                className='paneltablecolor-list paneltablecolor-list-more'
                style={{ background: '#ddd', cursor: 'not-allowed' }}
              >
                {' '}
              </div>
            );
        }
      });
    });
    columnsData.sort((a, b) => parseInt(a.title) - parseInt(b.title));
    columnsData.splice(0, 0, {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 130,
      fixed: 'left'
    });
    return columnsData;
  };

  renderTableContentListExamine = () => {
    const dataSourceList = this.state.perShiftAllMap.map((v, k) => {
      const value = v;
      value.key = v.perId;
      return value;
    });
    return dataSourceList;
  };

  contains = (arr, obj) => {
    let i = arr.length;
    while (i--) {
      if (arr[i] === obj) {
        return true;
      }
    }
    return false;
  };

  indexOfData = (arr, str) => {
    // 如果可以的话，调用原生方法
    if (arr && arr.indexOf) {
      return arr.indexOf(str);
    }

    let len = arr.length;
    for (let i = 0; i < len; i++) {
      // 定位该元素位置
      if (arr[i] === str) {
        return i;
      }
    }

    // 数组中不存在该元素
    return -1;
  };

  // /* 编辑模式 */
  // renderListPanel = () => {
  //   return (<div className="tabPanel lmb-tabpanel">
  //     <Table pagination={false} bordered dataSource={this.renderTableContentList()} columns={this.renderTableHeadList()} scroll={{ x: parseInt(this.state.dateValue * 205 + 210),y:560 }} />
  //   </div>);
  // };
  //
  // /* 查看模式 */
  // renderExaminePanel = () => {
  //   return (<div className="tabPanel lmb-tabpanel">
  //     <Table pagination={this.state.pagenav} bordered dataSource={this.renderTableContentListExamine()} columns={this.renderTableHeadListExamine()} scroll={{ x: parseInt(this.state.dateValue * 205 + 130) }} />
  //   </div>);
  // };

  /* 日历模式 */
  renderDatePanel = () => {
    return (
      <div className='tabPanel'>
        <Calendar
          className='TaskDetailPersonnelPlacement-Calendar'
          dateCellRender={this.dateCellRender}
          monthCellRender={this.monthCellRender}
        />
        <div className='bj-list'>
          <div className='bj-item b-orange'>
            <div className='bj-top'>
              <div className='item'>
                <span className='color-orange'>A</span>
                班次A: <em>9:00〜10:00</em>
              </div>
              <Button size='small' type='primary' ghost>
                添加人员
              </Button>
            </div>
            <div className='bj-user-list'>
              <div className='bj-user'>
                <Icon type='user' />
                陈小二
              </div>
            </div>
          </div>
          <div className='bj-item g-orange'>
            <div className='bj-top'>
              <div className='item'>
                <span className='color-green'>A</span>
                班次A: <em>9:00〜10:00</em>
              </div>
              <Button size='small' type='primary' ghost>
                添加人员
              </Button>
            </div>
            <div className='bj-user-list'>
              <div className='bj-user'>
                <Icon type='user' />
                陈小二
              </div>

            </div>
          </div>
          <div className='bj-item c-orange'>
            <div className='bj-top'>
              <div className='item'>
                <span className='color-cyan'>A</span>
                班次A: <em>9:00〜10:00</em>
              </div>
              <Button size='small' type='primary' ghost>
                添加人员
              </Button>
            </div>
            <div className='bj-user-list'>

            </div>
          </div>
        </div>
      </div>
    );
  };

  //保存
  saveData = () => {
    ajax
      .taskComTaskPerShiftSetSinglePerShift({
        comTaskId: this.state.comTaskId,
        month: this.state.date
      })
      .then(() => {
        this.setState({
          monthChangeTip: false,
          cancelChangeTip: false,
          whetherToEdit: true
        });
        this.renderDatePanel();
        this.updateClassesValue();
      });
  };

  // 补位日历排班初始值
  updateClassesValue = () => {
    const newClassesValue = this.state.perShiftAllMap;
    newClassesValue.forEach(val => {
      const keyArr = Object.keys(val);
      keyArr.forEach(v => {
        // 处理班次方位内未经初始化的日期为休息状态
        let isInterval = false; //判断当前时间是否在驻勤期间内
        const startTime = new Date(
          Date.parse(
            this.state.startDateValue.substring(0, 10).replace('-', '/')
          )
        );
        const endTime = new Date(
          Date.parse(this.state.endDateValue.substring(0, 10).replace('-', '/'))
        );
        const currentTime = new Date(Date.parse(v.replace('-', '/')));
        if (currentTime >= startTime && currentTime <= endTime) {
          isInterval = true;
          if (isInterval && !val[v]) {
            val[v] = '0';
          }
        }
      });
    });
    this.setState({
      perShiftAllMap: newClassesValue
    });
  };

  //取消
  cancelData = () => {
    if (!this.state.cancelChangeTip) {
      this.taskComTaskPer();
    } else {
      let _this = this;
      confirm({
        title: '您确定取消本次操作？',
        okText: '确定',
        cancelText: '继续排班',
        onOk() {
          _this.taskComTaskPer();
        },
        onCancel() { }
      });
    }
  };

  //点击搜索
  searchContent = sVal => {
    ajax
      .taskComTaskPerShiftPagePerShift({
        comTaskId: this.state.comTaskId,
        key: sVal,
        month: this.state.date,
        pageSize: this.state.pagenav.pageSize,
        pageNumber: this.state.pagenav.current
      })
      .then(data => {
        if (data.data) {
          this.setState({
            perShiftAllMap: data.data.perShiftAllMap,
            pagenav: { ...this.state.pagenav, total: data.data.perList.total }
          });
        }
      });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { personMessage } = this.state;
    //判断是否显示编辑状态或者是查看状态
    let isExamineShow = '';
    let isEditShow = '';
    if (!this.state.whetherToEdit) {
      isExamineShow = 'block';
      isEditShow = 'none';
    } else {
      isExamineShow = 'none';
      isEditShow = 'block';
    }

    return (
      <div className='TaskDetail TaskDetailPersonnelPlacement'>
        <Alert
          message={
            <div>
              排班制排班：出勤类型选择排班制的，需要手动进行排班，请根据您选择的班次及设定的周期在日历表中，对人员进行手动排班。
              {personMessage && (
                <div className='publish-success-info'>
                  {this.state.personMessage && (
                    <div className='specific-info'>
                      {personMessage}
                      <span
                        className='specific-list'
                        onClick={() => {
                          this.setState({
                            personMessageVisible: true
                          });
                        }}
                      >
                        查看名单
                      </span>
                    </div>
                  )}
                </div>
              )}
            </div>
          }
          type='warning'
          showIcon
        />
        {/*<div className="taskdetail-title">*/}
        {/*驻勤名称 <Tag>进行中</Tag>*/}
        {/*</div>*/}
        {/*<Menu current={4} />*/}

        <div className='info'>
          <section>
            <Button disabled={this.props.taskStatusValue == 2 || this.props.taskStatusValue == 4 || this.props.taskStatusValue == 7} style={{ marginTop: 10 }} type="primary" size="small" onClick={() => {
              this.setState({
                addExistingShiftVisible: true
              });
            }}>添加已有班次</Button>
            <Button disabled={this.props.taskStatusValue == 2 || this.props.taskStatusValue == 4 || this.props.taskStatusValue == 7} style={{ marginLeft: 15, marginTop: 10 }} type="primary" size="small" onClick={() => {
              this.setState({
                addShiftVisible: true
              });
              this.props.onCancel && this.props.onCancel();
            }}>添加新班次</Button>
            <Button disabled={this.props.taskStatusValue == 2 || this.props.taskStatusValue == 4 || this.props.taskStatusValue == 7} style={{ marginLeft: 15, marginTop: 10 }} type="primary" size="small" onClick={() => {
              this.setState({
                deleteVisible: true
              });
            }}>移除班次</Button>
          </section>
          <div className='list'>
            <span className='label'>班次：</span>
            {this.renderShiftList()}
          </div>
          <div className='list zlist'>
            <span className='label'>排班周期：</span>
            {this.renderCycleList()}
          </div>
        </div>

        <div className='form'>
          <Form
            onSubmit={this.handleSubmit}
            layout='inline'
            style={{ display: 'flex', alignItems: 'center' }}
          >
            <MonthPicker
              allowClear={false}
              style={{ marginTop: '4px' }}
              value={moment(this.state.date, monthFormat)}
              format={monthFormat}
              onChange={this.dateValueChange}
            />

            {!this.state.whetherToEdit ? (
              <FormItem
                style={{
                  marginRight: '0px',
                  marginLeft: '10px',
                  marginTop: '0px'
                }}
              >
                {getFieldDecorator('address', {
                  rules: [{ message: '请输入搜索内容' }]
                })(
                  <Search
                    placeholder='请输入搜索内容'
                    onSearch={value => this.searchContent(value)}
                    style={{ width: 200 }}
                    enterButton
                  />
                )}
              </FormItem>
            ) : (
                ''
              )}
            {/*<Radio.Group value={this.state.currentTab} className="ant-radio-group-self" >*/}
            {/*<Radio.Button onClick={() => { this.setState({ currentTab: "1" }); }} value="1">日历模式</Radio.Button>*/}
            {/*<Radio.Button onClick={() => { this.setState({ currentTab: "2" }); }} value="2">列表模式</Radio.Button>*/}
            {/*</Radio.Group>*/}


            {/[^247]/.test(this.props.taskStatusValue) &&
              (!this.state.whetherToEdit ? (
                <Button
                  type='primary'
                  ghost
                  style={{ marginLeft: 15 }}
                  onClick={() => {
                    this.setState({
                      whetherToEdit: false
                    });
                  }}
                >
                  编辑
                  </Button>
              ) : (
                  ''
                ))}

            {
              (() => {
                if (this.props.taskStatusValue == '4' || this.props.taskStatusValue == '7' || this.props.taskStatusValue == '2') {
                  return '';
                }
                return (
                  <div style={{ display: 'flex' }}>
                    <span style={{ color: '#F59A23', marginLeft: 15 }}>手动排班：点击人员对应日期即可进行排班；Excel排班:</span>
                    <a href="javascript:void(0)" type="primary" style={{ marginLeft: 15 }}
                      onClick={() => {
                        const QUERY = `comTaskId=${this.state.comTaskId}&month=${this.state.date}`;
                        axios({
                          method: 'get',
                          url: `${ajax.host}/task/com-task-schedul/export?${QUERY}`, //后台请求地址
                          responseType: 'blob',
                          headers: {
                            access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

                          }
                        }).then(data => {
                          if (!data) {
                            return;
                          }
                          let url = window.URL.createObjectURL(data.data);
                          let link = document.createElement('a');
                          link.style.display = 'none';
                          link.href = url;
                          link.setAttribute('download', `任务排班.xlsx`);
                          document.body.appendChild(link);
                          link.click();
                        });
                      }}
                    >
                      <em style={{ fontSize: 10 }}>①</em>
                      下载排班数据
                </a>
                    <span style={{ color: '#F59A23', marginLeft: 15 }}>></span>
                    {(() => {
                      const uploadExcel = {
                        name: 'xfile',
                        action: `${ajax.host}/task/com-task-schedul/import`,
                        headers: {
                          access_token: store.get('saas')['access_token']
                        },
                        showUploadList: false,
                        data: {
                          comTaskId: this.state.comTaskId
                        }
                      };
                      const beforeUpload = file => {
                        $loading.open('导入中，请勿离开此页面');
                        let ifError = true;
                        if (file.name.indexOf('xls') === -1 && file.name.indexOf('xlsx') === -1) {
                          $loading.close();
                          message.error('请上传xlsx文件!');
                          ifError = false;
                        }
                        return ifError;
                      };
                      //上传文件
                      const UploadChange = info => {
                        if (info.file.status === 'uploading') {
                          this.setState({
                            errFile: null
                          });
                          return;
                        }
                        if (info.file.status === 'done') {
                          $loading.close();
                          const { data, msg, retType } = info.file.response;
                          //"retType":"-1"为错误，data会有相应的路径值
                          //"retType":"0"为正确，data为空
                          if (retType === '-1') {
                            this.taskComTaskPer();
                            message.error(msg);
                            this.setState({
                              errFile: data
                            });
                          } else if (retType === '0') {
                            this.taskComTaskPer();
                            message.success(msg);
                          } else {
                            message.error(msg);
                          }
                        }
                      };
                      return <Upload
                        onChange={UploadChange}
                        beforeUpload={beforeUpload}
                        {...uploadExcel}
                        style={{ marginLeft: 15 }}
                      >
                        <a><em style={{ fontSize: 10 }}>②</em>导入排班数据</a>
                      </Upload>
                    })()}
                    {this.state.errFile && <a href="javascript:void(0)" style={{ marginLeft: 15, color: 'red' }} href={this.state.errFile}>点击下载</a>}
                    {/* <Button type="primary" >导入</Button> */}
                  </div>
                );
              })()
            }


          </Form>
          {/*{this.state.currentTab === "1" ? this.renderDatePanel() : this.renderListPanel()}*/}

          {/*{this.state.whetherToEdit ? this.renderExaminePanel() : this.renderListPanel()}*/}

          <div>
            <div className='oneContent' 
              style={{ display: isExamineShow }}
            >
              <div className='tabPanel lmb-tabpanel'>
                <Table
                  pagination={this.state.pagenav}
                  bordered
                  dataSource={this.renderTableContentListExamine()}
                  columns={this.renderTableHeadListExamine()}
                  scroll={{ x: parseInt(this.state.dateValue * 80 + 130) }}
                  loading={this.state.loading}
                />
              </div>
            </div>
            <div className='twoContent' 
              style={{ display: isEditShow }}
            >
              <div className='tabPanel lmb-tabpanel'>
                <Table
                  pagination={this.state.pagenav}
                  bordered
                  dataSource={this.renderTableContentList()}
                  // columns={this.renderTableHeadList()}
                  columns={this.state.popData}
                  scroll={{
                    x: parseInt(this.state.dateValue * 80 + 130),
                    y: 560
                  }}
                />
              </div>
            </div>
          </div>

          {this.state.whetherToEdit ? (
            ''
          ) : (
              <div className='btn-box'>
                <Button onClick={this.cancelData}>取消</Button>
                <Button type='primary' onClick={this.saveData}>
                  保存
              </Button>
              </div>
            )}
        </div>

        {/* 未投保人员名单Modal */}
        <Modal
          title='未投保人员名单'
          visible={this.state.personMessageVisible}
          footer={null}
          closable={false}
          width={600}
        >
          <p>
            有
            <span style={{ color: 'red' }}>
              {this.state.personMessageArr.length}
            </span>
            个驻勤成员<span style={{ color: 'red' }}>未购买保险</span>
            ,执行驻勤可能存在风险，请点击【去投保】购买保险保障。
          </p>
          <div style={{ margin: '30px 0' }}>
            {this.state.personMessageArr.map(val => (
              <span
                key={val.id}
                style={{
                  display: 'inline-block',
                  background: '#ccc',
                  padding: '4px 10px',
                  borderRadius: '4px',
                  margin: '4px 8px'
                }}
              >
                {val.name}
              </span>
            ))}
          </div>
          <div style={{ textAlign: 'center' }}>
            <Button
              style={{ marginRight: '20px' }}
              key='back'
              onClick={() => {
                this.setState({
                  personMessageVisible: false
                });
              }}
            >
              暂不投保
            </Button>
            <Button
              type='primary'
              key='go'
              onClick={() => {
                this.props.history.push(
                  `/insurancemanagement/enterpriseinsurance`
                );
              }}
            >
              去投保
            </Button>
          </div>
        </Modal>

       


        <Modal
          visible={this.state.addExistingShiftVisible}
          title="选择班次"
          width={600}
          className='drawer-box'
          destroyOnClose={true}
          maskClosable={true}
          onCancel={() => {
            this.setState({ addExistingShiftVisible: false });
          }}
          onOk={() => {
            const {
              pbzDataSourceCache: {
                returnComTaskAttendAddressList,
                returnComTaskSchedulCycleList,
                comShifts
              }
            } = this.state;
            if (comShifts.length > 26) {
              message.warning('最多只能选择26个班次！');
              return;
            }
            const { addressRange, attendType, comTaskId } = this.state;
            const shiftIdJson = comShifts.map(val => ({ shiftId: val.shiftId }));
            //设置排班周期
            const comTaskSchedulCycleJson = returnComTaskSchedulCycleList.map(
              ({ cycleName, cycleDays, taskSchedulCycleId, comTaskCycleShift }) => {
                const shiftIdArrayUse = [];
                comTaskCycleShift.map(v => {
                  if (v.shiftId === '') {
                    shiftIdArrayUse.push('-1');
                  } else {
                    shiftIdArrayUse.push(v.shiftId);
                  }
                });
                return {
                  cycleName,
                  cycleDays,
                  taskSchedulCycleId,
                  shiftIdArrayUse
                };
              }
            );
            const changeAddress = arr => {
              return arr.map(val => ({ ...val, ...{ addressRange } }));
            };
            const comTaskAttendAdresses = changeAddress(
              returnComTaskAttendAddressList
            );
            const ajaxPara = {
              comTaskId,
              attendType,
              shiftIdJson: JSON.stringify(shiftIdJson),
              comTaskSchedulCycleJson: JSON.stringify(comTaskSchedulCycleJson),
              comTaskAttendAdresses: JSON.stringify(comTaskAttendAdresses)
            };
            ajax.taskSaveStepTwoDetail(ajaxPara).then(res => {
              if (res.retType == 0) {
                this.setState({ addExistingShiftVisible: false });
                this.taskPerShiftListShift(() => {
                  this._getTaskComShiftPage();
                });
                notification.success({
                  message: '提交成功'
                });
              }
            });
          }}
        >
          <Table
            pagination={{
              defaultPageSize: 8,
              pageSizeOptions: ["8", "12", "16", "20", "25"],
              showSizeChanger: true
            }
            }
            rowSelection={{
              // selectedRowKeys: [...this.state.pbzDataSourceCache.comShifts].map(
              //   val => val.shiftId
              // ),
              // selectedRowKeys: this.state.selectedRowKeys,
              onChange: (selectedRowKeys, selectedRows) => {
                // this.setState({
                //   selectedRowKeys
                // });
                // 把已经添加的班次合并进来
                const selectedRowsArr = [...this.state.shiftList, ...selectedRows];
                const pbzDataSourceCache = { ...this.state.pbzDataSourceCache };

                pbzDataSourceCache.comShifts = selectedRowsArr.map(val => ({
                  shiftId: val.shiftId,
                  shiftName: val.shiftName,
                  shiftRuleTime: val.shiftRuleTime
                }));
                this.setState({ pbzDataSourceCache });
              }
            }}
            columns={[
              {
                title: '班次名称',
                dataIndex: 'shiftName',
                key: 'shiftName'
              },
              {
                title: '出勤时间',
                dataIndex: 'shiftRuleTime',
                key: 'shiftRuleTime',
                render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
              }
            ]}
            dataSource={this.state.taskComShiftData}
          />
        </Modal>
        {
          this.state.addShiftVisible &&
          <NewShift
            modalVisble={this.state.addShiftVisible}
            {...this.props}
            onUpdateShiftPage={() => {
              this._getTaskComShiftPage();
            }}
            onClose={() => {
              this.setState({ addShiftVisible: false });
            }}
          />
        }
        {this.state.deleteVisible&&<Modal
          title='移除班次'
          visible={this.state.deleteVisible}
          width={600}
          onCancel={()=>this.setState({deleteVisible:false})}
          onOk={()=>{
            const _this = this;
            if(_this.state.selectedRows){
              if(_this.state.noSchedulShiftListTotal===1){
                return message.warning("只剩最后一个班次了，请务删除")
              }
              if(_this.state.noSchedulShiftListTotal==_this.state.selectedRows.length){
                return message.warning("请至少留下一个班次")
              }
              Modal.confirm({
                title: '确认删除?',
                okText: '确定',
                cancelText: '取消',
                onOk() {
                  console.log(_this.state.selectedRows)
                  const shiftIdStrs = _this.state.selectedRows.map(item=>{
                    return item.shiftId
                  })
                  ajax.deleteTaskShift({comTaskId:_this.state.comTaskId,shiftIdStr:shiftIdStrs.join(",")}).then(res=>{
                    if(res.retType=='0'){
                      _this.setState({
                        selectedRowKeys:null,
                        selectedRows:null,
                        deleteVisible:false
                      })
                      _this.taskPerShiftListShift(() => {
                        _this._getTaskComShiftPage();
                      });
                    }
                  })
                }
              })
            }else{
              message.error("你还没选中班次")
            }
            }
           
          }
          okText="移除"
        >
          <div> 
            <Alert
              message='只有未被安排过的班次才可以移除，请勾选需要移除的班次并点击移除即可'
              type="warning"
              showIcon
            />
            <PTable
              style={{ marginTop: 20 }}
              columns={[
                {
                  title: '班次名称',
                  dataIndex: 'shiftName',
                  key: 'shiftName'
                },
                {
                  title: '出勤时间',
                  dataIndex: 'shiftRuleTime',
                  key: 'shiftRuleTime',
                }
              ]}
              url="getNoSchedulShiftList"
              pageParm={{pageNumber: 1,pageSize:10,comTaskId:this.state.comTaskId}}
              forceUpdate={false}
              rowSelection={{
                onChange: (selectedRowKeys, selectedRows) => {
                  this.setState({
                    selectedRows,
                    selectedRowKeys
                  });
                },
                selectedRowKeys: this.state.selectedRowKeys
              }}
              dateChange={(value)=>{
                this.setState({
                  noSchedulShiftListTotal:value.total
                })
              }}
            />
          </div>
        </Modal>}
        
      </div>
    );
  }
}
