import React, { Component } from 'react';

import { withRouter } from 'dva/router';
import moment from 'moment';
import store from 'store';
import axios from 'axios';
import {
  Modal,
  Alert,
  Button,
  Form,
  DatePicker,
  Upload,
  message,
  Table,
  Popconfirm,
  Tabs,
  Radio,
} from "antd";

import ExistingShiftModal from './ExistingShiftModal';
import DeleteShiftsModal from './DeleteShiftsModal';
import PopconfirmContent from './PopconfirmContent';

import {
  getTaskGetTaskUnInsPerInfoList,
  taskComTaskPerShiftPagePerShift,
  taskComShiftPage,
  taskComTaskPerShiftListShift,
  deleteTaskShift
} from '../../../services/api';
import LetterElment from '../../../components/LetterElment';
import NewShift from '../AttendanceManagement/NewShift';
import $nModal from '../../../utils//modal/nModal';
import $loading from '../../../utils/loading';

// import TaskDetailPersonnelPlacement from '../TaskDetail/TaskDetailPersonnelPlacement';
import '../Task.less';

const { MonthPicker } = DatePicker;
const { TabPane } = Tabs;
@withRouter
export default class SchedulingModal extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      comTaskId: '',
      unInsPers: [],  //未进行投保人员
      existingShifts: [], //已有班次
      addedShifts: [], //已添加的班次
      shiftAliasAlphaMap: {}, //排班id所对应的班次名称
      cycleList: [],  //排班周期
      allCycleDetailMap: {},  //排班周期所对应的班次名称

      existingShiftShow: false,  //添加已有班次模态框
      addShiftVisible: false, //新增班次模态框
      deleteVisible: false, //移除班次模态框

      perShiftAllMap: [],  //列表数据
      columns: [],
      month: moment().format('YYYY-MM'),
      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._getTableData());
        },
        onChange: (page, pageSize) => {
          const pagenav = Object.assign({}, this.state.pagenav);
          pagenav.current = page;
          pagenav.pageSize = pageSize;
          this.setState({ pagenav }, () => this._getTableData());
        },
        total: 0
      },
    }
  }
  componentWillReceiveProps(props) {
    if (props.visible && props.comTaskId && props.comTaskId != this.state.comTaskId) {
      this.setState({
        pagenav: {
          ...this.state.pagenav,
          current: 1,
          pageSize: 10
        }
      }, () => {
        this._init();
      });
    }
  }
  componentDidMount() {

  }
  _init = () => {
    //获取驻勤未进行投保人员列表
    getTaskGetTaskUnInsPerInfoList({ comTaskId: this.props.comTaskId }).then(res => {
      if (res.data && res.data.length) {
        this.setState({
          unInsPers: res.data
        });
      }
    });
    this._getAddedShifts();
    this._getTableData();
  }
  //获得某年某月的天数
  _getDaysInOneMonth = (year, month) => {
    month = parseInt(month, 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  };
  _getTableData = () => {
    const { month, pagenav } = this.state;
    const { comTaskId } = this.props;
    taskComTaskPerShiftPagePerShift({ month, comTaskId, key: '', pageSize: pagenav.pageSize, pageNumber: pagenav.current }).then(res => {
      if (res.data) {
        let perShiftAllMap = res.data.perShiftAllMap || [];
        const { perList } = res.data;
        this.setState({
          perShiftAllMap,
          pagenav: {
            ...this.state.pagenav,
            total: perList.total
          }
        }, () => {
          this.setState({
            columns: this._arrangeColumns()
          });
        });
      }
    });
  }

  // 整理表格数据
  _arrangeColumns = () => {
    const { perShiftAllMap } = this.state;
    const dataItem = perShiftAllMap[0];
    const columns = [];
    columns.push({
      title: '姓名',
      key: 'name',
      dataIndex: 'name',
      width: 130,
      fixed: 'left'
    });
    if (!dataItem) {
      for (let key = 1; key <= 30; key++) {
        columns.push({
          title: (key + '').slice(1) == '' ? '0' + key : key,
          key,
          dataIndex: key,
          width: 80
        });
      }
    } else {
      const dateArray = Object.keys(dataItem).filter(key => {
        const dateReg = /^\d{4}-\d{2}-\d{2}$/;
        return dateReg.test(key);
      })
      // .sort((a, b) => {
      //   const aDate = a.split('-')[2];
      //   const bDate = b.split('-')[2];
      //   if (!aDate) {
      //     return -1;
      //   }
      //   if (!bDate) {
      //     return 1;
      //   }
      //   return aDate - bDate;
      // });

      dateArray.forEach(key => {
        columns.push({
          title: key.split('-')[2],
          key: key + '',
          dataIndex: key + '',
          width: 80,
          render: (text, record, index) => {
            const { shiftDate, comTaskId } = this.props;

            const startDate = shiftDate.startDate ? moment(shiftDate.startDate.replace(/-/g, '/')).valueOf() : '';
            const endDate = shiftDate.endDate ? moment(shiftDate.endDate.replace(/-/g, '/')).valueOf() : '';
            const currentDate = moment(key.replace(/-/g, '/')).valueOf();
            const nowDate = moment().subtract(1, 'days').valueOf();
            const { isActive } = record;
            let disable = true;
            if (
              isActive == 1 &&
              currentDate > startDate &&
              currentDate <= endDate &&
              currentDate > nowDate
            ) {
              disable = false;
            }
            if (disable) {
              return (
                <div
                  style={{ background: '#ddd' }}
                  className='paneltablecolor-list paneltablecolor-list-more'
                >
                  {
                    record[key] && this.state.shiftAliasAlphaMap[record[key]] &&
                    <LetterElment
                      name={this.state.shiftAliasAlphaMap[record[key]]}
                      type='tag'
                    />
                  }
                </div>
              );
            } else {
              const { perId } = record;
              return (
                <PopconfirmContent
                  params={
                    {
                      perId,
                      comTaskId,
                      date: key,
                    }
                  }
                  shiftsValue={record[key]} 
                  getTableData={this._getTableData}
                  addedShifts={this.state.addedShifts}
                  shiftAliasAlphaMap={this.state.shiftAliasAlphaMap}
                  cycleList={this.state.cycleList}
                  shiftDate={shiftDate}
                />
              );
            }
          }
        });
      });
      return columns;
    }


    return perShiftAllMap.forEach((item, index) => {

      return (
        {
          title: "序号",
          dataIndex: "number",
          key: "number",
          width: 60,
          fixed: "left",
        }
      )
    });
  }
  // 获取已有班次
  // _getExistingShifts = (cb) => {
  //   const { existingShifts } = this.state;
  //   if (existingShifts.length == 0) {
  //     taskComShiftPage({ pageSize: 5000, pageNumber: 1, shiftType: 2 }).then(({ data: { data = [] } }) => {
  //       this.setState({
  //         existingShifts: data
  //       }, () => {
  //         cb && cb();
  //       });
  //     });
  //   } else {
  //     cb && cb();
  //   }
  // }

  // 获取已添加班次
  _getAddedShifts = () => {
    // 获得任务的班次和排班周期
    taskComTaskPerShiftListShift({ comTaskId: this.props.comTaskId })
      .then(res => {
        if (res.data) {
          this.setState({
            addedShifts: res.data.shiftList || [],
            shiftAliasAlphaMap: res.data.shiftAliasAlphaMap || {},
            cycleList: res.data.cycleList || [],
            allCycleDetailMap: res.data.allCycleDetailMap || {}
          });
        }
      });
  }

  // 导入
  __renderImporter = () => {
    const uploadExcel = {
      name: 'xfile',
      action: `/v5_api/task/com-task-schedul/import`,
      headers: {
        access_token: store.get('saas')['access_token']
      },
      showUploadList: false,
      data: {
        comTaskId: this.props.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._getAddedShifts();
          this._getTableData();
          message.error(msg);
          this.setState({
            errFile: data
          });
        } else if (retType === '0') {
          this._getAddedShifts();
          this._getTableData();
          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>
    );
  }
  render() {
    const { unInsPers } = this.state;
    // const { getFieldDecorator } = this.props.form;
    return (
      <Modal
        title={`${this.props.taskName}-人员排班`}
        visible={this.props.visible}
        className="TaskDetailPersonnelPlacement"
        footer={null}
        width={'80%'}
        destroyOnClose={true}
        onCancel={this.props.onCancel}
      >
        <Alert
          message={
            <div>
              排班制排班：出勤类型选择排班制的，需要手动进行排班，请根据您选择的班次及设定的周期在日历表中，对人员进行手动排班。
              {unInsPers.length > 0 && (
                <div className='publish-success-info'>
                  <div className='specific-info'>
                    {`有${unInsPers.length}个驻勤成员未购买保险,执行驻勤可能存在风险，请点击【金融保险】购买保险保障。`}
                    <a
                      className='specific-list'
                      onClick={() => {
                        $nModal({
                          title: '未投保人员名单',
                          okText: '去投保',
                          cancelText: '暂不投保',
                          content: (
                            <>
                              <p>
                                有
                                <span style={{ color: 'red' }}>
                                  {unInsPers.length}
                                </span>
                                个驻勤成员
                                <span style={{ color: 'red' }}>
                                  未购买保险
                                </span>
                                ,执行驻勤可能存在风险，请点击【去投保】购买保险保障。
                              </p>
                              {
                                unInsPers.map((val, index) => (
                                  <span
                                    key={index}
                                    style={{
                                      display: 'inline-block',
                                      background: '#ccc',
                                      padding: '4px 10px',
                                      borderRadius: '4px',
                                      margin: '4px 8px'
                                    }}
                                  >
                                    {val}
                                  </span>
                                ))
                              }
                            </>
                          ),
                          onOk: close => {
                            this.props.history.push(
                              `/insurancemanagement/enterpriseinsurance`
                            );
                            close();
                          }
                        });
                      }}
                    >
                      查看名单
                    </a>
                  </div>
                </div>
              )}
            </div>
          }
          type='warning'
          showIcon
        />

        <div className="info">
          <section>
            <Button disabled={/[247]/.test(this.props.taskStatusValue)} style={{ marginTop: 10 }} type="primary" size="small" onClick={() => {
              // this._getExistingShifts(() => {
              this.setState({
                existingShiftShow: true
              });
              // });
            }}>添加已有班次</Button>
            <Button disabled={/[247]/.test(this.props.taskStatusValue)} style={{ marginLeft: 15, marginTop: 10 }} type="primary" size="small" onClick={() => {
              this.setState({
                addShiftVisible: true
              });
            }}>添加新班次</Button>
            <Button disabled={/[247]/.test(this.props.taskStatusValue)} style={{ marginLeft: 15, marginTop: 10 }} type="primary" size="small" onClick={() => {
              this.setState({
                deleteVisible: true
              });
            }}>移除班次</Button>
          </section>
          <div className='list'>
            <span className='label'>班次：</span>
            {
              this.state.addedShifts.map((val, key) => (
                <b
                  key={val.shiftId}
                  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>
              ))
            }
          </div>
          {/* <div className='list zlist'>
            <span className='label'>排班周期：</span>
            {
              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>
                );
              })
            }
          </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.month, 'YYYY-MM')}
              format="YYYY-MM"
              onChange={(date, dateString) => {
                this.setState({
                  month: dateString
                }, () => {
                  this._getTableData();
                });
              }}
            />
            {
              /[^247]/.test(this.props.taskStatusValue) &&
              <section style={{ display: 'flex' }}>
                <span style={{ color: '#F59A23', marginLeft: 15 }}>手动排班：点击人员对应日期即可进行排班；Excel排班:</span>
                <a style={{ marginLeft: 15 }}
                  onClick={() => {
                    const QUERY = `comTaskId=${this.props.comTaskId}&month=${this.state.month}`;
                    axios({
                      method: 'get',
                      url: `/v5_api/task/com-task-schedul/export?${QUERY}`, //后台请求地址
                      responseType: 'blob',
                      headers: {
                        access_token: store.get('saas')['access_token']
                      }
                    }).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>
                {
                  this.__renderImporter()
                }
              </section>

            }
          </Form>
          <div className='tabPanel lmb-tabpanel'>
            <Table
              pagination={this.state.pagenav}
              bordered
              dataSource={this.state.perShiftAllMap}
              columns={this.state.columns}
              scroll={{ x: parseInt(31 * 80 + 130) }}
            // loading={this.state.loading}
            />
          </div>
        </div>

        {/* 添加已有班次模态框 */}
        <ExistingShiftModal
          existingShifts={this.state.existingShifts}
          addedShifts={this.state.addedShifts}
          visible={this.state.existingShiftShow}
          comTaskId={this.props.comTaskId}
          setState={this.setState.bind(this)}
          updatePage={() => {
            this._getAddedShifts();
            this._getTableData();
          }}
        />

        {/* 新增班次模态框 */}
        {
          this.state.addShiftVisible &&
          <NewShift
            // style={{zIndex: 1000000}}
            modalVisble={this.state.addShiftVisible}
            {...this.props}
            onUpdateShiftPage={() => {
              // 更新已有班次
              // this._getExistingShifts();
            }}
            onClose={() => {
              this.setState({ addShiftVisible: false });
            }}
          />
        }

        {/* 移除班次模态框 */}
        <DeleteShiftsModal
          comTaskId={this.props.comTaskId}
          addedShifts={this.state.addedShifts}
          visible={this.state.deleteVisible}
          setState={this.setState.bind(this)}
          onOk={(values, cb) => {
            Modal.confirm({
              title: '确认删除?',
              okText: '确定',
              cancelText: '取消',
              onOk: () => {
                const shiftIdStrs = values.map(({ shiftId }) => shiftId);
                deleteTaskShift({ comTaskId: this.props.comTaskId, shiftIdStr: shiftIdStrs.join(",") }).then(res => {
                  if (res.retType == '0') {
                    this.setState({
                      deleteVisible: false
                    });
                    cb && cb();
                    // 更新班次
                    this._getAddedShifts();
                    this._getTableData();
                  }
                })
              }
            });
          }}
        />
        {/* <TaskDetailPersonnelPlacement
          onCancel={this.props.onCancel}
          comTaskId={this.props.comTaskId}
          taskStatusValue={this.props.taskStatusValue}
          visible={this.props.visible}
        /> */}
      </Modal>
    );
  }
}
