import { observable, action, computed, autorun } from "mobx";
import { WeaTableNew, WeaSwitch } from "comsMobx";
import { WeaFormItem, WeaTimePicker, WeaInputNumber, WeaSelect ,WeaHelpfulTip, WeaCheckbox, WeaError, WeaLocaleProvider} from "ecCom";
import { Button, message } from "antd";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import * as api from "../apis/shiftManager";
import { i18n } from "../public/i18n";
import WorkTimeAnalysis from "../components/shiftManager/WorkTimeAnalysis";
import LinkComs from "../components/shiftManager/LinkComs";
import {DialogStore,SearchStore} from '../public/valhalla/stores/index.js';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import {addContentPath} from '../util/index.js'
import uuid from 'uuid';
const getLabel = WeaLocaleProvider.getLabel;

const { TableStore } = WeaTableNew;


export class HrmShiftManager extends HrmBaseStore {
  /********************* unobservable list *********************/
  custLabelCol = 4;
  worktime = 0;
  rightMenus = [];
  worktimeError = false;//message.error(i18n.label["388878"]());
  resttimeError = false;//message.error(i18n.label["388878"]());
  resttimeRangeError = false;
  sTime = ["09:00", "13:00", "19:00"];
  eTime = ["12:00", "18:00", "23:00"];
  ruleOptions = [];
  worktimeConstruct = {
    across: 0,
    mins: 60,
    mins_next:'',
    times: "",
    clockinnot:'0'
  };
  searchParams = {};
  orgTreeProps = {
    needSearch: true,
    isLoadAllSub: false,
    topPrefix: "hrmSearch",
    inputLeftDom: `<b>${i18n.label.organization()}</b>`,
    // needDropMenu: true,
    treeNodeClick: this.treeNodeClick,
    params: {
      rightStr: "KQClass:Management"
    }
  };
  errRefs = {}

  mainTabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "main",
        title: "",
        viewCondition: "1",
        searchType: ["base"],
        searchKey: "serial",
        doSearch: params => this.getTableData(params)
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1"
  };

  multiColumn = [
    {
      key: "permitlateminutes",
      labelCol: 0
    },
    {
      key: "seriouslateminutes",
      labelCol: 0
    },
    {
      key: "lateabsentminutes",
      labelCol: 0
    },
    {
      key: "permitleaveearlyminutes",
      labelCol: 0
    },
    {
      key: "seriousleaveearlyminutes",
      labelCol: 0
    },
    {
      key: "leaveearlyabsentminutes",
      labelCol: 0
    }
  ];

  itemRender = {
    serial: (field, textAreaProps, form, formParams) => {
      return (
        <div className="cust">
          <div className="basic">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7b0hgr`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        </div>
      );
    },
    subcompanyid: (field, textAreaProps, form, formParams) => {
      return (
        <div className="cust">
          <div className="basic">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@jsh3pm`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        </div>
      );
    },
    shiftonoffworkcount: (field, textAreaProps, form, formParams, callback) => {
      const { fieldMap } = form;
      return (
        <div className="cust">
          <div>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7v3lis`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
              onChange={v => this.onWorkCountChange(v)}
            />
          </div>
          {/* <div>
            <WeaSwitch
              fieldConfig={{
                ...fieldMap["punchsettings"],
                ...textAreaProps,
                content: fieldMap["punchsettings"].label
              }}
              form={form}
              formParams={formParams}
            />
          </div> */}
        </div>
      );
    },
    punchsettings: (field, textAreaProps, form, formParams) => null,
    isresttimeopen: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;//mins_next
      if (true/*formParams.shiftonoffworkcount === "1"*/) {
        return (
          <div className="cust">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bhw6l0`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
              onChange={v => this.calculateWorkTime()}
            />
            {/* {formParams.isresttimeopen === "1" && (
              <div className="child">
                <div className="lbl">{fieldMap["restbeigin"].label}</div>
                <div className="restTime">
                  <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@61faoc`} tipPosition='bottom'
                      ref={d => this.errRefs['restbeigin'] = d}
                      error={`"${fieldMap["restbeigin"].label}" ${i18n.message.dataEmpty()}`}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4lcpz1`}
                      fieldConfig={{
                        ...fieldMap["restbeigin"],
                        ...textAreaProps
                      }}
                      form={form}
                      formParams={formParams}
                      onChange={() => this.calculateWorkTime()}
                    />
                  </WeaError>
                </div>
                {
                  this.calculateRestTime(true) &&
                  <div className="restTimeInfo">{i18n.label["388785"]()}</div>
                }
              </div>
            )}
            {formParams.isresttimeopen === "1" && (
              <div className="child">
                <div className="lbl">{fieldMap["restend"].label}</div>
                <div className="restTime">
                  <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@clo7t7`} tipPosition='bottom'
                      ref={d => this.errRefs['restend'] = d}
                      error={`"${fieldMap["restend"].label}" ${i18n.message.dataEmpty()}`}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@5yaxx3`}
                      fieldConfig={{ ...fieldMap["restend"], ...textAreaProps }}
                      form={form}
                      formParams={formParams}
                      onChange={() => this.calculateWorkTime()}
                    />
                  </WeaError>
                </div>
                {
                  this.calculateRestTime() &&
                  <div className="restTimeInfo">{i18n.label["388785"]()}</div>
                }
              </div>
            )} */}
          </div>
        );
      } else {
        return null;
      }
    },
    restbeigin: (field, textAreaProps, form, formParams) => null,
    restend: (field, textAreaProps, form, formParams) => null,
    halfcalrule: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      let coms = [];
      if(formParams.halfcalrule == '1'){
        coms = [
          <div className="child">
            <div className="lbl">{fieldMap["halfcalpoint"].label}:</div>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@s3vn8e`}
              fieldConfig={{ ...fieldMap['halfcalpoint'], ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>,
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3rj6pe`}
              fieldConfig={{ ...fieldMap['halfcalpoint2cross'], ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        ]
      }
      return (
        <div className='cust'>
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@h7g775`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
          {
            coms
          }
        </div>
      );
    },
    halfcalpoint: (field, textAreaProps, form, formParams) => null,
    halfcalpoint2cross: (field, textAreaProps, form, formParams) => null,
    color: (field, textAreaProps, form, formParams) => {
      return (
        <div className='cust'>
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@15bao6`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
            <div className='helpful'>
              <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@2yhabq`} title={field.helpfulTip} />
            </div>
          </div>
        </div>
      );
    },
    permitlateminutes: (field, textAreaProps, form, formParams) => (
      <LinkComs ecId={`${this && this.props && this.props.ecId || ''}_LinkComs@mfn5gg`} {...{field, textAreaProps, form, formParams, linkKey: 'enableexcludelate'}} />
    ),
    seriouslateminutes: (field, textAreaProps, form, formParams) => (
      <LinkComs ecId={`${this && this.props && this.props.ecId || ''}_LinkComs@pwn8wx`} {...{field, textAreaProps, form, formParams}} />
    ),
    lateabsentminutes: (field, textAreaProps, form, formParams) =>
      this.itemRender.seriouslateminutes(field, textAreaProps, form, formParams),
    permitleaveearlyminutes: (field, textAreaProps, form, formParams) => (
      <LinkComs ecId={`${this && this.props && this.props.ecId || ''}_LinkComs@4eer72`} {...{field, textAreaProps, form, formParams, linkKey: 'enableexcludeleaveearly'}} />
    ),
    seriousleaveearlyminutes: (field, textAreaProps, form, formParams) =>
      this.itemRender.seriouslateminutes(field, textAreaProps, form, formParams),
    leaveearlyabsentminutes: (field, textAreaProps, form, formParams) =>
      this.itemRender.seriouslateminutes(field, textAreaProps, form, formParams),
    enableexcludelate: (field, textAreaProps, form, formParams) => null,
    enableexcludeleaveearly: (field, textAreaProps, form, formParams) =>null,
    cardRemind: (field, textAreaProps, form, formParams) => {//打卡提醒
      return (<div className='cardRemind'>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@gj1m5p`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
              onChange={this.handleCardRemindChange}
            />
          </div>)
    },
    
    cardRemOfSignIn: (field, textAreaProps, form, formParams) => {//上班打卡提醒
      const {
        cardRemind
      } = formParams;

      if (cardRemind === '1') {
        return (
          <div className='cardRemOfSignIn'>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@uplv8h`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        )
      }
    },
    minsBeforeSignIn:(field, textAreaProps, form, formParams) => {//提前多少分钟提醒
      const {
        cardRemind,
        cardRemOfSignIn
      } = formParams;

      if ( cardRemind === '1' && cardRemOfSignIn === '1') {
        return (
          <div className='minsBeforeSignIn'>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@lgvol0`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
            <span>{i18n.label["15049"]()}</span>
          </div>
        )
      }
    },
    cardRemOfSignOut: (field, textAreaProps, form, formParams) => {//下班打卡提醒
      const {
        cardRemind
      } = formParams;

      if (cardRemind === '1') {
        return (
          <div className='cardRemOfSignIn'>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4mmlua`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        )
      }
    },
    minsAfterSignOut:(field, textAreaProps, form, formParams) => {//延后多少分钟提醒
      const {
        cardRemind,
        cardRemOfSignOut
      } = formParams;

      if (cardRemind === '1' && cardRemOfSignOut === '1') {
        return (
          <div className='minsAfterSignOut'>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@26alj7`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
            <span>{i18n.label["15049"]()}</span>
          </div>
        )
      }
    },
    remindMode:(field, textAreaProps, form, formParams) => {//提醒方式
      const {
        cardRemind
      } = formParams;

      if (cardRemind==='1') {
        return (
            <div className='remindMode'>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@oakzx1`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
              <p>
                <span onClick={this.handleSettingLinkClick}>{getLabel(512648,'提醒内容设置')}</span>
                <span>{`(${getLabel(512649,'仅适用邮件提醒和短信提醒')})`}</span>
              </p>
            </div>
          )
      }
    },
    remindOnPC:(field, textAreaProps, form, formParams) => {//登陆PC端弹窗提醒
      const {
        cardRemind
      } = formParams;

      if (cardRemind==='1') {
        return (
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3ylne6`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
        )
      }

    },
    earlyinearlyoutsame: (field, textAreaProps, form, formParams) => null,
    lateinlateoutsame: (field, textAreaProps, form, formParams) => null,
    lateoutlateinsame: (field, textAreaProps, form, formParams) => null,
    earlyinearlyout: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      let coms = [];
      if (formParams.earlyinearlyout === "1") {
        coms = [
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@yy8xvg`}
              fieldConfig={{ ...fieldMap['earlyinearlyoutsame'], ...textAreaProps, content: fieldMap["earlyinearlyoutsame"].label }}
              form={form}
              formParams={formParams}
            />
            <span className="example-description" onClick={ () => this.handleMsgLabelClick("earlyinearlyout")}>示例说明</span>
          </div>
        ]
      }
      return (
        <div className='cust'>
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@c4tkur`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
          {
            coms
          }
        </div>
      )
    },
    lateinlateout: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      let coms = [];
      if (formParams.lateinlateout === "1") {
        coms = [
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@mamigh`}
              fieldConfig={{ ...fieldMap['lateinlateoutsame'], ...textAreaProps, content: fieldMap["lateinlateoutsame"].label }}
              form={form}
              formParams={formParams}
            />
            <span className="example-description" onClick={ () => this.handleMsgLabelClick("lateinlateout")}>示例说明</span>
          </div>
        ]
      }
      return (
        <div className='cust'>
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bvu5i5`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
          {
            coms
          }
        </div>
      )
    },
    lateoutlatein: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      let coms = [];
      if (formParams.lateoutlatein === "1") {
        coms = [
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1s4ca5`}
              fieldConfig={{ ...fieldMap['lateoutlateinsame'], ...textAreaProps, content: fieldMap["lateoutlateinsame"].label }}
              form={form}
              formParams={formParams}
            />
            <span className="example-description" onClick={ () => this.handleMsgLabelClick("lateoutlatein")}>示例说明</span>
          </div>
        ]
      }
      return (
        <div className='cust'>
          <div className="child">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@lvku6g`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
          {
            coms
          }
        </div>
      )
    },
    overtime_rule_id: (field, textAreaProps, form, formParams) => {
      return (
        <div style={{width: 176}}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@lvku6g`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
        </div>
      )
    },
    convert_attend_day: (field, textAreaProps, form, formParams) => {
      return (
        <div style={{width: 176}}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@lvku6g`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
        </div>
      )
    },

  };
  

  stopBubble = (e) => {
    e.stopPropagation &&e.stopPropagation();
    e.preventDefault && e.preventDefault();
  }

  handleCardRemindChange = (datas) => {
    const {
      cardRemind
    } = datas;

    if (cardRemind.value === '0') {
      this.formTarget.baseForm.updateFields({
        cardRemOfSignIn: '1',
        cardRemOfSignOut: '1',
        remindMode:'1',
        remindOnPC:'0',

      });
    }
  }

  @observable dialogStore = new DialogStore(this);
  @observable searchStore = new SearchStore('', this);

  @observable remindLoaing = false;

  @observable checkedReminderType = 0;//选中的提醒类型

  @observable emailRemindContent = {
    title:'',
    content:'',
    params:'',
  }; 
  @observable emailRemindTypeDatas=[];

  @observable msgRemindContent = {
    content:'',
    params:'',
  };
  @observable msgRemindTypeDatas=[];

  requestRemindContentTimes = 0;

  get dialogConfig(){
    return {
      title: getLabel(512648,'提醒内容设置'),
      style: {
        width: 700,
        height: 500
      }
    }
  }

  get DialogButtons() {
      return (
        [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ho70xe`} type='primary' onClick={this.handleSaveRemindSettingClick}>{getLabel(505564, '保存')}</Button>,
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@01061q`} type='primary' onClick={this.handleRestoreDefaultSettingClick}>{getLabel(512684, '恢复默认设置')}</Button>
        ]
      )
  }

  get MoreBtn() {
    return {
      datas: [{
          key: "1",
          disabled: false,
          icon: <i className="icon-coms-Save-as" />,
          content: getLabel(505564, '保存'),
          onClick: this.handleSaveRemindSettingClick
      },{
          key: "2",
          disabled: false,
          icon: <i className="icon-coms-Reset" />,
          content: getLabel(512684, '恢复默认设置'),
          onClick: this.handleRestoreDefaultSettingClick
      }]
    }
  }

  get searchConfig() {
    return {
      searchMoreProps: {
        searchType: []
      },
      datas:[{
        key:'0',
        title:getLabel(512714,'邮件提醒')
      },{
        key:'1',
        title:getLabel(512650,'短信提醒')
      }]
    }
  }

  //提醒类型可编辑列表的columns
  get remindTypeColumns() {
    const {
      selectedKey
    } = this.searchStore;

    const columns = [{
      title: '',
      dataIndex: 'radio',
      width: '10%',
      com: [{
        type: "RADIO",
        key: "radio"
      }]
    }, {
      title: getLabel(512657, '提醒类型'),
      dataIndex: 'type',
      width: '30%',
      com: [{
        type: "INPUT",
        key: "type",
        viewAttr: 1
      }]
    }, {
      title: getLabel(125926, '提醒标题'),
      dataIndex: 'title',
      width: '30%',
      com: [{
        type: "INPUT",
        key: "title",
        viewAttr: 1
      }]
    }, {
      title: getLabel(512658, '提醒内容'),
      dataIndex: 'content',
      width: '30%',
      com: [{
        type: "INPUT",
        key: "content",
        viewAttr: 1
      }]
    }];
    if (selectedKey === '0') {
      return columns
    } else {
      return columns.filter(col => col.dataIndex !== 'title')
    }
  };

  //提醒内容设置组的标题
  @computed get searchGroupTitles() {
    const titles = [getLabel(512653, '提醒类型（点击列表行可修改提醒内容）')];
    const label = getLabel(506919, '内容设置');

    if (this.checkedReminderType === 0) {
      titles.unshift(`${label}-${getLabel(512651,'上班打卡提醒')}`);
    } else {
      titles.unshift(`${label}-${getLabel(512652,'下班打卡提醒')}`);
    }

    return titles
  }

  //点击"提醒内容设置"
  handleSettingLinkClick = () => {
    const {
      setDialogConfig,
      openDialog
    } = this.dialogStore, {
      setSearchConfig,
      setSelectedKey
    } = this.searchStore;

    setSearchConfig(this.searchConfig);
    setSelectedKey('0');

    setDialogConfig(this.dialogConfig);
    openDialog();

    //新建班次只需调用一次提醒内容设置相关的接口
    if (this.dialogParams.opType === 'create' && this.requestRemindContentTimes === 1) {
      return;
    }

    this.getEmailRemindInfo().then(()=>{
      this.getMessageRemindInfo().then(() => {
        if (this.dialogParams.opType === 'create') {
            this.requestRemindContentTimes = 1;
        }
      });
    });
  }

  //保存提醒内容
  handleSaveRemindSettingClick=()=>{
    if (this.dialogParams.opType === 'create') {
      this.dialogStore.closeDialog();
    }else{
      this.saveRemindContent();
    }
  }

  //保存提醒内容
  saveRemindContent = () => {
    return new Promise((resolve, reject) => {
      this.saveEmailRemind().then(() => {
        this.saveMessageRemind().then(() => {
          resolve();
        });
      })
    })
  }

  //恢复提醒内容默认设置
  handleRestoreDefaultSettingClick = () => {
    const {
      selectedKey
    } = this.searchStore;

    if (selectedKey === '0') {
      this.emailRemindTypeDatas = this.emailDefaultDatas;
    }else{
      this.msgRemindTypeDatas = this.msgDefaultDatas;
    }

    this.changeRemindContent();
  }

  //获取邮件提醒信息
  getEmailRemindInfo = () => {
    this.remindLoaing = true;

    return new Promise((resolve, reject) => {
      const params = {};
      if (this.dialogParams.opType === 'edit') {
        Object.assign(params, {
          serialId: this.opId
        });
      };
      api.getEmailRemindForm(params).then(cb => {
        const {
          datas,
          defaultDatas,
          signInParams,
          signOutParams
        } = cb;

        this.emailRemindTypeDatas = datas;
        this.emailDefaultDatas = defaultDatas;
        this.emailSignInParams = signInParams;
        this.emailSignOutParams = signOutParams;

        this.changeRemindContent();

        resolve();

      })
    })
  }

  //获取短信提醒信息
  getMessageRemindInfo = () => {
    return new Promise((resolve, reject) => {
      const params = {};
      if (this.dialogParams.opType === 'edit') {
        Object.assign(params, {
          serialId: this.opId
        });
      };
      api.getMessageRemindForm(params).then(cb => {
        const {
          datas,
          defaultDatas,
          signInParams,
          signOutParams
        } = cb;

        this.msgRemindTypeDatas = datas;
        this.msgDefaultDatas = defaultDatas;
        this.msgSignInParams = signInParams;
        this.msgSignOutParams = signOutParams;

        this.remindLoaing = false;

        resolve();

      })
    })
  }

  //保存邮件提醒
  saveEmailRemind = () => {
    this.remindLoaing = true;

    return new Promise((resolve, reject) => {
      const params = {
        serialId: this.opId,
        datas: JSON.stringify(this.emailRemindTypeDatas)
      };
      api.saveEmailRemind(params).then(datas => {
        const {
          status,
          sign,
        } = datas;

        if (status === '1' || sign === '1') {
          resolve();
        }else{
          message.error(datas.message);
        }
      })
    })
  }

  //保存信息提醒
  saveMessageRemind = () => {
    return new Promise((resolve, reject) => {
      const params = {
        serialId: this.opId,
        datas: JSON.stringify(this.msgRemindTypeDatas)
      };
      api.saveMessageRemind(params).then(datas => {
        const {
          status,
          sign,
        } = datas;

        if (status === '1' || sign === '1') {
          this.remindLoaing = false;
          this.dialogStore.closeDialog();
          resolve();
        }else{
          message.error(datas.message);
        }
      })
    })
  }

  //修改邮件标题
  handleRemindTitleChange = (title) => {
    this.emailRemindContent.title = title;

    this.changeTableEditDatas('title')
  }

  //修改邮件内容
  handleRemindContentChange = (content) => {
    const {
      selectedKey
    } = this.searchStore;

    if (selectedKey === '0') {
      this.emailRemindContent.content = content;
    } else {
      this.msgRemindContent.content = content;
    }

    this.changeTableEditDatas('content');
  }

  //双击可用参数
  handleParamsDoubleClick = (event) => {
    this.remindTextAreaRef.setValue(`[${event.target.innerText}]`);

    this.changeTableEditDatas('content');
  }

  //改变可编辑列表的数据
  changeTableEditDatas = (type) => {
    const {
      selectedKey
    } = this.searchStore;

    const datas = (selectedKey === '0') ? this.emailRemindTypeDatas : this.msgRemindTypeDatas;

    let value;
    if (selectedKey === '0') {
      const {
        title,
        content
      } = this.emailRemindContent;
      value = (type === 'title') ? title : content;
    } else {
      value = this.msgRemindContent.content;
    }
    datas.forEach(data => {
      if (data.radio === '1') {
        if (type === 'title') {
          data.title = value;
        } else {
          data.content = value;
        }
      }
    })
  }

  //设置文本域ref
  setTextareaRef=(ref)=>{
    this.remindTextAreaRef=ref;
  }

  //切换radio
  handleTableEditChange = (datas) => {
    const {
      selectedKey
    } = this.searchStore;

    if (selectedKey === '0') {
      this.emailRemindTypeDatas = datas;
    } else {
      this.msgRemindTypeDatas = datas;
    }

    this.changeRemindContent();
  }

  @action changeRemindContent = () => {
    let datas, rContent, signInParams, signOutParams;

    const {selectedKey}= this.searchStore;

    if (selectedKey === '0') {
      datas = this.emailRemindTypeDatas;
      rContent = this.emailRemindContent;
      signInParams = this.emailSignInParams;
      signOutParams = this.emailSignOutParams;
    } else {
      datas = this.msgRemindTypeDatas;
      rContent = this.msgRemindContent;
      signInParams = this.msgSignInParams;
      signOutParams = this.msgSignOutParams;
    }

    //获取被选中提醒类型的索引值
    this.checkedReminderType = datas.findIndex(data => data.radio === '1');

    const {
      title,
      content
    } = datas.find(data => data.radio === '1');

    Object.assign(rContent, {
      title,
      content,
    });

    if (this.checkedReminderType === 0) {
      Object.assign(rContent, {
        params: (typeof signInParams === 'string') ? signInParams.split(',') : signInParams
      });
    } else {
      Object.assign(rContent, {
        params: (typeof signOutParams === 'string') ? signOutParams.split(',') : signOutParams
      });
    }

  }

  //切换【提醒内容设置】页签
  handleTabClick = () => {
    this.changeRemindContent();
  }

  childrenComponents = {
    shiftonoffworkcount: () => {
      const formParams = this.formTarget.baseForm.getFormParams();
       /*if (formParams.shiftonoffworkcount != "1") {
        this.formTarget.baseForm.updateFields({
          isresttimeopen: {
            value: "0"
          }
        });
      }*/
      let coms = [], worktimes = this.toJS(this.worktimes);
      if (worktimes.length === 0) return [];
      for (let i = 1; i <= Number(formParams.shiftonoffworkcount); i++) {
        const label = i18n.label["388782"]().replace("{params}", i);
        let timeConfig = worktimes[i - 1];
        coms.push(
          <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@28bi3e@${i}`}
            label={label}
            labelCol={{ span: this.custLabelCol }}
            wrapperCol={{ span: 24 - this.custLabelCol }}
          >
            <div className="workCust">
              <div className="cust">
                <div className="child">
                  <div className="lbl1" style={{width: 90}}>{i18n.label["125809"]()}</div>
                  <div className="restTime">
                    <WeaTimePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaTimePicker@r7kn14@${i}`}
                      key={timeConfig.start.key}
                      value={timeConfig.start.times}
                      onChange={v => this.onTimeChange(i - 1, v)}
                    />
                  </div>
                  {timeConfig.start.across === '1' && (
                    <div className="restTimeInfo">{i18n.label["388785"]()}</div>
                  )}
                  {formParams.punchsettings === "1" && (
                    <div
                      className="minutes"
                      style={{
                        marginLeft: timeConfig.start.across === '1' ? 0 : 10
                      }}
                    >
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@1ysdmj@${i}`} tipPosition='bottom'
                        ref={d => this.errRefs[`s${i - 1}-0`] = d}
                        error={this.rangeTimeError}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@3tbfae@${i}`}
                          min={1}
                          max={1440}
                          value={timeConfig.start.mins}
                          defaultValue={timeConfig.start.mins}
                          tip={i18n.label["388786"]()}
                          onChange={v => (this.worktimes[i - 1].start.mins = (v || 1))}
                        />
                      </WeaError>
                    </div>
                  )}
                </div>
                <div className="child">
                  {formParams.punchsettings === "1" && (
                    <div
                      className="minutes"
                      style={{ marginLeft: timeConfig.start.across === '1' ? 0 : 10 }}
                    >
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@qfgmii@${i}`} tipPosition='bottom'
                        ref={d => this.errRefs[`s${i - 1}-1`] = d}
                        error={this.rangeTimeError}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@a5g8dd@${i}`}
                          min={0}
                          max={1440}
                          value={timeConfig.start.mins_next}
                          defaultValue={timeConfig.start.mins_next}
                          tip={i18n.label["388787"]()}
                          onChange={v => (this.worktimes[i - 1].start.mins_next = v)}
                        />
                             
                      </WeaError>
               
                    </div>
                  )}
                </div>

                  <div style={{margin:'5px 0 0 50px'}}>
                    <WeaCheckbox
                      id="test"
                      value={timeConfig.start.clockinnot}
                      onChange={
                        v => (this.worktimes[i - 1].start.clockinnot = (v || 1))
                      }
                    />
                  </div>
                <div style={{margin:'10px 0 0 10px'}}>{getLabel('540846','无需打卡')}</div>

                      
              </div>
              <div className="cust">
                <div className="child"> 
                  <div className="lbl1" style={{width: 90}}>{i18n.label["125810"]()}</div>
                  <div className="restTime">
                    <WeaTimePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaTimePicker@jov4v8@${i}`}
                      key={timeConfig.end.key}
                      value={timeConfig.end.times}
                      onChange={v => this.onTimeChange(i - 1, v, false)}
                    />
                  </div>
                  {timeConfig.end.across === '1' && (
                    <div className="restTimeInfo">{i18n.label["388785"]()}</div> 
                  )}
                  {formParams.punchsettings === "1" && (
                    <div
                      className="minutes"
                      style={{
                        marginLeft: timeConfig.end.across === '1' ? 0 : 10
                      }}
                    >
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@4m8ikk@${i}`} tipPosition='bottom'
                        ref={d => this.errRefs[`e${i - 1}-1`] = d}
                        error={this.rangeTimeError}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@vv1hxa@${i}`}
                          min={0}
                          max={1440}
                          value={timeConfig.end.mins_next}
                          defaultValue={timeConfig.end.mins_next}
                          tip={i18n.label["388786"]()}
                          onChange={v => (this.worktimes[i - 1].end.mins_next = v)}
                        />
                      </WeaError>
                    </div>
                  )}
                </div>
                <div className="child">
                  {formParams.punchsettings === "1" && (
                    <div
                      className="minutes"
                      style={{ marginLeft: timeConfig.end.across === '1' ? 0 : 10 }}
                    >
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@a7n7pe@${i}`} tipPosition='bottom'
                        ref={d => this.errRefs[`e${i - 1}-0`] = d}
                        error={this.rangeTimeError}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@hnlc8d@${i}`}
                          min={1}
                          max={1440}
                          value={timeConfig.end.mins}
                          defaultValue={timeConfig.end.mins}
                          tip={i18n.label["388787"]()}
                          onChange={v => (this.worktimes[i - 1].end.mins = (v || 1))}
                        />
                      </WeaError>
                    </div>
                  )}
                </div>



                <div style={{margin:'5px 0 0 50px'}}>
                    <WeaCheckbox
                      id="test"
                      value={timeConfig.end.clockinnot}
                      onChange={
                        v => (this.worktimes[i - 1].end.clockinnot = (v || 1))
                      }
                    />
                  </div>
                <div style={{margin:'10px 0 0 10px'}}>{getLabel('540846','无需打卡')}</div>

              </div>
            </div>
            
            {i === Number(formParams.shiftonoffworkcount) && (
              <WorkTimeAnalysis ecId={`${this && this.props && this.props.ecId || ''}_WorkTimeAnalysis@xqkwk3@${i}`} store={this} />
            )}
          </WeaFormItem>
        );
      }
      return [
        {
          com: <div className="times">{coms}</div>,
          col: 1
        }
      ];
    },
    isresttimeopen: () => {
      const formParams = this.formTarget.baseForm.getFormParams();
      const { fieldMap } = this.formTarget.baseForm;
      if (formParams.isresttimeopen != "1") {
        return [];
      }
      const coms = [];
      this.restTimeCollection.forEach((d, index) => {
        const {record, start, end} = d;
        const {time: sTime = '12:00', accross: sAccross = '0'} = start || {};
        const {time: eTime, accross: eAccross = '0'} = end || {};
        coms.push(
          <WeaFormItem
            label={`${fieldMap['isresttimeopen'].label}${index + 1}`}
            labelCol={{ span: this.custLabelCol }}
            wrapperCol={{ span: 24 - this.custLabelCol }}
          >
            <div className="cust">
              <div className="child">
                <div className="lbl">{fieldMap["restbeigin"].label}</div>
                <div className="restTime">
                  <WeaError tipPosition='bottom'
                      ref={d => this.errRefs[`restbeigin${index}`] = d}
                      error={`"${fieldMap["restbeigin"].label}" ${i18n.message.dataEmpty()}`}>
                        <WeaTimePicker
                          value={sTime}
                          onChange={v => {
                            this.restTimeCollection[index].start.time = v;
                            this.calculateWorkTime();
                          }
                          }
                        />
                  </WeaError>
                </div>
                {
                  sAccross == '1' &&
                  <div className="restTimeInfo">{i18n.label["388785"]()}</div>
                }
              </div>
              <div className="child">
                <div className="lbl">{fieldMap["restend"].label}</div>
                <div className="restTime">
                  <WeaError tipPosition='bottom'
                      ref={d => this.errRefs[`restend${index}`] = d}
                      error={`"${fieldMap["restend"].label}" ${i18n.message.dataEmpty()}`}>
                        <WeaTimePicker
                          value={eTime}
                          onChange={v =>{
                            this.restTimeCollection[index].end.time = v;
                            this.calculateWorkTime();
                          }
                          }
                        />
                  </WeaError>
                </div>
                {
                  eAccross == '1' &&
                  <div className="restTimeInfo">{i18n.label["388785"]()}</div>
                }
              </div>
              <div className="child">
                <a onClick={() => this.deleteRest(index)}>
                  {i18n.label.delete()}
                </a>
              </div>
            </div>
          </WeaFormItem>
        );
      })
      coms.push(
        (
          <div className="addRule">
            <a onClick={() => this.onAddrest()}>{i18n.label["388877"]()}</a>
          </div>
        )
      )
      return [
        {
          com: <div>{coms}</div>,
          col: 1
        }
      ];
    },
    earlyinearlyout: () => {
      const formParams = this.formTarget.settingForm.getFormParams();
      let coms = [];
      if (formParams.earlyinearlyout === "1") {
        if(formParams.earlyinearlyoutsame === "1"){
          const label = i18n.label["388587"]();
          let info = i18n.label["513861"]().replace("{time1}", this.lateRules.earlyinearlyout.advancetime || '');
          coms.push(
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pjuztg`}
              label={label}
              labelCol={{ span: this.custLabelCol }}
              wrapperCol={{ span: 24 - this.custLabelCol }}
            >
              <div className="cust">
                <div className="child">
                  <div className="lbl">{i18n.label["513617"]()}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@8simxw`} tipPosition='bottom'
                      ref={d => this.errRefs[`earlyinearlyout-advancetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@rvaee9`}
                          min={1}
                          max={1440}
                          value={this.lateRules.earlyinearlyout.advancetime}
                          onChange={ v =>(
                              this.lateRules.earlyinearlyout.advancetime = v
                          )}
                      />
                    </WeaError>
                  </div>
                  <div className="lbl">{i18n.label["15049"]()}</div>
                  <div className="lbl-info">{info}</div>
                </div>
              </div>
            </WeaFormItem>
          );
        }else{
          const label = i18n.label["388587"]();
          const time1 = this.calculateTime(
            this.worktimes[0].start.times,
            this.lateRules.earlyinearlyout.advancetime,
            false
          ),
          time2 = this.calculateTime(
            this.worktimes[this.worktimes.length - 1].end.times,
            this.lateRules.earlyinearlyout.postponetime,
            false
          );
          let info = i18n.label["513858"]().replace("{time1}", time1 || '');
          info = info.replace("{time2}", time2 || '');
          coms.push(
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ntj250`}
              label={label}
              labelCol={{ span: this.custLabelCol }}
              wrapperCol={{ span: 24 - this.custLabelCol }}
            >
              <div className="cust">
                <div className="child">
                  <div className="lbl">{i18n.label["388868"]()}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@z59czf`} tipPosition='bottom'
                      ref={d => this.errRefs[`earlyinearlyout-advancetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@wko4v9`}
                            min={1}
                            max={1440}
                            value={this.lateRules.earlyinearlyout.advancetime}
                            onChange={ v =>(
                                this.lateRules.earlyinearlyout.advancetime = v
                            )}
                        />
                    </WeaError>
                  </div>
                  <div className="lbl">{getLabel(508152,'分钟，下班可以早走')}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@pqz7it`} tipPosition='bottom'
                      ref={d => this.errRefs[`earlyinearlyout-postponetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@t3hpvf`}
                            min={1}
                            max={1440}
                            value={this.lateRules.earlyinearlyout.postponetime}
                            onChange={
                                v =>(
                                this.lateRules.earlyinearlyout.postponetime = v
                            )}
                        />
                      </WeaError>
                  </div>
                  <div className="lbl">{i18n.label["15049"]()}</div>
                  <div className="lbl-info">{info}</div>
                </div>
              </div>
            </WeaFormItem>
          );
        }
        
        return [
          {
            com: <div>{coms}</div>,
            col: 1
          }
        ];
      } else return [];
    },
    lateinlateout: () => {
      const formParams = this.formTarget.settingForm.getFormParams();
      let coms = [];
      if (formParams.lateinlateout === "1") {
        if(formParams.lateinlateoutsame === "1"){
          const label = i18n.label["388591"]();
          let info = i18n.label["513862"]().replace("{time1}", this.lateRules.lateinlateout.advancetime || '');
          coms.push(
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@ot3am4`}
              label={label}
              labelCol={{ span: this.custLabelCol }}
              wrapperCol={{ span: 24 - this.custLabelCol }}
            >
              <div className="cust">
                <div className="child">
                  <div className="lbl">{i18n.label["513618"]()}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@zjkup6`} tipPosition='bottom'
                      ref={d => this.errRefs[`lateinlateout-advancetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@fh537s`}
                          min={1}
                          max={1440}
                          value={this.lateRules.lateinlateout.advancetime}
                          onChange={ v =>(
                              this.lateRules.lateinlateout.advancetime = v
                          )}
                      />
                      </WeaError>
                  </div>
                  <div className="lbl">{i18n.label["15049"]()}</div>
                  <div className="lbl-info">{info}</div>
                </div>
              </div>
            </WeaFormItem>
          );
        }else{
          const label = i18n.label["388591"]();
          const time1 = this.calculateTime(
              this.worktimes[0].start.times,
              this.lateRules.lateinlateout.advancetime
            ),
            time2 = this.calculateTime(
              this.worktimes[this.worktimes.length - 1].end.times,
              this.lateRules.lateinlateout.postponetime
            );
          let info = i18n.label["513859"]().replace("{time1}", time1 || '');
          info = info.replace("{time2}", time2 || '');
          coms.push(
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@pt3m4d`}
              label={label}
              labelCol={{ span: this.custLabelCol }}
              wrapperCol={{ span: 24 - this.custLabelCol }}
            >
              <div className="cust">
                <div className="child">
                  <div className="lbl">{i18n.label["388871"]()}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@phzzy9`} tipPosition='bottom'
                      ref={d => this.errRefs[`lateinlateout-advancetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@fugwcz`}
                          min={1}
                          max={1440}
                          value={this.lateRules.lateinlateout.advancetime}
                          onChange={ v =>(
                              this.lateRules.lateinlateout.advancetime = v
                          )}
                      />
                    </WeaError>
                  </div>
                  <div className="lbl">{i18n.label["508155"]()}</div>
                  <div className="select">
                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@nzgn8f`} tipPosition='bottom'
                      ref={d => this.errRefs[`lateinlateout-postponetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                      <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@hv2cwz`}
                          min={1}
                          max={1440}
                          value={this.lateRules.lateinlateout.postponetime}
                          onChange={ v =>(
                              this.lateRules.lateinlateout.postponetime = v
                          )}
                      />
                    </WeaError>
                  </div>
                  <div className="lbl">{i18n.label["15049"]()}</div>
                  <div className="lbl-info">{info}</div>
                </div>
              </div>
            </WeaFormItem>
          );
        }
        return [
          {
            com: <div>{coms}</div>,
            col: 1
          }
        ];
      } else return [];
    },
    lateoutlatein: () => {
      const formParams = this.formTarget.settingForm.getFormParams();
      let coms = [];
      const rules = this.toJS(this.lateRules);
      if (formParams.lateoutlatein === "1") {
        if (formParams.lateoutlateinsame === "1") {
          rules.lateoutlatein.map((rule, index) => {
            const label = `${i18n.label["388592"]()}${index + 1}`;
            let info = i18n.label["513863"]().replace("{time1}", this.lateRules.lateoutlatein[index].advancetime || '');
            coms.push(
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@7yn9dt`}
                label={label}
                labelCol={{ span: this.custLabelCol }}
                wrapperCol={{ span: 24 - this.custLabelCol }}
              >
                <div className="cust">
                  <div className="child">
                    <div className="lbl">{i18n.label["513619"]()}</div>
                    <div className="select">
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@mmk68v`} tipPosition='bottom'
                      ref={d => this.errRefs[`lateoutlatein-${index}-advancetime`] = d}
                      error={getLabel('522833','时间段必填')}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@4oa0pz`}
                          min={1}
                          max={1440}
                          value={rule.advancetime}
                          onChange={v =>
                            (this.lateRules.lateoutlatein[index].advancetime = v)
                          }
                        />
                      </WeaError>
                    </div>
                    <div className="lbl">{i18n.label["15049"]()}</div>
                    <div className="lbl-info">{info}</div>
                    {rules.lateoutlatein.length >= 1 && formParams.lateoutlateinsame !== "1" && (
                      <div>
                        <a onClick={() => this.ruleOp(index, false)}>
                          {i18n.label.delete()}
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              </WeaFormItem>
            );
          });
          if (rules.lateoutlatein.length < 3) {
            coms.push(
              <div className="addRule">
                <a onClick={() => this.ruleOp()}>{i18n.label["388877"]()}</a>
              </div>
            );
          }
          if(formParams.lateoutlateinsame === "1"){
            coms = [coms[0]];
          }
          return [
            {
              com: <div>{coms}</div>,
              col: 1
            }
          ];
        }else{
          rules.lateoutlatein.map((rule, index) => {
            const label = `${i18n.label["388592"]()}${index + 1}`;
            const time1 = this.calculateTime(
                this.worktimes[this.worktimes.length - 1].end.times,
                this.lateRules.lateoutlatein[index].advancetime
              ),
              time2 = this.calculateTime(
                this.worktimes[0].start.times,
                this.lateRules.lateoutlatein[index].postponetime
              );
            let info = i18n.label["513860"]().replace("{time1}", time1 || '');
            info = info.replace("{time2}", time2 || '');
            coms.push(
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@tbgf95`}
                label={label}
                labelCol={{ span: this.custLabelCol }}
                wrapperCol={{ span: 24 - this.custLabelCol }}
              >
                <div className="cust">
                  <div className="child">
                    <div className="lbl">{i18n.label["388874"]()}</div>
                    <div className="select">
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@gjbi3k`} tipPosition='bottom'
                        ref={d => this.errRefs[`lateoutlatein-${index}-advancetime`] = d}
                        error={getLabel('522833','时间段必填')}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@3l0xy5`}
                          min={1}
                          max={1440}
                          value={rule.advancetime}
                          onChange={v =>
                            (this.lateRules.lateoutlatein[index].advancetime = v)
                          }
                        />
                      </WeaError>
                    </div>
                    <div className="lbl">{i18n.label["513616"]()}</div>
                    <div className="select">
                      <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@kalaq2`} tipPosition='bottom'
                        ref={d => this.errRefs[`lateoutlatein-${index}-postponetime`] = d}
                        error={getLabel('522833','时间段必填')}>
                        <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@jpf7l4`}
                          min={1}
                          max={1440}
                          value={rule.postponetime}
                          onChange={v =>
                            (this.lateRules.lateoutlatein[index].postponetime = v)
                          }
                        />
                      </WeaError>
                    </div>
                    <div className="lbl">{i18n.label["15049"]()}</div>
                    <div className="lbl-info">{info}</div>
                    {rules.lateoutlatein.length >= 1 && (
                      <div>
                        <a onClick={() => this.ruleOp(index, false)}>
                          {i18n.label.delete()}
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              </WeaFormItem>
            );
          });
          if (rules.lateoutlatein.length < 3) {
            coms.push(
              <div className="addRule">
                <a onClick={() => this.ruleOp()}>{i18n.label["388877"]()}</a>
              </div>
            );
          }
          return [
            {
              com: <div>{coms}</div>,
              col: 1
            }
          ];
        }
        
      } else return [];

    }
  };

  
  /********************* unobservable list *********************/

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

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

  /********************* observable list *********************/
  @observable
  spinning = false;
  @observable
  selectedSubCompany;
  @observable
  table = new TableStore();
  @observable
  worktimes = [];
  @observable
  hour = 0;
  @observable
  minute = 0;
  @observable
  lateRules = {
    earlyinearlyout: {
      advancetime: "30",
      postponetime: "30"
    },
    lateinlateout: {
      advancetime: "30",
      postponetime: "30"
    },
    lateoutlatein: []
  };
  @observable restTimeSections = [
    {
      resttype: "start",
      time: '',
      across: ''
    },
    {
      resttype: "end",
      time: '',
      across: ''
    }
  ];
  @observable
  refreshCalRs = new Date().getTime();
  @observable
  editTabConfig = {
    tabs: [],
    keyParam: "viewCondition",
    activeTabKey: "1",
    tabChangeHandle: key => this.setActiveTab(key)
  };

  @observable canAdd = false;
  @observable canCreate = false;
  @observable canDel = false;

  dialogParams = {
    ...this.dialogPropsDef,
    opType: "create",
    style: {
      width: 500,
      height: 165
    },
    onCancel: () => {
      this.dialogParams.visible = false;
      this.dialogParams.opType = "create";
      this.opId = null;
    }
  };

  @observable timeErrorType = 1;
  
  @observable restTimeCollection = [];
  /********************* observable list *********************/

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

  @computed get rangeTimeError(){
    return this.timeErrorType == 1 ? getLabel('505756','打卡时段无法重叠') : getLabel('505757','打卡时段无法跨两天');
  }
  /********************* computed list *********************/

  /********************* action list *********************/
  @action onAddrest = () => {
    this.restTimeCollection.push({
      record: uuid(),
      start: {time: '', accross: '0'},
      end: {time: '', accross: '0'}
    });

    this.calculateWorkTime();
  }

  @action deleteRest = index => {
    this.restTimeCollection.splice(index, 1);
    this.calculateWorkTime();
  }

  setRuleOptions = () => {
    this.ruleOptions.length = 0;
    for (let i = 0; i < 10; i++) {
      for (let j = 1; j <= 2; j++) {
        this.ruleOptions.push({
          key: i + j / 2,
          showname: (i + j / 2).toString()
        });
      }
    }
  };
  @action
  init = () => {
    this.selectedSubCompany = null;
    this.setRuleOptions();
    this.containerInitFinished.init = true;
    api.init().then(
      rs => {
        rs.map((data, index) => {
          if (data.status === "1") {
            switch (index) {
              case 0:
                this.rightMenus = data.rightMenu;
                break;
              case 1:
                let tabs = [];
                data.tabs.map(tab => {
                  tabs.push({
                    color: "#000000",
                    groupId: `g{tab.key}`,
                    title: tab.title,
                    viewCondition: tab.key
                  });
                });
                this.editTabConfig.tabs = tabs;
                break;
            }
          }
        });
        this.getTableData();
      },
      error => {}
    );
  };

  @computed
  get getTopProps(){
    let buttons = [];
    this.canCreate && buttons.push((
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0ce5je`} type="primary" op="create" onClick={() => this.getCreateForm()}>
        {i18n.label.create()}
      </Button>
    ));
    this.canDel && buttons.push((
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1kp36g`}
        type="primary"
        op="remove"
        disabled={this.tableMultiDelete}
        onClick={() => this.doDelete()}
      >
        {i18n.label.multiDelete()}
      </Button>
    ));

    let menus = this.convertToMenus(buttons);
    return {
      buttons,
      menus: [
        ...menus,
        ...this.getBasicMenus("HRM_ENGINE_SHIFTMANAGER")
      ]
    };
  };

  @action
  treeNodeClick = (event, ids, nodeids, nodes) => {
    const { data: nodeData } = event.node.props;
    this.selectedSubCompany = nodeData;
    this.getTableData();
  };

  @action
  clearData = () => {
    this.worktimes.length = 0;
    this.lateRules.lateoutlatein.lenght = 0;
    this.requestRemindContentTimes = 0;
  };

  @action
  getTableData = (params = {}) => {
    this.searchParams = params;
    Object.assign(params, {
      subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null
    });
    api.getShiftManagementSearchList(params).then(
      data => {
        if (data.status === "1") {
          this.canCreate = data.canAdd;
          this.canDel = data.canDel;
          this.table = new TableStore();
          this.table.getDatas(data.sessionkey, 1);
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  };

  @action
  getShiftManagementBaseForm = (params, callback) => {
    if (this.spinning) return;
    this.spinning = true;
    api.getShiftManagementBaseForm(params).then(
      data => {
        if (data.status === "1") {
          this.processCondition(data);
          this.canAdd = data.canAdd;
          this.shift_24 = data.shift_24 || 0;
          this.restTimeCollection = data.restTimeSections;
          this.setFormData("baseForm", data.condition);
          if (this.formTarget.baseForm.isFormInit) {
            callback && callback();
          }
        } else {
          message.error(data.message);
        }
        this.spinning = false;
      },
      error => (this.spinning = false)
    );
  };

  processCondition = (data) => {
    const {
      condition
    } = data;

    condition.map(c => c.items.map(item => {
      if (item.domkey[0] === 'remindMode') {
        item.options.map(option => {
          const {
            key,
            showname
          } = option;

          let callback;

          if (key === '2') { //邮件提醒
            callback = (e) => {
              this.stopBubble(e);
              window.open(`/spa/email/static4engine/engine.html#/email/sysSetting`);
            };
          }
          if (key === '3') { //短信提醒
            callback = (e) => {
              this.stopBubble(e);
              window.open(`/spa/smallApp/static4engine/engine.html#/sms/SmsSet`);
            }
          }
          if (key !== '1') {
            option.showname = (
              <span>{showname}<i className='icon-coms-Flow-setting' onClick={callback}/></span>
            );
          }
        })
      }
    }))
  }

  @action
  getCreateForm = () => {
    this.clearData();
    this.getShiftManagementBaseForm(null, () => {
      if(this.selectedSubCompany != null){
        this.formTarget.baseForm.updateFields({
          subcompanyid: {
            value: this.selectedSubCompany.id.toString(),
            valueSpan: this.selectedSubCompany.name,
            valueObj: [{
              id: this.selectedSubCompany.id.toString(),
              name: this.selectedSubCompany.name
            }]
          }
        });
      }
      this.worktimes.push({
        start: {
          ...this.worktimeConstruct,
          times: "09:00",
          key: 's0'
        },
        end: {
          ...this.worktimeConstruct,
          times: "18:00",
          key: 'e0'
        }
      });
      this.calculateWorkTime();
      this.dialogParams.title = i18n.label["388538"]();
      this.dialogParams.opType = "create";
      this.dialogParams.style = {
        width: 1000,
        height: 420
      };
      this.dialogParams.visible = true;
    });
  };

  @action
  onWorkCountChange = v => {
    this.worktimes.length = 0;
    const count = Number(v.shiftonoffworkcount.value);
    for (let i = 1; i <= count; i++) {
      this.worktimes.push({
        start: {
          across: 0,
          mins: i == 1 ? 60 : 30,
          mins_next:'',
          times: count === 1 ? "09:00" : this.sTime[i - 1],
          key: `s${i - 1}`,
          clockinnot:'0'
        },
        end: {
          across: 0,
          mins: i == count ? 60 : 29,
          mins_next:'',
          times: count === 1 ? "18:00" : this.eTime[i - 1],
          key: `e${i - 1}`,
          clockinnot:'0'
        }
      });
    }
    this.calculateWorkTime();
  };

  @action
  onTimeChange = (index, v, isStart = true) => {
    this.worktimeError = false;
    const d = this.toJS(this.worktimes);
    let record = d[index];

    if (v === "") {
      record[isStart ? "start" : "end"].key = new Date().getTime();
      this.worktimes[index] = record;
      return;
    }
    record[isStart ? "start" : "end"].times = v;
    
    let s = this.convertTimeToMoment(record.start.times),
      e = this.convertTimeToMoment(record.end.times);
      
    // if(this.shift_24 == 0 && record.start.across == record.end.across && s.isSame(e)){
    //   this.worktimeError = true;
    //   // return;
    // }

    //计算是否跨天
    if (d.length === 1) {//只有1个班次
      record.end.across = (e.isBefore(s) || e.isSame(s)) ? '1' : '0';
    } else{//多个班次
      if(index == (d.length - 1)){//最后一个班次
        //最后一个班次下班时间与第一个班次上班时间比较
        let lastRecord = d[index - 1];
        let le = this.convertTimeToMoment(lastRecord.end.times);

        if(this.shift_24 == 0 && lastRecord.end.across === '1' && (s.isBefore(le) || e.isBefore(s))){
          this.worktimeError = true;
          // return;
        }else if(s.isBefore(le)){
          record.start.across = record.end.across = '1';
        }else if(e.isBefore(s)){
          record.start.across = lastRecord.end.across;
          record.end.across = "1";
        }else{
          record.start.across = lastRecord.end.across;
          record.end.across = record.start.across;
        }
      }else{
        if(index != 0){
          let lastRecord = d[index - 1];
          let le = this.convertTimeToMoment(lastRecord.end.times);
          record.start.across = s.isBefore(le) ? '1' : lastRecord.end.across;
        }
        record.end.across = e.isBefore(s) ? '1' : record.start.across;
        for (let i = index + 1; i < d.length; i++) {
          record = d[i - 1];

          s = this.convertTimeToMoment(record.start.times);
          e = this.convertTimeToMoment(record.end.times);

          let nextRecord = d[i];

          let nst = this.convertTimeToMoment(nextRecord.start.times);
          let net = this.convertTimeToMoment(nextRecord.end.times);
          if(this.shift_24 == 0 && record.end.across === '1' && (nst.isBefore(e) || net.isBefore(nst))){
            this.worktimeError = true;
            // return;
          }
          if(nst.isBefore(e)){
            nextRecord.start.across = nextRecord.end.across = "1";
          }else if(net.isBefore(nst)){
            nextRecord.start.across = record.end.across;
            nextRecord.end.across = "1";
          }else{
            nextRecord.start.across = record.end.across;
            nextRecord.end.across = nextRecord.start.across;
          }
        }
      }
    }
    this.worktimes = d;
    if(this.worktimeError)
      return;
    this.calculateWorkTime();
  };

  calculateRestTime = (isStart = false) => {
    if(isStart)
      return this.restTimeSections[0].across == '1';
    else
      return this.restTimeSections[1].across == '1';
  }

  checkRestTimeCollection = (times) => {
    this.resttimeRangeError = false;
    if(times.length <= 1)
      return this.resttimeRangeError;
    const obj = times.reduce((current, next) => {
      const {s, e} = next;
      current.start.push(s.format('YYYY-MM-DD HH:mm:ss'));
      current.end.push(e.format('YYYY-MM-DD HH:mm:ss'));
      return current;
    }, {start: [], end: []});
    let {start, end} = obj;
    start = start.sort();
    end = end.sort();

    for(let i = 1; i < start.length; i++){
        if (start[i] <= end[i - 1]){
            console && console.debug("时间有重复！");
            this.resttimeRangeError = true;
        }
    }

    return this.resttimeRangeError;
  }

  calculateWorkTime = () => {
    this.resttimeError = false;
    this.timeRange = 0;
    const formParams = this.formTarget.baseForm.getFormParams();
    let hour = 0,
      minute = 0;
    try {
      const d = this.toJS(this.worktimes);
      if (d.length === 1) {
        let record = d[0];
        let s = this.convertTimeToMoment(record.start.times),
          e = this.convertTimeToMoment(record.end.times);
        if (record.start.across === '1' && record.end.across === '1') {
        } else if (record.end.across === '1') {
          e.add(1, "d");
        }
        minute = Math.abs(s.diff(e, "m"));
        if (formParams.isresttimeopen === "1") {
          const times = [];
          this.restTimeCollection = this.toJS(this.restTimeCollection).map(d => {
            const {record, start, end} = d;
            const {time: restbeigin = ''} = start || {};
            const {time: restend = ''} = end || {};
            let sAcross = '0', eAcross = '0';
            if (restbeigin != "" && restend != "") {
              const rst = this.convertTimeToMoment(restbeigin),
                ret = this.convertTimeToMoment(restend),
                wst = this.convertTimeToMoment(this.worktimes[0].start.times),
                wet = this.convertTimeToMoment(this.worktimes[0].end.times);
              this.worktimes[0].end.across === '1' && wet.add(1, "d");
              if(rst.isBefore(wst)){
                sAcross = '1';
                rst.add(1, 'd');
                ret.add(1, 'd');
              }
              if(ret.isBefore(rst)){
                eAcross = '1';
                ret.add(1, 'd');
              }

              times.push({s: rst, e: ret});
              if (
                rst.isBefore(wst) ||
                rst.isAfter(wet) ||
                ret.isBefore(wst) ||
                ret.isAfter(wet) ||
                rst.isSame(ret)
              ) {
                this.resttimeError = true;
                let ts = rst, te = ret;
                sAcross == '1' && ts.add(-1, 'd') && te.add(-1, 'd');
                if(ts.isAfter(wet)){
                  ts = wet;
                }else if(ts.isBefore(wst))
                  ts = wst;

                if(te.isAfter(wet)){
                  te = wet;
                }
                minute -= Math.abs(ts.diff(te, "m"));
              } else {
                if (ret.isBefore(rst)) ret.add(1, "d");
                minute -= Math.abs(rst.diff(ret, "m"));
              }
              d.start.accross = sAcross;
              d.end.accross = sAcross == '1' ? '1' : eAcross;
            }
            return d;
          });
          this.checkRestTimeCollection(times);
        }
        this.hour = Math.floor(minute / 60);
        this.minute = minute % 60;
      } else {
        let firstS;
        let lastE;
        d.map((record, i) => {
          let s = this.convertTimeToMoment(record.start.times),
            e = this.convertTimeToMoment(record.end.times);
          i == 0 && (firstS = s);
          if (record.start.across === '1' && record.end.across === '1') {
          } else if (record.end.across === '1') {
            e.add(1, "d");
          }
          i == (d.length - 1) && (lastE = e);
          minute += Math.abs(s.diff(e, "m"));
        });
		if (formParams.isresttimeopen === "1") {
				for(let i=0; i<this.worktimes.length; i++) {
          const times = [];
          this.restTimeCollection = this.toJS(this.restTimeCollection).map(d => {
            const {record, start, end} = d;
            const {time: restbeigin = ''} = start || {};
            const {time: restend = ''} = end || {};
            let sAcross = '0', eAcross = '0';
            if (restbeigin != "" && restend != "") {
					const rst = this.convertTimeToMoment(restbeigin),
					ret = this.convertTimeToMoment(restend),
					wst = this.convertTimeToMoment(this.worktimes[i].start.times),
					wet = this.convertTimeToMoment(this.worktimes[i].end.times);
				  this.worktimes[0].end.across === '1' && wet.add(1, "d");
				  if(!(ret.isBefore(wst) || rst.isAfter(wet))){
					  times.push({s: rst, e: ret});
					  if (
						rst.isBefore(wst) ||
						rst.isAfter(wet) ||
						ret.isBefore(wst) ||
						ret.isAfter(wet) ||
						rst.isSame(ret)
					  ) {
						this.resttimeError = true;
						let ts = rst, te = ret;
						sAcross == '1' && ts.add(-1, 'd') && te.add(-1, 'd');
						if(ts.isAfter(wet)){
						  ts = wet;
						}else if(ts.isBefore(wst))
						  ts = wst;

						if(te.isAfter(wet)){
						  te = wet;
						}
						minute -= Math.abs(ts.diff(te, "m"));
					  } else {
						if (ret.isBefore(rst)) ret.add(1, "d");
						minute -= Math.abs(rst.diff(ret, "m"));
					  }
				  }
            }
            return d;
          });
          this.checkRestTimeCollection(times);
				}
        }
        this.hour = Math.floor(minute / 60);
        this.minute = minute % 60;
        this.timeRange = Math.abs(firstS.diff(lastE, "m"));
      }
      this.worktime = minute;
    } catch (ex) {}
    let result = i18n.label["388788"]().replace("{hour}", hour);
    result = result.replace("{minute}", minute);
    return result;
  };

  convertTimeToMoment = time => {
    const arr = time.split(':');
    return this.moment()
    .hour(Number(arr[0]))
    .minute(Number(arr[1]))
    .second(0)
    .millisecond(0);
  }
  
  // compareTime = (start, end) => {
  //   let compareLeft, compareRight, minute, minLeft, minRight, rs = true;
  //   //比较上班开始打卡和下班结束打卡时间是否重叠
  //   compareLeft = this.convertTimeToMoment(start.times);
  //   start.across == '1' && compareLeft.add(1, 'd');
  //   compareRight = this.convertTimeToMoment(end.times);
  //   end.across == '1' && compareRight.add(1, 'd');
  //   minLeft = Number(start.mins == '' ? 0 : start.mins);
  //   compareLeft.add(start.time * minLeft, 'm');
  //   minRight = Number(end.mins == '' ? 0 : end.mins);
  //   compareRight.add(end.time * minRight, 'm');
  //   if(!compareLeft.isBefore(compareRight) || Math.abs(compareLeft.diff(compareRight, 'd')) > 1 || Math.abs(compareLeft.diff(compareRight, 'm')) >= (60 * 24) || compareLeft.format('HH:mm:ss') == compareRight.format('HH:mm:ss')){
  //     this.timeErrorType = (Math.abs(compareLeft.diff(compareRight, 'd')) > 1 ? 2 : 1);
  //     [start.key, end.key].map(k => {
  //       const errRefKey = `${k}-0`;
  //       this.errRefs[errRefKey] && this.errRefs[errRefKey].showError();
  //     });
  //     rs = false;
  //   }
  //   return rs;
  // }

  // @action
  // checkSignTime = () =>{
  //   let failed = false;
  //   const worktimes = this.toJS(this.worktimes);
  //   const len = worktimes.length;
  //   for(let i = 0; i < len; i++){
  //     let {start, end} = worktimes[i];
  //     failed = !this.compareTime({...start, time: -1}, {...end, time: 1});
  //     if(failed)
  //       break;
  //     if(len > 1){
  //       if(i == 0){
  //         end = worktimes[len - 1].end;
  //         failed = !this.compareTime({...start, time: -1}, {...end, time: 1});
  //         if(failed)
  //           break;
  //         if(i < len -1){
  //           start = worktimes[i].end;
  //           end = worktimes[i + 1].start;
  //           failed = !this.compareTime({...start, time: 1}, {...end, time: -1});
  //           if(failed)
  //             break;
  //         }
  //       }else if(i < len -1){
  //         start = worktimes[i].end;
  //         end = worktimes[i + 1].start;
  //         failed = !this.compareTime({...start, time: 1}, {...end, time: -1});
  //         if(failed)
  //           break;
  //       }
  //     }
  //   }
  //   return failed;
  // }

  compareTime = (t1, t2, keys) => {
    const ks = keys.map(k => k.split('-')[0]);
    const sameKey = ks[0] == ks[1];
    if(!t1.isBefore(t2) || Math.abs(t1.diff(t2, 'd')) > 1 || (!sameKey && Math.abs(t1.diff(t2, 'm')) >= (60 * 24)) || t1.format('HH:mm:ss') === t2.format('HH:mm:ss')){
      this.timeErrorType = (Math.abs(t1.diff(t2, 'd')) > 1 ? 2 : 1);
      keys.map(k => {
        console.debug && console.debug(t1.format('YYYY-MM-DD HH:mm:ss'), t2.format('YYYY-MM-DD HH:mm:ss'));
        this.errRefs[k] && this.errRefs[k].showError();
      });
      return true;
    }
  }

  /**
   * 比对当前班次信息
   * 1.当前班次上班开始打卡时间与当前班次上班结束打卡时间比对
   * 2.当前班次上班结束打卡时间与当前班次下班开始打卡时间比对
   * 3.当前班次下班开始打卡时间与当前班次下班结束打卡时间比对
   * 4.当前班次上班开始打卡时间与下班结束打卡时间比对
   */
  compareCurrentShift = worktime => {
    let rs = false;
    const {start, end} = worktime;
    const {times: st, mins: sm, mins_next: smn, across: sAcross, key: sk} = start;
    const {times: et, mins: emn, mins_next: em, across: eAcross, key: ek} = end;
    //上班时间
    let workStartTime = this.convertTimeToMoment(st).add((sAcross == 1 ? 1 : 0), 'd')
    //下班时间
    let workOffTime = this.convertTimeToMoment(et).add((eAcross == 1 ? 1 : 0), 'd')
    //上班开始打卡时间
    const workStartBeginTime = cloneDeep(workStartTime).add(-1 * Number(sm == '' ? 0 : sm), 'm');
    // console.debug(workStartBeginTime.format('YYYY-MM-DD HH:mm:ss'));
    //上班结束打卡时间
    const workStartEndTime = cloneDeep(workStartTime).add(Number(smn == '' ? 0 : smn), 'm');
    // console.debug(workStartEndTime.format('YYYY-MM-DD HH:mm:ss'));
    //下班开始打卡时间
    const workOffBeginTime = cloneDeep(workOffTime).add(-1 * Number(em == '' ? 0 : em), 'm');
    // console.debug(workOffBeginTime.format('YYYY-MM-DD HH:mm:ss'));
    //下班结束打卡时间
    const workOffEndTime = cloneDeep(workOffTime).add(Number(emn == '' ? 0 : emn), 'm');
    // console.debug(workOffEndTime.format('YYYY-MM-DD HH:mm:ss'));

    //1.当前班次上班开始打卡时间与当前班次上班结束打卡时间比对
    rs = rs || this.compareTime(workStartBeginTime, workStartEndTime, [`${sk}-0`, `${sk}-1`]);
    //2.当前班次上班结束打卡时间与当前班次下班开始打卡时间比对
    rs = rs || this.compareTime(workStartEndTime, workOffBeginTime, [`${sk}-1`, `${ek}-1`]);
    //3.当前班次下班开始打卡时间与当前班次下班结束打卡时间比对
    rs = rs || this.compareTime(workOffBeginTime, workOffEndTime, [`${ek}-1`, `${ek}-0`]);
    //4.当前班次上班开始打卡时间与下班结束打卡时间比对
    rs = rs || this.compareTime(workStartBeginTime, workOffEndTime, [`${sk}-0`, `${ek}-0`]);

    return rs;
  }

  /**
   * 比对当前班次与下一班次时间
   * 当前班次下班结束打卡时间与下一班次上班开始打卡时间比对
   */
  compareNextShift = (currentWorktime, nextWorktime) => {
    let rs = false;
    const {end} = currentWorktime;
    const {start} = nextWorktime;
    const {times: st, mins: sm, across: sAcross, key: sk} = end;
    const {times: et, mins: em, across: eAcross, key: ek} = start;
    //当前班次时间
    let current = this.convertTimeToMoment(st).add((sAcross == 1 ? 1 : 0), 'd')
    //下次班次时间
    let next = this.convertTimeToMoment(et).add((eAcross == 1 ? 1 : 0), 'd')
    //当前班次下班结束打卡时间
    const currentTime = cloneDeep(current).add(Number(sm == '' ? 0 : sm), 'm');
    // console.debug(currentTime.format('YYYY-MM-DD HH:mm:ss'));
    //下次班次上班开始打卡时间
    const nextTime = cloneDeep(next).add(-1 * Number(em == '' ? 0 : em), 'm');
    // console.debug(nextTime.format('YYYY-MM-DD HH:mm:ss'));

    //当前班次下班结束打卡时间与下一班次上班开始打卡时间比对
    rs = rs || this.compareTime(currentTime, nextTime, [`${sk}-0`, `${ek}-0`]);

    return rs;
  }

  /**
   * 比对第一个班次与最后一个班次时间
   * 第一个班次上班开始打卡时间与最后一个班次下班结束打卡时间的比对
   */
  compareShift = (firstWorktime, lastWorktime) => {
    let rs = false;
    const {start} = firstWorktime;
    const {end} = lastWorktime;
    const {times: st, mins: sm, across: sAcross, key: sk} = start;
    const {times: et, mins: em, across: eAcross, key: ek} = end;
    //第一个班次时间
    let first = this.convertTimeToMoment(st).add((sAcross == 1 ? 1 : 0), 'd')
    //最后一个班次时间
    let next = this.convertTimeToMoment(et).add((eAcross == 1 ? 1 : 0), 'd')
    //第一个班次上班开始打卡时间
    const firstTime = cloneDeep(first).add(-1 * Number(sm == '' ? 0 : sm), 'm');
    //最后一个班次下班结束打卡时间
    const lastTime = cloneDeep(next).add(Number(em == '' ? 0 : em), 'm');

    //第一个班次上班开始打卡时间与最后一个班次下班结束打卡时间的比对
    rs = rs || this.compareTime(firstTime, lastTime, [`${sk}-0`, `${ek}-0`]);

    return rs;
  }

  /**
   * 1.当前班次上班开始打卡时间与当前班次上班结束打卡时间比对
   * 2.当前班次上班结束打卡时间与当前班次下班开始打卡时间比对
   * 3.当前班次下班开始打卡时间与当前班次下班结束打卡时间比对
   * 4.当前班次下班结束打卡时间与下一班次上班开始打卡时间比对
   * 5.最后一个班次下班结束打卡时间与第一个班次上班开始打卡时间比对
   * 6.只有一个班次时还需要进行上班开始打卡时间与下班结束打卡时间的比对
   */
  @action
  checkSignTime = () =>{
    if(this.shift_24 != 0)
      return false;
    let failed = false;
    const worktimes = this.toJS(this.worktimes);
    const len = worktimes.length;
    if(len == 1){
      const worktime = worktimes[0];
      return this.compareCurrentShift(worktime);
    }
    for(let i = 0; i < len; i++){
      const worktime = worktimes[i];
      failed = this.compareCurrentShift(worktime);
      if(failed)
        break;
      if(i + 1 == len){
        const firstWorktime = worktimes[0];
        failed = this.compareShift(firstWorktime, worktime);
        if(failed)
          break;
      }else{
        const nextWorktime = worktimes[i + 1];
        failed = this.compareNextShift(worktime, nextWorktime);
        if(failed)
          break;
      }
    }
    return failed;
  }

  @action
  save = (setting = false) => {
    if (
      this.dialogParams.opType === "edit" &&
      this.editTabConfig.tabs.length > 0 &&
      this.editTabConfig.activeTabKey === "2"
    ) {
      this.saveRule();
      return;
    }
    if (this.spinning) return;
    this.spinning = true;
    const formParams = this.formTarget.baseForm.getFormParams();
    window.e9HideFormFieldKeys = [];
    const{shiftonoffworkcount, isresttimeopen, cardRemind,cardRemOfSignIn,cardRemOfSignOut, halfcalrule}=formParams;
    /*if (
      shiftonoffworkcount != null &&
      (shiftonoffworkcount != "1" ||
        (shiftonoffworkcount === "1" &&
          isresttimeopen &&
          isresttimeopen != "1"))
    ) {*/
    window.e9HideFormFieldKeys.push(...["restbeigin", "restend"]);
    //}
    if(halfcalrule == '0'){
      ['halfcalpoint','halfcalpoint2cross'].forEach(key=>{
        window.e9HideFormFieldKeys.push(key);
      })
    }
    if (!cardRemind || cardRemind === '0') {//关闭【打卡提醒】开关
      ['minsBeforeSignIn','minsAfterSignOut'].forEach(key=>{
        window.e9HideFormFieldKeys.push(key);
      })
    }
    if (cardRemind === '1') {
      if(cardRemOfSignIn === '0') {
        window.e9HideFormFieldKeys.push('minsBeforeSignIn');
      } 
      if (cardRemOfSignOut === '0') {
         window.e9HideFormFieldKeys.push('minsAfterSignOut');
      }
    }
    if(this.shift_24 == 1 && this.timeRange / 60 > 24){
      this.spinning = false;
      message.error(getLabel('518907','班次设置不能超过24小时'));
      return;
    }

    this.formTarget.baseForm.validateForm().then(f => {
      if (f.isValid) {
        let data = { ...formParams };
        if (this.opId != null) data.id = this.opId;
        if (this.selectedSubCompany && !data.subcompanyid)
          data.subcompanyid = this.selectedSubCompany.id;
        const worktimes = this.toJS(this.worktimes);
        worktimes.map((record, index) => {
          record.record = index;
          if(formParams.punchsettings != '1'){
            record.start.mins = 0;
            record.end.mins = 0;
          }
        });
        data.workSections = worktimes;
        data.worktime = this.worktime;
        if(this.worktimeError){
          message.error(i18n.label["388878"]());
          this.spinning = false;
          return;
        }
        if(formParams.punchsettings == '1' && this.checkSignTime()){
          this.spinning = false;
          return;
        }
        if(/*shiftonoffworkcount == "1" &&*/ isresttimeopen == '1'){
          if(this.resttimeRangeError){
            message.error(getLabel('523624','休息时间不能重叠'));
            this.spinning = false;
            return;
          }
          // if(this.resttimeError){
          //   message.error(i18n.label["390303"]());
          //   this.spinning = false;
          //   return;
          // }
  
          const arr = this.toJS(this.restTimeCollection);
          if(arr.length == 0){
            message.error(getLabel('523634','请设置休息时间'));
            this.spinning = false;
            return;
          }
  
          const rIndex = [];
          arr.map((d, i) => {
            const {start, end} = d;
            const {time: restbeigin = ''} = start || {};
            const {time: restend = ''} = end || {};
            const flag = (restbeigin == '' || restend == '');
            flag && rIndex.push(i);
            restbeigin == '' && this.errRefs[`restbeigin${i}`] && this.errRefs[`restbeigin${i}`].showError();
            restend == '' && this.errRefs[`restend${i}`] && this.errRefs[`restend${i}`].showError();
          })
          if(rIndex.length > 0){
            this.spinning = false;
            return;
          }
        }
        if(halfcalrule == '1'){
          const {halfcalpoint, halfcalpoint2cross} = data;
          const time = this.convertTimeToMoment(halfcalpoint).add(Number(halfcalpoint2cross), 'd');
          const start = worktimes[0].start;
          const end = worktimes[worktimes.length - 1].end;
          const startTime = this.convertTimeToMoment(start.times).add(Number(start.across), 'd');
          const endTime = this.convertTimeToMoment(end.times).add(Number(end.across), 'd');
          if(time.isBefore(startTime) || time.isAfter(endTime)){
            message.error(i18n.label['514034']());
            this.spinning = false;
            return;
          }
        }

        // data.restTimeSections = this.toJS(this.restTimeSections);
        data.restTimeSections = this.toJS(this.restTimeCollection).map((d, i) => {
          return {...d, orderId: i}
        });

        const params = { data: JSON.stringify(data) };
        api.saveShiftManagementBaseForm(params).then(
          data => {
            if (data.status === "1") {
              const cb = () => {
                message.success(i18n.message.saveSuccess());
                this.dialogParams.onCancel();
                this.getTableData(this.toJS(this.searchParams));
                if (setting) this.doEdit(data.id, "2");
              }

              //新建班次时，因为拿不到班次id，所以需要先保存班次，然后再保存提醒内容设置。
              if (this.dialogParams.opType === 'create') {
                this.opId = data.id;
                this.saveRemindContent().then(()=>{
                  cb();
                })
              }else{
                cb();
              }
            } else {
              message.error(data.message);
            }
            this.spinning = false;
          },
          error => (this.spinning = false)
        );
      } else {
        f.showErrors();
        const fields = this.formTarget.baseForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.baseForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
            this.errRefs[k] && this.errRefs[k].showError();
          }
        });
        this.showError = new Date().getTime();
        this.spinning = false;
      }
    });
  };

  @action
  getShiftInfo = (id, callback) => {
    api.getShiftInfo({ id }).then(rs => {
      let workSections, personalizedRuleDetails;
      rs.map((data, index) => {
        if (data.status === "1") {
          switch (index) {
            case 0:
              this.processCondition(data);
              this.canAdd = data.canAdd;
              this.shift_24 = data.shift_24 || 0;
              this.setFormData("baseForm", data.condition);
              workSections = data.workSections || [];
              this.restTimeCollection = data.restTimeSections
              break;
            case 1:
              data.condition[0].items.map(item => (item.colSpan = 2));
              personalizedRuleDetails = data.personalizedRuleDetails;
              this.setFormData("settingForm", data.condition);
              break;
          }
        }
      });
      if (
        this.formTarget.baseForm.isFormInit &&
        this.formTarget.settingForm.isFormInit
      )
        callback && callback(workSections, personalizedRuleDetails);
    });
  };

  @action
  setWorkSection = workSections => {
    let arr = [];
    if (workSections && workSections.length > 0) {
      workSections.map((d, i) => {
        arr.push({
          start: {
            ...d.start,
            key: `s${i}`
          },
          end: {
            ...d.end,
            key: `e${i}`
          }
        });
      });
    } else {
      arr.push({
        start: {
          ...this.worktimeConstruct,
          times: "09:00",
          key: 's0'
        },
        end: {
          ...this.worktimeConstruct,
          times: "18:00",
          key: 'e0'
        }
      });
    }
    this.worktimes = arr;
  };

  @action
  setLateRule = details => {
    if (details == null) return;
    const { earlyinearlyout, lateinlateout, lateoutlatein } = details;
    if (earlyinearlyout != null) {
      this.lateRules.earlyinearlyout = earlyinearlyout;
    } else {
      this.lateRules.earlyinearlyout = {
        advancetime: "30",
        postponetime: "30"
      };
    }
    if (lateinlateout != null) {
      this.lateRules.lateinlateout = lateinlateout;
    } else {
      this.lateRules.lateinlateout = {
        advancetime: "30",
        postponetime: "30"
      };
    }
    this.lateRules.lateoutlatein.length = 0;
    if (lateoutlatein && lateoutlatein.length > 0) {
      lateoutlatein.map(d => {
        this.lateRules.lateoutlatein.push({
          advancetime: d.advancetime,
          postponetime: d.postponetime
        });
      });
    }
  };

  @action
  doEdit = (id, tabKey) => {
    this.opId = id;

    this.getShiftInfo(id, (workSections, personalizedRuleDetails) => {
      this.setWorkSection(workSections);
      this.setLateRule(personalizedRuleDetails);
      this.calculateWorkTime();
      this.dialogParams.title = i18n.label["388539"]();
      this.dialogParams.opType = "edit";
      this.dialogParams.style = {
        width: 1000,
        height: 420
      };
      this.dialogParams.visible = true;
      this.setActiveTab(tabKey);
    });
  };

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

  @action
  ruleOp = (index, add = true) => {
    if (add) {
      this.lateRules.lateoutlatein.push({
        advancetime: "30",
        postponetime: "30"
      });
    } else {
      this.lateRules.lateoutlatein.splice(index, 1);
    }
  };

  @action
  saveRule = () => {
    if (this.spinning) return;
    this.spinning = true;
    const formParams = this.formTarget.settingForm.getFormParams();
    window.e9HideFormFieldKeys = [];
    const { fieldMap } = this.formTarget.settingForm;
    [...Object.keys(fieldMap)].map(key => {
      if (
        fieldMap[key].checkbox &&
        (fieldMap[key].checkboxValue || false) == false
      ) {
        window.e9HideFormFieldKeys.push(key);
      }
    });

    this.formTarget.settingForm.validateForm().then(f => {
      if (f.isValid) {
        let data = { ...formParams };
        if (this.opId != null) data.id = this.opId;
        if (this.selectedSubCompany)
          data.subcompanyid = this.selectedSubCompany.id;
        data.personalizedRuleDetails = this.toJS(this.lateRules);
        let flag = true;
        if (formParams.earlyinearlyout === "1") {//早到早走
          const {earlyinearlyout: {advancetime, postponetime}} = data.personalizedRuleDetails;
          if((advancetime || '') == ''){
            this.errRefs[`earlyinearlyout-advancetime`] && this.errRefs[`earlyinearlyout-advancetime`].showError();
            flag = false;
          }
          if(formParams.earlyinearlyoutsame === "0" && ((postponetime || '') == '')){
            this.errRefs[`earlyinearlyout-postponetime`] && this.errRefs[`earlyinearlyout-postponetime`].showError();
            flag = false
          }
        }
        if (formParams.lateinlateout === "1") {//晚到晚走
          const {lateinlateout: {advancetime, postponetime}} = data.personalizedRuleDetails;
          if((advancetime || '') == ''){
            this.errRefs[`lateinlateout-advancetime`] && this.errRefs[`lateinlateout-advancetime`].showError();
            flag = false;
          }
          if(formParams.lateinlateoutsame === "0" && ((postponetime || '') == '')){
            this.errRefs[`lateinlateout-postponetime`] && this.errRefs[`lateinlateout-postponetime`].showError();
            flag = false
          }
        }
        if (formParams.lateoutlatein === "1") {//晚走晚到
          const {lateoutlatein} = data.personalizedRuleDetails;
          lateoutlatein.map((d, i) => {
            const {advancetime, postponetime} = d;
            if((advancetime || '') == ''){
              this.errRefs[`lateoutlatein-${i}-advancetime`] && this.errRefs[`lateoutlatein-${i}-advancetime`].showError();
              flag = false;
            }
            if(formParams.lateinlateoutsame === "0" && ((postponetime || '') == '')){
              this.errRefs[`lateoutlatein-${i}-postponetime`] && this.errRefs[`lateoutlatein-${i}-postponetime`].showError();
              flag = false
            }
          })
        }
        if(!flag){
          this.spinning = false;
          return;
        }
        data.personalizedRuleDetails.lateoutlatein.map((record, index) => {
          record.record = index;
        });
        const { fieldMap } = this.formTarget.settingForm;
        [...Object.keys(fieldMap)].map(key => {
          if (fieldMap[key].checkbox) {
            data[`${key}enable`] =
              fieldMap[key].checkboxValue || false ? "1" : "0";
          }
        });
        const params = { data: JSON.stringify(data) };
        api.saveShiftManagementPersonalizedForm(params).then(
          data => {
            if (data.status === "1") {
              message.success(i18n.message.saveSuccess());
              console && console.debug(data);
              this.dialogParams.onCancel();
              this.getTableData(this.toJS(this.searchParams));
            } else {
              message.error(data.message);
            }
            this.spinning = false;
          },
          error => (this.spinning = false)
        );
      } else {
        f.showErrors();
        const fields = this.formTarget.baseForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.baseForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
        this.spinning = false;
      }
    });
  };

  @action
  doDelete = params => {
    let content;
    if (params == null) {
      params = {
        ids: this.table.selectedRowKeys
      };
      content = i18n.confirm.deleteSelected();
    } else {
      content = i18n.confirm.delete();
    }
    this.confirmInfo({
      content,
      onOk: () => {
        api.delShiftManagementForm(params).then(data => {
          if (data.status === "1") {
            message.success(i18n.message.deleteSuccess());
            this.table.getDatas(null, 1);
          }
        });
      }
    });
  };

  calculateTime = (time, range, plus = true) => {
    let t = this.convertTimeToMoment(time);
    t.add(Number(range) * (plus ? 1 : -1), "m");
    return t.format("HH:mm");
  };

  @action getDetachOperatelevel = v => {
    api.getDetachOperatelevel({subcompanyid: v.subcompanyid.value}).then(data => {
      if(data.status == 1){
        this.canAdd = !(data.operatelevel < 1);
      }else{
        message.error(data.message);
      }
    })
  }
  /********************* action list *********************/
@observable dialogStore1 = new DialogStore(this);

msgDialogButtons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1d5gna`} type="primary" onClick={this.dialogStore1.closeDialog}>关闭</Button>,];

msgMoreBtn = {datas: []};

handleMsgLabelClick = (type) => {
    const o = this.dialogStore1;
    const c = {
        title: (type == "earlyinearlyout") ? getLabel('521192','允许早到早走示例说明')  : (type == "lateinlateout") ? getLabel('521193','允许晚到晚走示例说明')  : getLabel('521194','允许晚走晚到示例说明') ,
        style: {
            width: 900,
            height: 650
        },
        dialogMark:"msg"
    };

    this.msgType = type;

    o.setDialogConfig(c)
    o.openDialog();
}

@computed get title1(){
  return getLabel('521195','精确时间计算示例说明') 
} ;

@computed get title2(){
  return getLabel('521196','相对时间计算示例说明') 
}

@computed get msg1(){
  return getLabel('521197','1.固定班制设置1天1次打卡，上班标准时段设置为9:00-18:00；') 
}

@computed get msgDatas() {
  return {
    earlyinearlyout:[{
      title:this.title1,
      msgs: [
        this.msg1,
        getLabel('521198','2.设置早到早走规则：上班早到30分钟，下班可以早走30分钟；即08:30之前打上班卡，允许17:30下班不算早退。如下图所示：') ,
        `<img src=${addContentPath('/hrm/hrm_e9/image/1.png')} />`
      ]
    },{
      title:this.title2,
      msgs: [
         this.msg1,
        getLabel('521199','2.早到早走规则-使用相对时间：在保证上班时长的前提下，早到可以早走，弹性限额30分钟；即每早到1分钟可早走1分钟，最多可早走30分钟。如下图所示：') ,
        `<img src=${addContentPath('/hrm/hrm_e9/image/2.png')} />`
      ]
    }],
    lateinlateout:[{
      title:this.title1,
      msgs: [
         this.msg1,
        getLabel('521200','2.晚到晚走规则：上班晚到30分钟及以内，下班需晚走30分钟以上；即在9:00-9:30之间打上班卡，需在18:30后下班才算正常出勤。如下图所示：'),
        `<img src=${addContentPath('/hrm/hrm_e9/image/3.png')} />`
      ]
    },{
      title:this.title2,
      msgs: [
        this.msg1,
        getLabel('521201','2.晚到晚走规则-使用相对时间：在保证上班时长的前提下，晚到可以晚走，弹性限额30分钟；即每晚到1分钟需晚走1分钟才不算迟到，弹性限额最多30分钟。如下图所示：'),
        `<img src=${addContentPath('/hrm/hrm_e9/image/4.png')} />`
      ]
    }],
    lateoutlatein:[{
      title:this.title1,
      msgs: [
         this.msg1,
        getLabel('521202','2.晚走晚到规则：前一天下班晚走30分钟及以上，第二天上班可以晚到30分钟；即第一天在18:30以后下班，第二天允许9:30上班不算迟到。如下图所示：'),
        `<img src=${addContentPath('/hrm/hrm_e9/image/5.png ')}/>`
      ]
    },{
      title:this.title2,
      msgs: [
        this.msg1,
        getLabel('521203','2.晚走晚到规则-使用相对时间：在保证上班时长的前提下，第一天晚走，第二天可以晚到，弹性限额30分钟；即第二天的晚到时间等于第一天的晚走时间，算正常出勤。如下图所示：'),
        `<img src=${addContentPath('/hrm/hrm_e9/image/6.png')} />`
      ]
    }]
  }
}
}

export const hrmShiftManager = new HrmShiftManager();
