import { observable, action, computed } from "mobx";
import { message, Button } from "antd";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import * as api from "../apis/scheduleSetting";
import { i18n } from "../public/i18n";
import { findIndex, dropRight, remove, cloneDeep, find } from "lodash";
import ListCell from "../components/scheduleSetting/ListCell";
import ListHeader from "../components/scheduleSetting/ListHeader";
import { dateFormat } from '../util/index';
import has from 'lodash/has';
import filter from 'lodash/filter';
import { WeaLocaleProvider, WeaTools } from "ecCom";
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel;

export class HrmScheduleSetting extends HrmBaseStore {
  /********************* unobservable list *********************/
  groupId;
  shortWeekdays = this.getLocale().lang.format.veryShortWeekdays;
  dateMap = new Map();
  radioGroupVal = {}
  extenalRadioGroupConfig = [];
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable showhideFlag = true;
  @observable today = this.moment();
  @observable groupName = '';
  @observable spinning = false;
  @observable spinTip = '';
  @observable pageIndex = 1;
  @observable pageSize = 10;
  @observable total = 0;
  @observable radioGroupConfig = [];
  @observable showHasNotAccount = false;
  @observable tabConfig = {
    tabs: [],
    keyParam: "viewCondition",
    activeTabKey: "1",
    tabChangeHandle: key => this.setActiveTab(key)
  };
  @observable groupValidatDate = { start: null, end: null };

  @observable editTabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "g1",
        title: () => getLabel('389506', '按天排班'),
        viewCondition: "1"
      },
      {
        color: "#000000",
        groupId: "g2",
        title: () => getLabel('389507', '按周期排班'),
        viewCondition: "2"
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1",
    tabChangeHandle: key => this.setEditActiveTab(key)
  };

  @observable
  groupEditDialogParams = {
    ...this.dialogPropsDef,
    moreBtn: {},
    style: {
      width: 800,
      height: 740
    },
    callback: () => {
      message.success(i18n.message.saveSuccess());
      this.groupEditDialogParams.visible = false;
      // this.init(this.groupId);
      this.getScheduleData(this.getListTableQueryParams());
    },
    onCancel: () => {
      this.groupEditDialogParams.visible = false;
    }
  };

  @observable
  holidayDialogParams = {
    ...this.dialogPropsDef,
    moreBtn: {},
    style: {
      width: 800,
      height: 680
    },
    callback: () => {
      message.success(i18n.message.saveSuccess());
      this.holidayDialogParams.visible = false;
      this.init(this.groupId);
    },
    onCancel: () => {
      this.holidayDialogParams.visible = false;
    }
  };

  @observable searchDate = this.moment().format("YYYY-MM");
  @observable shiftList = [];
  @observable serialInfo = [];
  @observable listTable = {
    columns: [],
    datas: []
  };
  @observable analysisTable = {
    columns: [],
    datas: []
  };
  @observable holidays = [];

  @observable batchShiftScheduleFromParams = {
    moduleName: 'hrm',
    visible: false,
    onOk: data => {
      this.doBatchSchedule(data);
    },
    onCancel: () => (this.batchShiftScheduleFromParams.visible = false)
  };

  @observable selectedRowKeys = [];
  /********************* observable list *********************/

  /********************* computed list *********************/
  @computed get multiDelete () {
    return this.selectedRowKeys.length === 0;
  }
  /********************* computed list *********************/

  /********************* action list *********************/
  clearData = groupId => {
    this.selectedRowKeys.length = 0;
    this.showHasNotAccount = false;
    this.groupId = groupId;
    this.pageIndex = 1;
    this.pageSize = 10;
    this.shiftList.length = 0;
    this.serialInfo.length = 0;
    this.holidays.length = 0;
    this.dateMap.clear();
  };

  @action getListTableQueryParams = (pageIndex, pageSize) => {
    this.pageIndex = pageIndex || 1;
    pageSize && (this.pageSize = pageSize);
    return {
      groupId: this.groupId,
      kqMonth: this.searchDate,
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      ...this.radioGroupVal,
      isNoAccount: this.showHasNotAccount ? '1' : '0'
    }
  }

  init = groupId => {
    this.searchDate = this.moment().format("YYYY-MM");
    this.clearData(groupId);
    this.radioGroupVal = {};
    api.init(this.getListTableQueryParams()).then(
      rs => {
        rs.map((data, index) => {
          if (data.status === "1") {
            switch (index) {
              case 0:
                this.extenalRadioGroupConfig = data.conditions;
                this.setRadioGroupConfig();
                break;
              case 1:
                let tabs = [];
                data.tabs.map((tab, index) => {
                  let tabInfo = {
                    color: "#000000",
                    groupId: `g{tab.key}`,
                    title: tab.title,
                    viewCondition: tab.key
                  };
                  tabs.push(tabInfo);
                });
                this.tabConfig.tabs = tabs;
                this.setActiveTab("1");
                break;
              // case 2:
              //   this.setScheduleData(data);
              //   break;
            }
          }
        });
      },
      error => { }
    );
  };

  @action setActiveTab = key => {
    const tabIndex = this.getTabIndex(this.toJS(this.tabConfig.tabs), key);
    if (tabIndex < 0) return;
    this.tabConfig.activeTabKey = key || this.tabConfig.tabs[0].viewCondition;
    if (key === '2') {
      this.getShiftScheduleTotal();
    } else {
      this.clearData(this.groupId);
      // this.getScheduleData(this.getListTableQueryParams());
    }
  };

  @action getShiftScheduleTotal = () => {
    api.getShiftScheduleTotal({ groupId: this.groupId, kqMonth: this.searchDate }).then(data => {
      if (data.status === '1') {
        this.setAnalysisData(data);
        // this.analysisTable.columns = [...data.columns];
      } else {
        message.error(data.message);
      }
    }, error => { })
  }

  @action setSelectedRowKeys = v => this.selectedRowKeys = v;

  @action setAnalysisData = data => {
    const serialCol = data.columns[0];
    const render = (text, record) => {
      const style = {
        background: (record.serialId === '-1' ? '#ccc' : (find(this.toJS(this.shiftList), { id: record.serialId }) || { bgColor: window.defaultScheduleBGColor[0] }).bgColor),
        color: (record.serialId === '-1' ? '#000' : '#fff')
      }
      return <div className='scheduleName' style={style}>{text}</div>
    }
    this.analysisTable.columns = [{ ...serialCol, key: serialCol.dataIndex, width: '250px', render }];
    this.generateAnalysisTableColumns();
    this.analysisTable.datas = data.datas;
  }

  @action setEditActiveTab = key => {
    const tabIndex = this.getTabIndex(this.toJS(this.editTabConfig.tabs), key);
    if (tabIndex < 0) return;
    this.editTabConfig.activeTabKey =
      key || this.editTabConfig.tabs[0].viewCondition;
  };

  @action setSearchDate = v => {
    if (this.moment.isMoment(v))
      this.searchDate = v.format("YYYY-MM");
    else
      this.searchDate = dateFormat(v, "YYYY-MM")
    this.getScheduleData(this.getListTableQueryParams());
  };

  @action getScheduleData = (params) => {
    if (this.spinning)
      return;
    this.selectedRowKeys.length = 0;
    this.spinning = true;
    api.getShiftSchedule(params).then(data => {
      if (data.status === '1') {
        this.setScheduleData(data);
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }, error => { this.spinning = false; })
  }

  @action setDateMap = datas => {
    this.dateMap.clear();
    datas.map(d => {
      const arr = d.split('|');
      const resourceid = arr[0], date = arr[1], recordId = arr[2];
      if (!this.dateMap.has(resourceid))
        this.dateMap.set(resourceid, new Map());
      this.dateMap.get(resourceid).set(date, recordId);
    })
  }

  @action setShiftList = datas => {
    const colorLen = window.defaultScheduleBGColor.length;
    datas.map((d, i) => {
      d.bgColor = window.defaultScheduleBGColor[i % colorLen];
    });
    this.shiftList = [
      ...datas,
      {
        id: '-1',
        bgColor: "#ccc",
        name: getLabel('26593', '休息')
      }
    ]
  }

  @action setSerialInfo = datas => {
    if (this.shiftList.length > 0 && datas.length > 0) {
      datas = datas.map((d, i) => {
        return { ...d, bgColor: window.defaultScheduleBGColor[i % window.defaultScheduleBGColor.length] }
      })
    }
    // datas[0].bgColor = this.shiftList[0].bgColor;
    this.serialInfo = [...datas];
  }

  cloneData = [];
  @action setListTableColumns = datas => {
    this.listTable.columns = [
      {
        title: <div style={{ width: 100 }}>{getLabel('714', "编号")}</div>,
        dataIndex: "workcode",
        key: "workcode",
        width: 100,
        fixed: 'left',
        render: (text, record, index) => <div className='text-elli'>{text}</div>,
      },
      {
        title: <div style={{ width: 100 }}>{getLabel('25034', '姓名')}</div>,
        dataIndex: "name",
        key: "name",
        width: 100,
        fixed: 'left',
        render: (text, record, index) => <ListCell ecId={`${this && this.props && this.props.ecId || ''}_ListCell@qfa12l@${index}`} store={this} dataIndex='name' record={record} withName />,
      },
      {
        title: <div style={{ width: 150 }}>{getLabel('27511', '部门')}</div>,
        dataIndex: "department",
        key: "department",
        width: 150,
        fixed: 'left',
        render: (text, record, index) => <div className='text-elli' style={{ width: 150 }}>{text}</div>,
      }
    ];
    this.cloneData = cloneDeep(datas);
    this.listTable.datas = [...datas];
    this.generateListTableColumns();
  }

  @action setScheduleData = data => {
    this.today = this.moment(data.today, 'YYYY-MM-DD');
    this.groupName = data.groupName;
    this.setDateMap(data.keyDatas);
    this.holidays = data.holidays || [];
    this.setShiftList(data.shiftList);
    this.setSerialInfo(data.serialInfo);
    this.setRadioGroupConfig();
    this.setListTableColumns(data.datas);
    this.pageIndex = Number(data.pageindex);
    this.pageSize = Number(data.pagesize);
    this.total = Number(data.count);
    if (has(data, 'validityFromDate')) {
      this.groupValidatDate = { start: data.validityFromDate, end: data.validityEndDate };
    }
  }

  @action onCellMouseEnter = index => {
    $("div[name*='scheduleCol']").removeClass('sameCol');
    const k = `div[name='scheduleCol${index}']`;
    $(k).addClass('sameCol')
  }

  @action onCellMouseLeave = () => {
  }

  @action generateListTableColumns = () => {
    const hs = this.toJS(this.holidays);
    const m = this.moment(this.toJS(this.searchDate), "YYYY-MM");
    const days = m.daysInMonth();
    let { columns } = this.toJS(this.listTable);
    if (columns.length > 3)
      columns = dropRight(columns, columns.length - 3);
    for (let i = 1; i <= days; i++) {
      m.set("date", i);
      const d = m.format("d");
      const date = m.format('YYYY-MM-DD');
      const props = {
        weekDay: d,
        day: i,
        holidayInfo: hs.length > 0 && hs.find(data => data.date == date),
      }
      columns.push({
        title: (
          <ListHeader ecId={`${this && this.props && this.props.ecId || ''}_ListHeader@3g77wp@${i}`} {...props} />
        ),
        width: 50,
        dataIndex: m.format('YYYY-MM-DD'),
        key: m.format('YYYY-MM-DD'),
        render: (text, record, index) => this.listTableColRender(text, record, index, i),
        otherParams: props
      });
    }
    this.listTable.columns = columns;
  };

  listTableColRender = (text, record, index, colIndex) => {
    const props = {
      store: this,
      colIndex,
      id: text,
      record
    }
    return (
      <ListCell ecId={`${this && this.props && this.props.ecId || ''}_ListCell@cebo01`} {...props} />
    );
  };

  @action generateAnalysisTableColumns = () => {
    const hs = this.toJS(this.holidays);
    const m = this.moment(this.toJS(this.searchDate), "YYYY-MM");
    const days = m.daysInMonth();
    let { columns } = this.toJS(this.analysisTable);
    for (let i = 1; i <= days; i++) {
      m.set("date", i);
      const d = m.format("d");
      const date = m.format('YYYY-MM-DD');
      const props = {
        weekDay: d,
        day: i,
        holidayInfo: hs.length > 0 ? hs[0][date] : null,
        dropdown: false
      }
      columns.push({
        title: (
          <ListHeader ecId={`${this && this.props && this.props.ecId || ''}_ListHeader@8sode7@${i}`} {...props} />
        ),
        width: "50px",
        dataIndex: m.format('YYYY-MM-DD'),
        key: m.format('YYYY-MM-DD'),
        // render: (text, record, index) => this.listTableColRender(text, record, index, i),
        // otherParams: props
      });
    }
    this.analysisTable.columns = columns;
  };

  @action onScheduleChange = (records, target) => {
    let { datas, columns } = this.toJS(this.listTable);
    let dataIndex, d;
    const today = this.moment();
    records.map(record => {
      switch (target) {
        case 'cell':
          dataIndex = findIndex(datas, { resourceid: record.resourceid });
          d = datas[dataIndex];
          datas[dataIndex] = { ...d, ...record };
          break;
        case 'header':
          [...Object.keys(record)].map(k => {
            if (k != 'resourceid') {
              for (let i = 0; i < datas.length; i++) {
                let d = datas[i];
                const m = this.moment(k);
                const isValidWithinRange = m.isSameOrAfter(d.validatefrom) && m.isSameOrBefore(d.validateto);
                if(isValidWithinRange){
                  datas[i] = { ...d, [k]: record[k] };
                }
              }
            }
          });
          break;
        case 'resource':
          dataIndex = findIndex(datas, { resourceid: record.resourceid });
          let colIndex = this.getColIndex(columns, null, target);
          for (let col = 0; col < columns.length; col++) {
            const column = columns[col];
            const m = this.moment(column.dataIndex);
            let {validatefrom ,validateto } = datas[dataIndex];
            let isValidWithinRange;
            if( today.isAfter(validateto)){
              isValidWithinRange = false;
            }else{
              if( today.isSameOrAfter(validatefrom) && today.isSameOrBefore(validateto)){
                validatefrom = today.format('YYYY-MM-DD');
              }
              isValidWithinRange = m.isSameOrAfter(validatefrom) && m.isSameOrBefore(validateto);
            }
           
            if(isValidWithinRange){
              Object.assign(datas[dataIndex], {
                [column.dataIndex]: record.shiftid
              });
            }
          }
          break;
      }
    });
    this.listTable.datas = datas;
  }

  getValidDate = () => {
    const m = this.moment(this.toJS(this.searchDate), "YYYY-MM");
    const days = m.daysInMonth();
    for (let i = 1; i <= days; i++) {
      m.set("date", i);
      if (!m.isBefore(this.toJS(this.today)) || m.isSame(this.toJS(this.today), 'day')) {
        return m.format('YYYY-MM-DD');
      }
    }
    return null;
  }

  getColIndex = (columns, date, target) => {
    if (target === 'cell')
      return findIndex(columns, { dataIndex: date });
    else {
      return findIndex(columns, { dataIndex: this.getValidDate() });
    }
  }

  @action onCycleClick = (records, target, isContinue = false) => {
    let { datas, columns } = this.toJS(this.listTable);
    records.map(record => {
      const { date, serial } = record;
      let i = 0, dataIndex;
      switch (target) {
        case 'header':
          const o = {};
          for (let col = colIndex; col < columns.length; col++) {
            const column = columns[col];
            const { weekDay, holidayInfo } = column.otherParams;
            // if((weekDay == 0 || weekDay == 6 || (holidayInfo && holidayInfo.type === 'rest')) && !isContinue){
            if ((weekDay == 0 || weekDay == 6) && !isContinue) {
              Object.assign(o, {
                [column.dataIndex]: ''
              });
              continue;
            }
            Object.assign(o, {
              [column.dataIndex]: serial[i % serial.length]
            });
            i++;
          }
          for (i = 0; i < datas.length; i++) {
            Object.assign(datas[i], o);
          }
          break;
        default:
          let colIndex = this.getColIndex(columns, date, target);
          dataIndex = findIndex(datas, { resourceid: record.resourceid });
          for (let col = colIndex; col < columns.length; col++) {
            const column = columns[col];
            const { weekDay, holidayInfo = {} } = column.otherParams || {};
            const {type} = holidayInfo
            // if((weekDay == 0 || weekDay == 6 || (holidayInfo && holidayInfo.type === 'rest')) && !isContinue){
            
            //双休日取消排班
            const b = (weekDay == 0 || weekDay == 6) && !isContinue
            
            if (
              ( type == '1' && (this.value2 == '2' ) ) ||
              (  type == '3' && (this.value3 == '2') ) || 
              (!['1','3'].includes(type) && b )
            ) {
              Object.assign(datas[dataIndex], {
                [column.dataIndex]: ''
              });
              continue;
            }
            const m = this.moment(column.dataIndex);
            const {validatefrom ,validateto } = datas[dataIndex];
            const isValidWithinRange = m.isSameOrAfter(validatefrom) && m.isSameOrBefore(validateto);
            if(isValidWithinRange){
              Object.assign(datas[dataIndex], {
                [column.dataIndex]: serial[i % serial.length]
              });
            }
            i++;
          }
          break;
      }
    });
    this.listTable.datas = datas;
    this.value2 = '1';
    this.value3 = '1';
  }

  @action save = () => {
    if (this.spinning)
      return;
    this.spinning = true;
    let datas = this.toJS(this.listTable.datas);
    let arr = [];
    datas.map((d, index) => {
      const cloneRecord = this.cloneData[index];
      let entity = {
        kqdata: []
      };
      remove([...Object.keys(d)], v => ['name', 'department', 'validatefrom', 'validateto'].indexOf(v) < 0).map(k => {
        if (k === 'resourceid')
          entity.resourceid = d[k];
        else {
          const resourceid = entity.resourceid || d.resourceid;
          const date = k;
          let recordId = '';
          if (this.dateMap.has(resourceid) && this.dateMap.get(resourceid).has(date)) {
            recordId = this.dateMap.get(resourceid).get(date);
          }
          entity.kqdata.push({
            id: recordId,
            serialid: d[k],
            oldValue: cloneRecord[k],
            date
          });
        }
      })
      arr.push(entity);
    });
    api.save({ data: JSON.stringify({ datas: arr, groupId: this.groupId }) }).then(data => {
      if (data.status === '1') {
        message.success(i18n.message.saveSuccess());
        this.spinning = false;
        this.getScheduleData(this.getListTableQueryParams());
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }, error => this.spinning = false);
  };

  @action groupSetting = () => {
    // const url = `/spa/hrm/attendance.html#/attendance/groupInfo/${this.groupId}?_key=${new Date().getTime()}`;
    const url = `/#/main/attendance/groupInfo/${this.groupId}?_key=${new Date().getTime()}`;
    this.groupEditDialogParams.title = i18n.label["389108"]();
    this.groupEditDialogParams.groupId = this.groupId;
    // this.groupEditDialogParams.url = url;
    this.groupEditDialogParams.visible = true;
  }

  @action getBatchShiftScheduleFrom = () => {
    api.getBatchShiftScheduleFrom({ groupId: this.groupId }).then(data => {
      if (data.status === '1') {
        this.batchShiftScheduleFromParams.conditions = data.conditions;
        this.batchShiftScheduleFromParams.title = getLabel('33511', '批量设置');
        this.batchShiftScheduleFromParams.visible = true;
      } else {
        message.error(data.message);
      }
    }, error => { })
  }

  @action holidaySetting = () => {
    window.open(`/spa/hrm/staticAttendance4engine/engine.html#/attendance/holidaySetting/${this.groupId}`);
  }

  @action doBatchSchedule = (data) => {
    let sd = null;
    if (data.shiftScheduleType == '1' && data.shiftScheduleDate != '') {
      sd = this.moment(data.shiftScheduleDate, "YYYY-MM-DD");
    } else if (data.shiftScheduleType == '2' && data.shiftScheduleBeginDate != null && data.shiftScheduleEndDate != '') {
      sd = this.moment(data.shiftScheduleBeginDate, "YYYY-MM-DD");
      let ed = this.moment(data.shiftScheduleEndDate, "YYYY-MM-DD");
      // if(Math.abs(sd.diff(ed, "d")) > 31){
      //   message.error(getLabel('508248','排班周期不能超过31天'));
      //   this.batchShiftScheduleFromParams.onCancel();
      //   return;
      // }
      if (!sd.isSame(ed) && !sd.isBefore(ed)) {
        message.error(getLabel('508286', '结束日期不能大于开始日期'));
        this.batchShiftScheduleFromParams.onCancel();
        return;
      }
    } else {
      message.error('排班日期不能为空');
      this.batchShiftScheduleFromParams.onCancel();
      return;
    }

    // if(sd.isBefore(this.toJS(this.today)) && !sd.isSame(this.toJS(this.today), 'day')){
    //   message.error(getLabel('500488','无法对过往日期进行排班'));
    //   this.batchShiftScheduleFromParams.onCancel();
    //   return;
    // }

    if (this.spinning)
      return;
    this.spinning = true;
    let d = cloneDeep(data);
    const keys = remove([...Object.keys(data)], v => v.indexOf('span') > -1);
    keys.map(k => delete d[k]);
    let obj = { groupId: this.groupId, ...d };
    api.batchSave({ data: JSON.stringify(obj) }).then(data => {
      this.spinning = false;
      if (data.status === '1') {
        message.success(i18n.message.saveSuccess());
        this.getScheduleData(this.getListTableQueryParams());
        this.batchShiftScheduleFromParams.onCancel();
      } else {
        message.error(data.message);
        this.batchShiftScheduleFromParams.onCancel();
      }
    }, error => {
      this.spinning = false;
      this.batchShiftScheduleFromParams.onCancel();
    })
  }

  @action importExcel = (fileid) => {
    api.importExcel({ groupId: this.groupId, filename: fileid }).then(data => {
      if (data.status === '1') {
        message.success(i18n.message.uploadSuccess());
        this.getScheduleData(this.getListTableQueryParams());
      } else {
        message.error(data.message);
      }
    }, error => { })
  }

  @action exportExcel = () => {
    if (this.spinning)
      return;
    this.spinning = true;
    this.spinTip = getLabel('500702', '导出数据中，请稍候');
    const params = {
      groupId: this.groupId,
      kqMonth: this.searchDate,
      ...this.radioGroupVal,
      isNoAccount: this.showHasNotAccount ? '1' : '0'
    };

    api.exportExcel({ data: JSON.stringify(params) }).then(data => {
      this.spinning = false;
      this.spinTip = '';
      if (data.status === '1' && data.url != null && data.url.trim().length > 0)
        WeaTools.downloadFile(addContentPath(data.url), "GET");
    }, error => {
      this.spinning = false;
      this.spinTip = '';
    })
  }

  getContrastYIQ = (val) => {
    if (val == null)
      return '#000';
    let sColor = val.toLowerCase();
    //十六进制颜色值的正则表达式
    const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    // 如果是16进制颜色
    if (sColor && reg.test(sColor)) {
      if (sColor.length === 4) {
        let sColorNew = "#";
        for (var i = 1; i < 4; i += 1) {
          sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
        }
        sColor = sColorNew;
      }
      //处理六位的颜色值
      var sColorChange = [];
      for (var i = 1; i < 7; i += 2) {
        sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
      }
      const yiq = ((sColorChange[0] * 299) + (sColorChange[1] * 587) + (sColorChange[2] * 114)) / 1000;
      const c = (yiq >= 128) ? 'black' : 'white';
      return c;
    }
    return '#000';
  };

  @action setRadioGroupConfig = () => {
    let { viewscope, datascope } = this.radioGroupVal;
    viewscope = viewscope || '0';
    datascope = datascope || '0';
    const config = [
      {
        label: getLabel('500489', '班次说明'),
        labelcol: 3,
        fieldcol: 21,
        com: (
          <div>
            {
              filter(this.toJS(this.shiftList), v => v.isDelete != '1').map(shift => <div className='item' style={{ background: shift.bgColor, color: shift.id === 0 ? '#000' : '#fff' }}>{shift.name}</div>)
            }
          </div>
        )
      },
      {
        label: getLabel('389103', '排班周期'),
        labelcol: 3,
        fieldcol: 21,
        com: (
          <div>
            {
              this.toJS(this.serialInfo).map(serial => <div className='item' style={{ background: serial.bgColor, color: '#fff' }}>{serial.name}</div>)
            }
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w9svcb`} className='settingBtn' type='default' onClick={this.groupSetting}>{getLabel('30747', '设置')}</Button>
          </div>
        )
      }
    ];
    config.push(...this.extenalRadioGroupConfig);
    this.radioGroupConfig = config;
  }

  @action onRadioGroupChange = params => {
    this.radioGroupVal = params;
    switch (params.viewscope) {
      case '1':
        if (params.subCompanyId == null || params.subCompanyId == '') {
          return;
        }
        break;
      case '2':
        if (params.departmentId == null || params.departmentId == '') {
          return;
        }
        break;
      case '3':
        if (params.resourceId == null || params.resourceId == '') {
          return;
        }
        break;
    }
    this.showHasNotAccount = ((['4', '5', '6', '7', '9'].indexOf(params.status || '')) > -1);
    this.getScheduleData(this.getListTableQueryParams());
  }

  @action showAll = () => {
    this.showHasNotAccount = !this.showHasNotAccount;
    this.getScheduleData(this.getListTableQueryParams());
  }

  @action multiDeleteSchedule = () => {
    let { datas } = this.toJS(this.listTable);
    let ids = [];
    this.toJS(this.selectedRowKeys).map(index => {
      ids.push(datas[index].resourceid)
    })
    const params = {
      resourceids: ids.join(','),
      month: this.searchDate,
      groupId: this.groupId
    }
    this.confirmInfo({
      content: getLabel('500490', '确定要删除所选人员的排班信息吗？'),
      onOk: () => {
        api.batchDelete(params).then(data => {
          if (data.status === "1") {
            message.success(i18n.message.deleteSuccess());
            this.selectedRowKeys.length = 0;
            this.getScheduleData(this.getListTableQueryParams());
          } else {
            message.error(data.message);
          }
        });
      }
    });
  }
  /********************* action list *********************/

  @action onClickHandle = () => {
    this.showhideFlag = !this.showhideFlag
  }

  onSelectChangeHandle = (val, type) => {
      this[`value${type}`] = val
  }
}

export const hrmScheduleSetting = new HrmScheduleSetting();
