import React, { Component } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Radio,
  Steps,
  Icon,
  Table,
  Modal,
  message,
  Alert
} from 'antd';
import Drawer from 'react-motion-drawer';
import AddNewShift from '../AddNewShift';
import SetLocation from './SetLocation';
import bcx_utils from '../../../common/bcx_utils';
// import { GenNonDuplicateID } from '../../../utils/utils';
import '../Task.less';
import {
  formItemLayout,
  submitFormLayout,
  formItemLayout1,
  returnComTaskFixedDList,
  pageInit
} from './Constants';
import PZhezhao from '../../../components/Pro/PZhezhao';
import DrawCircleForm from './DrawCircleForm';
import style, { css } from 'styled-components';
import {
  taskComShiftPage,
  taskDeleteAddress,
  taskDeleteSchedulCycle
} from '../../../services/api';

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;

@Form.create()
export default class CreateTaskAttendance extends Component {
  state = {
    open: false, //  固定班次----添加班次
    open1: false, // 排班次----添加班次
    open2: false, // 排班次----添加排班周期
    open3: false, // 固定班次/排班次----新增班次
    visible: false, //添加地点

    gdbzDataSource: {
      //固定班制 详情
      returnComTaskFixedDList, //默认休息 初始化值
      returnComTaskAttendAddressList: []
    },
    //排班制
    pbzDataSource: {
      comShifts: [], //出勤班次
      returnComTaskSchedulCycleList: [], //周期设置
      returnComTaskAttendAddressList: [] //地址列表
    },
    //排班制 缓存
    pbzDataSourceCache: {
      comShifts: [],
      returnComTaskSchedulCycleList: [],
      returnComTaskAttendAddressList: []
    },
    taskComShiftData: [], //所有班次信息

    cursor: 0, //选择要修改的出勤班次 游标位置  ; "all"表示批量修改

    addressRange: '300', //出勤范围

    comTaskId: this.props.comTaskId,

    canEdit: '0', //修改范围 （0全部不可修改，1全部可以修改，2部分可以修改）
    taskStatus: this.props.taskStatus || '' //驻勤状态（0: "未开始",1: "进行中",2: "已完成", //不可修改 3: "已延期",4: "已取消", //不可修改 5: "已暂停",6: "未发布",7: "已结束",）
  };

  componentDidMount() {
    this.props.form.setFieldsValue({ attendType: '2' });

    this.taskComShiftPage(); //请求所有班次
    this.canEditArea();
    this.init();
  }

  init = () => {
    const { dataSource } = this.props;

    const { attendType = '2' } = dataSource;

    this.props.form.setFieldsValue({ attendType });

    const { PBZ, GDBZ } = dataSource;

    //设置排班制或者固定班制
    if (PBZ && PBZ !== '') {
      this.setState({
        pbzDataSource: PBZ,
        pbzDataSourceCache: bcx_utils.jsoncopy(PBZ)
      });
      if (
        PBZ.returnComTaskAttendAddressList &&
        PBZ.returnComTaskAttendAddressList.length
      ) {
        this.setState({
          addressRange: PBZ.returnComTaskAttendAddressList[0].addressRange
        });
      }
    }
    // 未测试
    if (GDBZ && GDBZ !== '') {
      this.setState({ gdbzDataSource: GDBZ });
      if (
        GDBZ.returnComTaskAttendAddressList &&
        GDBZ.returnComTaskAttendAddressList.length
      ) {
        this.setState({
          addressRange: GDBZ.returnComTaskAttendAddressList[0].addressRange
        });
      }
    }

    setTimeout(() => {
      console.log('-----------------进入修改模式-----------------');
      console.log('初始化信息：排班制', this.state.pbzDataSource);
      console.log('初始化信息：固定班制', this.state.gdbzDataSource);
    }, 1000);
  };
  canEditArea = () => {
    //存在typeof canEdit==string的时候，代表是编辑页面，否则是创建页面
    const { canEdit } = this.props;
    console.log(typeof canEdit);
    if (canEdit === '0') {
      message.info('当前页面不可修改', 1.5);
    }
    if (canEdit === '2') {
      message.info('当前页面只有出勤地点可以修改', 1.5);
    }
    this.setState({ canEdit });
  };
  //获取班次分页查询
  taskComShiftPage = () => {
    taskComShiftPage({ pageSize: 5000, pageNumber: 1, shiftType: 2 }).then(
      ({ data: { data = [] } }) => {
        console.log(data, 'taskComShiftPage-获取班次分页查询-response');
        this.setState({ taskComShiftData: data });
      },
      err => {
        console.log(err, 'taskComShiftPage-获取班次分页查询-err');
      }
    );
  };
  //页面提交信息
  handleSubmit = e => {
    e.preventDefault();
    const attendType = '2';
    const { gdbzDataSource, addressRange } = this.state;
    const comTaskId = this.state.comTaskId;
    //批量修改 考勤范围
    const changeAddress = arr => {
      return arr.map(val => ({ ...val, ...{ addressRange } }));
    };
    //消息提示
    const messageTip = (title, resolve) => {
      message.error(title, 1.5, () => {
        window.setTimeout(() => {
          resolve();
        }, 500);
      });
    };
    //出勤地点有效范围 非空判断
    if (parseInt(addressRange) <= 0) {
      bcx_utils.preventRA(resolve => {
        messageTip('出勤地点有效范围必须是大于0的数字', resolve);
      });
      return;
    }

    //固定班制
    if (attendType === '1') {
      if (gdbzDataSource.returnComTaskAttendAddressList.length === 0) {
        bcx_utils.preventRA(resolve => {
          messageTip('出勤地点不能为空', resolve);
        });
        return;
      }

      const {
        gdbzDataSource: {
          returnComTaskFixedDList,
          returnComTaskAttendAddressList
        }
      } = this.state;

      /*
       * 检查是否有重叠的时间
       */
      let preTime = ''; //上一次时间
      const overTimeTip = []; //重叠班次

      //找到指定的时间
      const findTargetTime = (str, type) => {
        if (!str) {
          return;
        }
        const times = str.match(/(\d\d:\d\d)/g);
        if (type === 'first') {
          return times[0];
        }
        if (type === 'last') {
          return times[times.length - 1];
        }
      };
      const isBeforeTime = (t1, t2) => {
        let [s1, s2] = t1.split(':');
        let [s3, s4] = t2.split(':');
        s1 = parseInt(s1);
        s2 = parseInt(s2);
        s3 = parseInt(s3);
        s4 = parseInt(s4);
        return s1 * 60 + s2 < s3 * 60 + s4;
      };

      returnComTaskFixedDList.map((val, key) => {
        if (key === 0) {
          preTime = val.shiftDetails;
        }
        if (key !== 0) {
          const { shiftDetails } = val;
          if (preTime.includes('次日') && !shiftDetails.includes('休息')) {
            const curentTime = findTargetTime(shiftDetails, 'first');
            const pre = findTargetTime(preTime, 'last');
            if (isBeforeTime(curentTime, pre)) {
              overTimeTip.push(key);
            }
          }
          preTime = shiftDetails;
        }
      });
      //如果存在重叠班次
      if (overTimeTip.length !== 0) {
        const tipArr = overTimeTip.map(
          val =>
            bcx_utils.changeWeekData(val + 1) +
            '与' +
            bcx_utils.changeWeekData(val) +
            '排班有时间重叠'
        );
        bcx_utils.preventRA(resolve => {
          messageTip(tipArr, resolve);
        });
        return;
      }

      //（固定班制时必传）固定排班制列表Json化的String串
      const comTaskFixeds = returnComTaskFixedDList.map(
        ({ taskFixedId, weekDay, shiftId }) => ({
          taskFixedId,
          weekDay,
          shiftId
        })
      );
      const comTaskAttendAdresses = changeAddress(
        returnComTaskAttendAddressList
      );

      const ajaxPara = {
        comTaskId,
        attendType,
        comTaskFixeds: JSON.stringify(comTaskFixeds),
        comTaskAttendAdresses: JSON.stringify(comTaskAttendAdresses)
      };

      bcx_utils.preventRA(resolve => {
        this.props.taskSaveStepTwoDetail(ajaxPara, resolve);
      });
    }
    //排班制
    if (attendType === '2') {
      const {
        pbzDataSource: {
          returnComTaskAttendAddressList,
          returnComTaskSchedulCycleList,
          comShifts
        }
      } = this.state;

      if (comShifts.length === 0) {
        bcx_utils.preventRA(resolve => {
          messageTip('出勤班次不能为空', resolve);
        });
        return;
      }
      // 改为非必填，冠男
      // if (returnComTaskSchedulCycleList.length === 0) {
      //   bcx_utils.preventRA(resolve => {
      //     messageTip('周期排班不能为空', resolve);
      //   });
      //   return;
      // }
      if (returnComTaskAttendAddressList.length === 0) {
        bcx_utils.preventRA(resolve => {
          messageTip('出勤地点不能为空', resolve);
        });
        return;
      }
      const comTaskAttendAdresses = changeAddress(
        returnComTaskAttendAddressList
      );

      //设置出勤班次
      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 ajaxPara = {
        comTaskId,
        attendType,
        shiftIdJson: JSON.stringify(shiftIdJson),
        comTaskSchedulCycleJson: JSON.stringify(comTaskSchedulCycleJson),
        comTaskAttendAdresses: JSON.stringify(comTaskAttendAdresses)
      };

      console.log(ajaxPara);

      bcx_utils.preventRA(resolve => {
        this.props.taskSaveStepTwoDetail(ajaxPara, resolve);
      });
    }
  };

  //增加出勤地点
  addArea = (type, [addressLongitude, addressLatitude], address) => {
    const target = this.state[type];

    let selectedAddress = target.returnComTaskAttendAddressList.filter(
      item => item.address === address
    );
    if (selectedAddress.length) {
      message.warning('该地点已被选为出勤地点，请勿重复选择');
      return;
    }
    target.returnComTaskAttendAddressList.push({
      taskAttendAddressId: '',
      address,
      addressLongitude,
      addressLatitude,
      addressRange: '300',
      key: ''
    });
    target.returnComTaskAttendAddressList = target.returnComTaskAttendAddressList.map(
      (val, i) => {
        val.key = i;
        return val;
      }
    );
    this.setState({ [type]: target });
  };
  //修改出勤范围
  addressRangeChange = addressRange => {
    this.setState({ addressRange });
  };
  //删除出勤地点
  deleteLocalItem = (cursor, { taskAttendAddressId, address }) => {
    console.log(cursor);
    console.log(taskAttendAddressId);
    const { attendType = '2' } = this.props.form.getFieldsValue();

    //本地数据删除
    const filterDelete = (data, list) => {
      //固定班制
      if (attendType === '1') {
        const gdbzDataSource = bcx_utils.jsoncopy(this.state.gdbzDataSource);
        const returnComTaskAttendAddressList =
          gdbzDataSource.returnComTaskAttendAddressList;
        // gdbzDataSource.returnComTaskAttendAddressList = returnComTaskAttendAddressList.filter(val => val.taskAttendAddressId !== taskAttendAddressId);
        // this.setState({
        //   gdbzDataSource
        // });
        console.log(
          'gdbzDataSource.returnComTaskAttendAddressList',
          gdbzDataSource.returnComTaskAttendAddressList
        );
        gdbzDataSource.returnComTaskAttendAddressList = returnComTaskAttendAddressList.filter(
          val => val.address !== address
        );
        this.setState({
          gdbzDataSource
        });
      }
      //排班制
      if (attendType === '2') {
        const pbzDataSource = bcx_utils.jsoncopy(this.state.pbzDataSource);
        const returnComTaskAttendAddressList =
          pbzDataSource.returnComTaskAttendAddressList;
        pbzDataSource.returnComTaskAttendAddressList = returnComTaskAttendAddressList.filter(
          // val => val.taskAttendAddressId !== taskAttendAddressId
          val => val.address !== address
        );
        console.log(pbzDataSource.returnComTaskAttendAddressList);
        this.setState({
          pbzDataSource
        });
      }
    };

    const self = this;
    //删除确认框
    Modal.confirm({
      title: '确认删除?',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        // if (taskAttendAddressId.trim() !== '') {
        //   const returnComTaskAttendAddressList = bcx_utils.jsoncopy(
        //     self.state.gdbzDataSource.returnComTaskAttendAddressList
        //   );
        //   //已发布驻勤的考勤地点保留最后一条信息
        //   if (
        //     returnComTaskAttendAddressList &&
        //     returnComTaskAttendAddressList.length > 1
        //   ) {
        //     bcx_utils.preventRA(resolve => {
        //       taskDeleteAddress({ taskAttendAddressId }).then(
        //         data => {
        //           console.log(data);
        //           resolve();
        //           filterDelete();
        //         },
        //         err => {
        //           console.log(err);
        //           resolve();
        //         }
        //       );
        //     });
        //   }
        //   else {
        //     message.info("已发布驻勤最后一条考勤地点不能删除！");
        //   }
        // } else {
        //   filterDelete();
        // }
        filterDelete();
      },
      onCancel() {
        console.log('Cancel');
      }
    });
  };

  /* 固定班次----选择默认班次 */
  fixedShiftRender = () => {
    const { returnComTaskFixedDList = [] } = this.state.gdbzDataSource;

    if (returnComTaskFixedDList.length === 0) {
      return;
    }
    const dataSource = bcx_utils
      .jsoncopy(returnComTaskFixedDList)
      .map((val, key) => ({
        ...val,
        ...{ key }
      }));

    //选择班次信息
    const openDrawfixedShift = cursor => {
      this.setState(
        {
          cursor
        },
        () => {
          this.setState({ open: true });
          console.log('打开抽屉，设置游标：' + this.state.cursor);
        }
      );
    };
    //设置休息
    const rest = index => {
      const gdbzDataSource = { ...this.state.gdbzDataSource };
      gdbzDataSource.returnComTaskFixedDList[index].shiftId = '-1';
      gdbzDataSource.returnComTaskFixedDList[index].shiftDetails = '休息';
      gdbzDataSource.returnComTaskFixedDList[index].isRest = '1';

      this.setState({ gdbzDataSource });
    };
    const columns = [
      {
        title: '工作日',
        dataIndex: 'weekDay',
        key: 'weekDay',
        render: (text, record) => {
          return bcx_utils.changeWeekData(record.weekDay);
        }
      },
      {
        title: '班次详情',
        dataIndex: 'shiftDetails',
        key: 'shiftDetails',
        // width: 200,
        render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
      }
      // {
      //   title: '操作',
      //   dataIndex: 'option',
      //   key: '4',
      //   render: (text, record, index) => (
      //     <div style={{ color: 'rgba(15,113,255,1)' }}>
      //       <span onClick={openDrawfixedShift.bind(this, index)}>选择班次</span>
      //       <span style={{ marginLeft: 10 }} onClick={rest.bind(this, index)}>
      //         休息
      //       </span>
      //     </div>
      //   )
      // }
    ];
    const addOptColumns = [...columns];
    typeof this.props.canEdit === 'string' &&
    this.state.taskStatus !== '0' &&
    this.state.taskStatus !== '6'
      ? ''
      : addOptColumns.push({
          title: '操作',
          dataIndex: 'option',
          key: '4',
          render: (text, record, index) => (
            <div style={{ color: 'rgba(15,113,255,1)' }}>
              <span onClick={openDrawfixedShift.bind(this, index)}>
                选择班次
              </span>
              <span style={{ marginLeft: 10 }} onClick={rest.bind(this, index)}>
                休息
              </span>
            </div>
          )
        });
    return (
      <FormItem {...formItemLayout} label='设置出勤班次'>
        <div>
          {typeof this.props.canEdit === 'string' &&
          this.state.taskStatus !== '0' &&
          this.state.taskStatus !== '6' ? (
            ''
          ) : (
            <Button
              onClick={openDrawfixedShift.bind(this, 'all')}
              style={{ marginBottom: 16 }}
              type='primary'
              ghost
            >
              批量选择班次
            </Button>
          )}
          <Table
            size='middle'
            pagination={false}
            columns={addOptColumns}
            dataSource={dataSource}
          />
        </div>
      </FormItem>
    );
  };

  /* 固定班次--选择班次*/
  renderDrawFixedShift = () => {
    const { open } = this.state;

    //初始化 table 数据
    const taskComShiftData = bcx_utils
      .jsoncopy(this.state.taskComShiftData)
      .map(val => ({ ...val, ...{ key: val.shiftId } }));

    const columns = [
      {
        title: '班次名称',
        dataIndex: 'shiftName',
        key: 'shiftName'
      },
      {
        title: '出勤时间',
        dataIndex: 'shiftRuleTime',
        key: 'shiftRuleTime',
        render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
      }
    ];

    //单选按钮
    const rowSelectionRadio = {
      type: 'radio',
      onChange: (selectedRowKeys, selectedRows) => {
        const { cursor } = this.state;
        const { shiftId, shiftName, shiftRuleTime } = selectedRows[0];
        const gdbzDataSource = bcx_utils.jsoncopy(this.state.gdbzDataSource);

        //批量修改
        if (cursor === 'all') {
          gdbzDataSource.returnComTaskFixedDList = gdbzDataSource.returnComTaskFixedDList.map(
            val => ({
              ...val,
              ...{ shiftId, shiftDetails: shiftName + ': ' + shiftRuleTime }
            })
          );
        }
        //单个修改，根据数组的游标位置，找到指定对象
        if (bcx_utils.objType(cursor) === 'Number') {
          gdbzDataSource.returnComTaskFixedDList[cursor].shiftId = shiftId;
          gdbzDataSource.returnComTaskFixedDList[cursor].shiftDetails =
            shiftName + ': ' + shiftRuleTime;
        }

        this.gdbzDataSourceCache = gdbzDataSource;
      }
    };
    //确定，缓存覆盖
    const confirm = () => {
      this.setState({
        gdbzDataSource: bcx_utils.jsoncopy(this.gdbzDataSourceCache),
        open: false
      });
    };
    const cancel = () => {
      this.setState({
        open: false,
        cursor: 0
      });
      this.gdbzDataSourceCache = null;
    };

    return (
      <Drawer
        overlayColor='rgba(0, 0, 0,0)'
        right
        open={this.state.open}
        noTouchClose
        width={600}
        className='drawer-box'
        onChange={open => {
          this.setState({ open });
        }}
      >
        <div className='drawer'>
          <div className='drawer-header'>
            选择班次
            {/*<Button
              type="primary"
              onClick={() => this.setState({open3: true, open: false})}
              ghost
            >
              新增班次
            </Button>*/}
          </div>
          <div className='drawer-content'>
            {open && (
              <Table
                pagination={pageInit}
                rowSelection={rowSelectionRadio}
                columns={columns}
                dataSource={taskComShiftData}
              />
            )}
          </div>
          <div className='drawer-footer'>
            <Button onClick={cancel}>取消</Button>
            <Button type='primary' onClick={confirm}>
              确定
            </Button>
          </div>
        </div>
      </Drawer>
    );
  };

  //周期性排班下拉
  renderSelect = () => {
    //加载下拉列表
    const taskComShiftData = [...this.state.taskComShiftData];
    console.log('加载下拉列表', taskComShiftData);
    this.state.pbzDataSourceCache.comShifts.map((val, key) => {
      console.log('下拉列表 keys', `${val.shiftId}+${val.shiftName}`);
    });

    const comShifts = bcx_utils.jsoncopy(
      this.state.pbzDataSourceCache.comShifts
    );
    console.log(comShifts, 'comShifts');
    comShifts.push({
      shiftId: '-1',
      shiftName: '休息',
      shiftRuleTime: ''
    });

    return (
      <Select>
        {/* {this.state.pbzDataSourceCache.comShifts.map((val, key) => ( */}
        {comShifts.map((val, key) => {
          if (val.shiftId === '-1') {
            return (
              <Option
                title={val.shiftName}
                value={`${val.shiftId}+${val.shiftName}`}
                key={`${val.shiftId}+${val.shiftName}`}
              >
                {val.shiftName}
              </Option>
            );
          }
          return (
            <Option
              title={
                val.shiftName + '-' + bcx_utils.formatHtml(val.shiftRuleTime)
              }
              value={`${val.shiftId}+${val.shiftName}`}
              key={`${val.shiftId}+${val.shiftName}`}
            >
              {val.shiftName + '-' + bcx_utils.formatHtml(val.shiftRuleTime)}
            </Option>
          );
        })}
      </Select>
    );
  };

  /* 排班制--出勤班次 */
  scheduleRender = () => {
    const { comShifts = [] } = this.state.pbzDataSource;

    const dataSource = bcx_utils.jsoncopy(comShifts).map((val, key) => ({
      ...val,
      ...{ key }
    }));

    //选择班次信息
    const openDrawfixedShift = (cursor, text, record) => {
      this.setState(
        {
          open: true,
          cursor
        },
        () => {
          console.log(this.state.cursor);
        }
      );
    };

    const columns = [
      {
        title: '班次名称',
        dataIndex: 'shiftName',
        key: 'shiftName'
      },
      {
        title: '时间安排',
        dataIndex: 'shiftRuleTime',
        render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
      }
    ];

    return (
      <FormItem {...formItemLayout} label='设置出勤班次'>
        <div>
          {typeof this.props.canEdit === 'string' &&
          this.state.taskStatus !== '0' &&
          this.state.taskStatus !== '6' ? (
            ''
          ) : (
            <Button
              onClick={openDrawfixedShift}
              style={{ marginBottom: 16 }}
              type='primary'
              ghost
            >
              选择默认班次
            </Button>
          )}
          <Table
            size='middle'
            pagination={false}
            columns={columns}
            dataSource={dataSource}
          />
        </div>
      </FormItem>
    );
  };

  /* 排班制--选择班次*/
  renderDrawschedule = () => {
    const { open } = this.state;

    const taskComShiftData = bcx_utils
      .jsoncopy(this.state.taskComShiftData)
      .map(val => ({ ...val, ...{ key: val.shiftId } }));

    const columns = [
      {
        title: '班次名称',
        dataIndex: 'shiftName',
        key: 'shiftName'
      },
      {
        title: '出勤时间',
        dataIndex: 'shiftRuleTime',
        key: 'shiftRuleTime',
        render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
      }
    ];

    const rowSelection = {
      selectedRowKeys: [...this.state.pbzDataSourceCache.comShifts].map(
        val => val.shiftId
      ),
      onChange: (selectedRowKeys, selectedRows) => {
        const pbzDataSourceCache = bcx_utils.jsoncopy(
          this.state.pbzDataSourceCache
        );
        pbzDataSourceCache.comShifts = selectedRows.map(val => ({
          shiftId: val.shiftId,
          shiftName: val.shiftName,
          shiftRuleTime: val.shiftRuleTime
        }));
        this.setState({ pbzDataSourceCache });
      }
    };

    const confirm = () => {
      const pbzDataSourceCache = this.state.pbzDataSourceCache;
      pbzDataSourceCache.returnComTaskSchedulCycleList = [];

      if (pbzDataSourceCache.comShifts.length > 26) {
        message.warning('最多只能选择26个班次！');
        return;
      }
      this.setState({
        pbzDataSource: bcx_utils.jsoncopy(pbzDataSourceCache),
        pbzDataSourceCache,
        open: false
      });
    };
    const cancel = () => {
      this.setState({
        open: false
      });
      this.state.pbzDataSourceCache = bcx_utils.jsoncopy(
        this.state.pbzDataSource
      );
    };

    return (
      <Drawer
        overlayColor='rgba(0, 0, 0,0)'
        right
        open={this.state.open}
        noTouchClose
        width={600}
        className='drawer-box'
        onChange={open => {
          this.setState({ open });
        }}
      >
        <div className='drawer'>
          <div className='drawer-header'>
            选择班次
            {/*<Button
              type="primary"
              onClick={() => this.setState({open3: true, open: false})}
              ghost
            >
              新增班次
            </Button>*/}
          </div>
          <div className='drawer-content'>
            {open && (
              <Table
                pagination={pageInit}
                rowSelection={rowSelection}
                columns={columns}
                dataSource={taskComShiftData}
              />
            )}
          </div>
          <div className='drawer-footer'>
            <Button onClick={cancel}>取消</Button>
            <Button type='primary' onClick={confirm}>
              确定
            </Button>
          </div>
        </div>
      </Drawer>
    );
  };

  /* 排班制--周期性排班 */
  periodicityRender = () => {
    //修改周期排班
    const updataItem = cursor => {
      this.setState({ open2: true, cursor });
    };
    //删除记录
    const deleteItem = cursor => {
      //taskSchedulCycleId
      const pbzDataSource = bcx_utils.jsoncopy(this.state.pbzDataSource);
      let returnComTaskSchedulCycleList =
        pbzDataSource.returnComTaskSchedulCycleList;
      const taskSchedulCycleId =
        returnComTaskSchedulCycleList[cursor].taskSchedulCycleId;

      //本地数据删除
      const filterDelete = () => {
        pbzDataSource.returnComTaskSchedulCycleList = returnComTaskSchedulCycleList.filter(
          (val, index) => index !== cursor
        );
        this.setState({
          pbzDataSource,
          pbzDataSourceCache: bcx_utils.jsoncopy(pbzDataSource)
        });
      };

      Modal.confirm({
        title: '确认删除?',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          if (taskSchedulCycleId !== '') {
            bcx_utils.preventRA(resolve => {
              taskDeleteSchedulCycle({ taskSchedulCycleId }).then(
                data => {
                  console.log(data);
                  resolve();
                  filterDelete();
                },
                err => {
                  console.log(err);
                  resolve();
                }
              );
            });
          } else {
            filterDelete();
          }
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    };

    //添加周期排班
    const addItem = cursor => {
      const pbzDataSourceCache = { ...this.state.pbzDataSourceCache };

      pbzDataSourceCache.returnComTaskSchedulCycleList.push({
        cycleName: '',
        cycleDays: '1',
        taskSchedulCycleId: '',
        comTaskCycleShift: []
      });
      const length =
        pbzDataSourceCache.returnComTaskSchedulCycleList.length - 1;

      this.setState({ cursor: length, pbzDataSourceCache }, () => {
        this.setState({ open2: true });
      });
    };

    /* 排班制----周期性排班设置 */
    const columns = [
      {
        title: '周期名称',
        dataIndex: 'cycleName',
        key: 'cycleName'
      },
      {
        title: '周期天数',
        dataIndex: 'cycleDays',
        key: 'cycleDays'
      },
      {
        title: '启用班次',
        dataIndex: 'shiftNameStr',
        key: 'shiftNameStr',
        render: text => <div dangerouslySetInnerHTML={{ __html: text }} />
      }
      // {
      //   title: '操作',
      //   key: 'update',
      //   render: (text, record, index) => (
      //     <div style={{ color: 'rgba(15,113,255,1)' }}>
      //       <span
      //         onClick={updataItem.bind(this, index)}
      //         style={{ marginRight: 10 }}
      //       >
      //         修改
      //       </span>
      //       <span onClick={deleteItem.bind(this, index)}>删除</span>
      //     </div>
      //   )
      // }
    ];

    const addOptColumns = [...columns];
    typeof this.props.canEdit === 'string' &&
    this.state.taskStatus !== '0' &&
    this.state.taskStatus !== '6'
      ? ''
      : addOptColumns.push({
          title: '操作',
          key: 'update',
          render: (text, record, index) => (
            <div style={{ color: 'rgba(15,113,255,1)' }}>
              <span
                onClick={updataItem.bind(this, index)}
                style={{ marginRight: 10 }}
              >
                修改
              </span>
              <span onClick={deleteItem.bind(this, index)}>删除</span>
            </div>
          )
        });

    const dataSource = this.state.pbzDataSource.returnComTaskSchedulCycleList.map(
      (val, key) => ({ ...val, ...{ key } })
    );

    return (
      <FormItem
        className='hidden-star'
        {...formItemLayout}
        label='周期性排班设置'
      >
        <div>
          {typeof this.props.canEdit === 'string' &&
          this.state.taskStatus !== '0' &&
          this.state.taskStatus !== '6' ? (
            ''
          ) : (
            <Button
              onClick={addItem}
              style={{ marginBottom: 16 }}
              type='primary'
              ghost
            >
              添加周期
            </Button>
          )}
          <Table
            size='middle'
            pagination={false}
            columns={addOptColumns}
            dataSource={dataSource}
          />
        </div>
      </FormItem>
    );
  };

  //设置周期性排班
  renderDrawCircle = () => {
    const { open2, cursor, pbzDataSourceCache, pbzDataSource } = this.state;

    let cycleName = '',
      cycleDays = '1',
      comTaskCycleShift = [];

    //修改模式下，读取当前记录
    if (
      pbzDataSourceCache.returnComTaskSchedulCycleList.length !== 0 &&
      open2
    ) {
      const currentItem =
        pbzDataSourceCache.returnComTaskSchedulCycleList[cursor];
      cycleName = currentItem.cycleName;
      cycleDays = currentItem.cycleDays;
      comTaskCycleShift = currentItem.comTaskCycleShift;
    }

    const cancle = () => {
      //判断是创建模式，还是 修改模式
      const ifUpdate =
        pbzDataSource.returnComTaskSchedulCycleList.length ===
        pbzDataSourceCache.returnComTaskSchedulCycleList.length;

      this.setState(
        {
          open2: false
        },
        () => {
          this.setState({
            pbzDataSourceCache: bcx_utils.jsoncopy(this.state.pbzDataSource)
          });
        }
      );

      if (!ifUpdate) {
        this.setState({ cursor: cursor - 1 });
      }
    };

    const confirm = values => {
      console.log(pbzDataSource.returnComTaskSchedulCycleList);
      console.log(values);

      //转化数据类型
      const { cycleDays, cycleName } = values;
      const comTaskCycleShift = [];
      const shiftNameStrArr = [];
      Object.keys(values).map(val => {
        if (val.includes('returnComTaskSchedulCycleList')) {
          const [shiftId, shiftName] = values[val].split('+');
          comTaskCycleShift.push({ shiftName, shiftId });
          shiftNameStrArr.push(shiftName);
        }
      });

      console.log(cycleDays, cycleName, comTaskCycleShift);

      const { cursor, pbzDataSourceCache } = this.state;

      pbzDataSourceCache.returnComTaskSchedulCycleList[
        cursor
      ].cycleName = cycleName;
      pbzDataSourceCache.returnComTaskSchedulCycleList[
        cursor
      ].cycleDays = cycleDays;
      pbzDataSourceCache.returnComTaskSchedulCycleList[
        cursor
      ].comTaskCycleShift = comTaskCycleShift;
      pbzDataSourceCache.returnComTaskSchedulCycleList[
        cursor
      ].shiftNameStr = shiftNameStrArr.join(',');

      console.log(pbzDataSource.returnComTaskSchedulCycleList);

      this.setState({
        open2: false,
        pbzDataSourceCache,
        pbzDataSource: bcx_utils.jsoncopy(this.state.pbzDataSourceCache)
      });
    };

    //加载 班次列表
    const renderFormItems = (number, FormItem, getFieldDecorator) => {
      const items = [];
      if (!number) {
        return items;
      }
      for (let day = 1; day < number + 1; day++) {
        let initialProp = {};
        //判断
        if (
          pbzDataSourceCache.returnComTaskSchedulCycleList[cursor]
            .comTaskCycleShift[day - 1]
        ) {
          const {
            shiftId,
            shiftName
          } = pbzDataSourceCache.returnComTaskSchedulCycleList[
            cursor
          ].comTaskCycleShift[day - 1];
          initialProp = {
            initialValue: `${shiftId}+${shiftName.replace(/<[^<>]+>/g, '')}`
          };
        }

        if (
          pbzDataSourceCache.returnComTaskSchedulCycleList.length <=
          number + 1
        ) {
          items.push(
            <FormItem
              {...formItemLayout}
              label={`第${bcx_utils.changeIntData(day)}天班次`}
              key={day}
            >
              {getFieldDecorator(`returnComTaskSchedulCycleList${day}`, {
                ...initialProp,
                rules: [{ required: true, message: '请输入' }]
              })(this.renderSelect())}
            </FormItem>
          );
        } else {
          items.push(
            <FormItem
              {...formItemLayout}
              label={`第${bcx_utils.changeIntData(day)}天班次`}
              key={day}
            >
              {getFieldDecorator(`returnComTaskSchedulCycleList${day}`, {
                rules: [{ required: true, message: '请输入' }]
              })(this.renderSelect())}
            </FormItem>
          );
        }
      }
      return items;
    };

    return (
      <Drawer
        overlayColor='rgba(0, 0, 0,0)'
        zIndex={3}
        right
        open={this.state.open2}
        noTouchClose
        width={600}
        className='drawer-box'
        onChange={open2 => {
          this.setState({ open2 });
        }}
      >
        {open2 && (
          <DrawCircleForm
            cycleName={cycleName}
            cycleDays={cycleDays}
            renderFormItems={renderFormItems}
            cancle={cancle}
            confirm={confirm}
          />
        )}
      </Drawer>
    );
  };

  render() {
    const {
      getFieldDecorator,
      setFieldsValue,
      getFieldValue
    } = this.props.form;
    const attendType = '2';
    const { open, open1, open2, open3, canEdit } = this.state;
    return (
      <Container>
        <div className='CreateTask'>
          <div className='Steps'>
            <Steps current={1}>
              <Step title='基本信息' />
              <Step title='出勤设置' />
              <Step title='发布设置' />
            </Steps>
          </div>
          <div style={{ margin: '20px 20px 0' }}>
            <Alert
              message={
                <div>
                  1、班次、周期设置完成后，不可编辑，请根据实际需求准确填写；
                  <p style={{ marginBottom: '0' }}>
                    2、出勤地点，支持多个考勤地点，可点击“添加地点”进行新增；考勤组创建后，可再次编辑考勤地点；
                  </p>
                </div>
              }
              type='warning'
              showIcon
            />
          </div>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
            {canEdit === '0' && <NoTouch bottom={'40'} />}
            <div style={{ position: 'relative' }}>
              {canEdit === '2' && <NoTouch />}
              {/* <FormItem {...formItemLayout} label='选择出勤类型'>
                {getFieldDecorator('attendType', {
                  onChange: e => {
                    setFieldsValue({ attendType: e.target.value });
                  }
                })(
                  //编辑状态，且驻勤的状态不是未开始/未发布就可以让用户选择
                  <Radio.Group
                    disabled={
                      typeof this.props.canEdit === 'string' &&
                      this.state.taskStatus !== '0' &&
                      this.state.taskStatus !== '6'
                        ? true
                        : false
                    }
                  >
                    <Radio className='radioStyle' value='1'>
                      固定班制（每天出勤时间一样）
                      <span className='exclamation'>
                        <Icon type='exclamation-circle' />
                        适用于：每天固定上下班的驻勤。
                      </span>
                    </Radio>
                    <Radio className='radioStyle' value='2'>
                      排班制（自定义设置出勤时间）
                      <span className='exclamation'>
                        <Icon type='exclamation-circle' />
                        适用于：每天多个班次进行轮流上岗的驻勤。
                      </span>
                    </Radio>
                    <Radio disabled className="radioStyle" value="3">
                    自由班制（不设置班次，可随时打卡出勤，计算工时）
                    </Radio>
                  </Radio.Group>
                )}
              </FormItem> */}
              {/* 固定班次 */}
              {attendType === '1' && this.fixedShiftRender()}

              {attendType === '1' && this.renderDrawFixedShift()}

              {/* 排班次--出勤班次 */}
              {attendType === '2' && this.scheduleRender()}

              {attendType === '2' && this.renderDrawschedule()}

              {/* 排班次--周期性排班 */}
              {/* {attendType === '2' &&
                this.state.pbzDataSource.comShifts.length != 0 &&
                this.periodicityRender()} */}
            </div>

            {/*固定班次-设置地点*/}
            {attendType === '1' && (
              <SetLocation
                dataSource={
                  this.state.gdbzDataSource.returnComTaskAttendAddressList
                }
                deleteLocalItem={this.deleteLocalItem}
                addArea={this.addArea.bind(this, 'gdbzDataSource')}
                addressRangeChange={this.addressRangeChange}
                addressRange={this.state.addressRange}
                taskCityName={this.props.dataSource.taskCityName} //添加当前驻勤城市名称，9-28
              />
            )}

            {/*排班次-设置地点*/}
            {attendType === '2' && (
              <SetLocation
                dataSource={
                  this.state.pbzDataSource.returnComTaskAttendAddressList
                }
                deleteLocalItem={this.deleteLocalItem}
                addArea={this.addArea.bind(this, 'pbzDataSource')}
                addressRangeChange={this.addressRangeChange}
                addressRange={this.state.addressRange}
                taskCityName={this.props.dataSource.taskCityName} //添加当前驻勤城市名称，9-28
              />
            )}

            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button onClick={() => this.props.switchStep(-1, this.state.comTaskId)}>上一步</Button>
              {/* <Button type="primary" style={{marginLeft: 8}} htmlType="submit" onClick={() => this.props.switchStep(1)}>
              下一步
            </Button> */}
              <Button
                type='primary'
                style={{ marginLeft: 8 }}
                htmlType='submit'
              >
                下一步
              </Button>
            </FormItem>
          </Form>

          {attendType === '2' && this.renderDrawCircle()}

          {/*  选择班次--新增班次 */}
          <Drawer
            overlayColor='rgba(0, 0, 0,0)'
            right
            open={this.state.open3}
            noTouchClose
            width={600}
            className='drawer-box'
            zIndex={3}
            onChange={open3 => {
              this.setState({ open3 });
            }}
          >
            <AddNewShift />
          </Drawer>

          <Modal
            title='添加出勤WIFI'
            visible={this.state.visible1}
            okText='确认'
            cancelText='取消'
            onOk={this.handleOk}
            onCancel={this.handleCancel}
          >
            <Form onSubmit={this.handleSubmit}>
              <FormItem label='WIFI名称' {...formItemLayout1}>
                {getFieldDecorator('address', {
                  rules: [{ required: true, message: '请输入' }]
                })(<Input />)}
              </FormItem>
              <FormItem {...formItemLayout1} label='MAC地址'>
                {getFieldDecorator('address', {
                  rules: [{ required: true, message: '请输入' }]
                })(<Input />)}
              </FormItem>
            </Form>
          </Modal>
          {(open || open1 || open2 || open3) && <PZhezhao />}
        </div>
      </Container>
    );
  }
}

const Container = style.div`
    .ant-form{
      position: relative;
    }
    .ant-form-item-label{
      >label:before{
       display: inline-block;
       margin-right: 4px;
       content: "*";
       font-family: SimSun;
       line-height: 1;
       font-size: 14px;
       color: #f5222d;
      }
    }
    .hidden-star{
      .ant-form-item-label{
        >label:before{
         content: "";
        }
      }
    }
`;

const NoTouch = style.div`
    // position: absolute;
    left: 0;
    right: 0;
    top: 0px;
    ${({ bottom = 0 }) =>
      css`
        bottom: ${bottom}px;
      `}
    background: rgba(0,0,0,0);
    z-index: 100;
    // cursor: not-allowed;
`;
