import { observable, action, computed } from "mobx";
import { WeaTableNew, WeaSwitch } from "comsMobx";
import { WeaBrowser, WeaFormItem, WeaSelect, WeaUpload, WeaHelpfulTip, WeaLocaleProvider, WeaNewScroll, WeaError, WeaTools, WeaInputSearch } from "ecCom";
import { WeaLogView, WeaForm } from 'comsMobx';
import { Button, message, Table, Radio, Row, Col } from "antd";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import * as api from "../apis/groupSetting";
import { i18n } from "../public/i18n";
import { uniq, find, findIndex, has, fill, concat, dropRight, filter, isEmpty } from "lodash";
import classnames from "classnames";
import SerialTableList from '../components/groupSetting/info/SerialTableList';
import { addContentPath } from '../util/index.js'
const RadioGroup = Radio.Group;
const { WeaTable, TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

export class HrmGroupSetting extends HrmBaseStore {
  /********************* unobservable list *********************/
  single;
  moduleCallback;
  custLabelCol = 5;
  rightMenus = [];
  columns = [];
  opId;
  currGroupSerialidsDirty = [];
  locationSessionKey;
  wifiSessionKey;
  location = {};
  groupSelectedShift = [];
  orgTreeProps = {
    needSearch: true,
    isLoadAllSub: false,
    topPrefix: "hrmSearch",
    inputLeftDom: `<b>${i18n.label.organization()}</b>`,
    // needDropMenu: true,
    treeNodeClick: this.treeNodeClick,
    params: {
      rightStr: "HrmKQGroup:Add"
    }
  };
  @observable mainActiveTabKey = '1';
  @computed get mainTabConfig () {
    return {
      tabs: [
        {
          color: "#000000",
          groupId: "main",
          title: getLabel('390221', '考勤组'),
          viewCondition: "1",
          searchType: ["base", "advanced"],
          searchKey: "groupname",
          doSearch: () => this.getTableData()
        },
        {
          color: "#000000",
          groupId: "1212",
          title: getLabel('515128', '人员考勤组查询'),
          viewCondition: "2",
        }
      ],
      keyParam: "viewCondition",
      activeTabKey: this.mainActiveTabKey
    }
  };

  addBtnClasses = classnames({
    ["icon-coms-Add-to-hot"]: true,
    ["btn"]: true,
    ["btn-active"]: true
  });

  _itemRender = {
    groupname: (field, textAreaProps, form, formParams) => {
      return (
        <div className="cust">
          <div className="basic">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@hhwf18`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
            />
          </div>
        </div>
      );
    },
    excludeid: (field, textAreaProps, form, formParams) =>
      this.itemRender.groupname(field, textAreaProps, form, formParams),
    subcompanyid: (field, textAreaProps, form, formParams) =>
      this.itemRender.groupname(field, textAreaProps, form, formParams),
    kqtype: (field, textAreaProps, form, formParams) => {
      const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      };
      const getHelpful = (key) => {
        switch (key) {
          case '1':
            return getLabel('500476', '按周设置固定上班时间，适用于：早九晚五固定上班时间的公司使用');
          case '2':
            return getLabel('500477', '按日期设置上班时间，适用于：每天工作时间不固定的公司使用');
          case '3':
            return getLabel('500478', '不设置上班时间，随时打卡考勤,适用于：班次没有规律只计算工作时段的公司使用');
        }
      }
      return (
        <div className="cust">
          <div className="basic">
            <RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@lsqvqm`} disabled={field.viewAttr === 1} onChange={e => form.updateFields({ kqtype: { value: e.target.value } })} value={formParams.kqtype}>
              {
                field.options.map((option, index) => {
                  return (
                    <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@b10cnh@${index}`} style={radioStyle} key={option.key} value={option.key}>
                      {option.showname}
                      <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@q9tz1c@${index}`} title={getHelpful(option.key)} />
                    </Radio>
                  )
                })
              }
            </RadioGroup>
          </div>
        </div>
      );
    },
    overtime_type: (field, textAreaProps, form, formParams) => {
      const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      };
      if (formParams.kqtype === "3")return null;
      return (
        <div className="cust">
          <div className="basic">
            <RadioGroup ecId={`${this && this.props && this.props.ecId || ''}_RadioGroup@lsqvqm`} disabled={field.viewAttr === 1} onChange={e => form.updateFields({ overtime_type: { value: e.target.value } })} value={formParams.overtime_type}>
              {
                field.options.map((option, index) => {
                  return (
                    <Radio ecId={`${this && this.props && this.props.ecId || ''}_Radio@b10cnh@${index}`} style={radioStyle} key={option.key} value={option.key}>
                      <span className="overtime_type">
                        {option.showname}
                        {
                          formParams.overtime_type == '0' && option.key == '0' &&
                            <WeaSwitch 
                              fieldConfig={{
                                ...form.fieldMap["overtime_rule_id"],
                                ...textAreaProps
                              }}
                              form={form}
                              formParams={formParams}
                              onChange={
                                (v) => {
                                  form.updateFields(v)
                                }
                              }
                            />
                        }
                        { (option.key == '1' && field.helpfulTip )&& <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@q9tz1c@${index}`} title={ field.helpfulTip } /> }
                      </span>
                    </Radio>
                  )
                })
              }
            </RadioGroup>
          </div>
        </div>
      );
    },
    overtime_rule_id: () => null,
    calmethod: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "3")
        return (
          <div className="cust">
            <div className="basic" style={{ width: '100%' }}>
              <div className='serialidsBrowser' style={{ width: '100%' }}>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fe554m`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
                <div style={{ width: 'auto', float: 'left', marginTop: '6px' }} onClick={this.calmethodHandle}><a>{getLabel('529753', '计算方式说明')}</a></div>
              </div>
            </div>
          </div>
        );
      return null;
    },
    desc: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "3") {
        return (
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@amkprq`}
            fieldConfig={{ ...field, ...textAreaProps }}
            form={form}
            formParams={formParams}
          />
        )
      }
      return null;
    },
    serialids: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "2") {
        return (
          <div className="cust">
            <div className="basic">
              <div className='serialidsBrowser'>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fe554m`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                  onChange={(v) => {
                    this.compareSearial(v, form);
                  }}
                />
              </div>
            </div>
          </div>
        )
      }
      return null;
    },
    self_shift: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "2")
        return (
          <div className="cust">
            <div className="basic">
              <WeaSwitch
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
        );
      return null;
    },
    shiftcycleday: (field, textAreaProps, form, formParams) => {
      let info = i18n.label['389226']();
      info = info.replace("{params}", formParams.shiftcycleday);
      return (
        <div className="cust">
          <div className="child" style={{ marginRight: 0 }}>
            <div className="inputNumber">
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@a32mzn`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
            {
              formParams.shiftcycleday && <div className="lbl text-elli" style={{ maxWidth: 265 }} title={info}>{info}</div>
            }
          </div>
        </div>
      );
    },
    weekday: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "3")
        return (
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@e9uccz`}
            fieldConfig={{ ...field, ...textAreaProps }}
            form={form}
            formParams={formParams}
          />
        );
      return null;
    },
    signstart: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "3")
        return (
          <div className="cust">
            <div className="child">
              <div className="lbl1">{i18n.label["389105"]()}</div>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2wzc3h`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
        );
      return null;
    },
    workhour: (field, textAreaProps, form, formParams) => {
      if (formParams.kqtype === "3")
        return (
          <div className="cust">
            <div className="basicSetting">
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2aekxh`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
        );
      return null;
    },
    validityfromdate: (field, textAreaProps, form, formParams) => {
      if (formParams.validity === "1")
        return (
          <div className="cust">
            <div className="basic">
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@nxgtkf`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
        );
      return null;
    },
    validityenddate: (field, textAreaProps, form, formParams) => {
      if (formParams.validity === "1")
        return (
          <div className="cust">
            <div className="basic">
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@h3358r`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
        );
      return null;
    },
    signintype: (field, textAreaProps, form, formParams) => {
      return (
        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2yywwz`}
          fieldConfig={{ ...field, ...textAreaProps }}
          form={form}
          formParams={formParams}
          onChange={() => this.refreshAttendanceForm = new Date().getTime()}
        />
      )
    },
    ipscope_v4_pc: (field, textAreaProps, form, formParams) => {
      const signintype = ~~formParams.signintype;
      if (signintype > 3)
        return null;
      const { fieldMap } = form;
      return (
        <div className="cust">
          {
            (signintype == 1 || signintype == 2) &&
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ax9ovn`} gutter={16} className="ip_range">
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@dktdk5`} span='3'><div className="ipscope">{getLabel('522577', 'pc端')}</div></Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@mkit74`} span='12'>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ru4rul`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </Col>
            </Row>
          }
          {
            (signintype == 1 || signintype == 3) &&
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rx5ddr`} gutter={16} className="ip_range">
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gikq77`} span='3'><div className="ipscope">{getLabel('522578', '移动端')}</div></Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@xr0b9k`} span='12'>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bl0xy3`}
                  fieldConfig={{ ...fieldMap['ipscope_v4_em'], ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </Col>
            </Row>
          }
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@xzgo1a`} gutter={16} className="ip_range">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@gv8gkt`} span='21' offset='3'>
              <div className="ipscope">{i18n.label["389116"]()}</div>
            </Col>
          </Row>
        </div>
      );
    },
    ipscope_v4_em: (field, textAreaProps, form, formParams) => null,
    ipscope_v6_pc: (field, textAreaProps, form, formParams) => {
      const signintype = ~~formParams.signintype;
      if (signintype > 3)
        return null;
      const { fieldMap } = form;
      return (
        <div className="cust">
          {
            (signintype == 1 || signintype == 2) &&
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8awno2`} gutter={16} className="ip_range">
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ofspsu`} span='3'><div className="ipscope">{getLabel('522577', 'pc端')}</div></Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@hche7k`} span='12'>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@slmqny`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </Col>
            </Row>
          }
          {
            (signintype == 1 || signintype == 3) &&
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7tt71b`} gutter={16} className="ip_range">
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@c7mn5f`} span='3'><div className="ipscope">{getLabel('522578', '移动端')}</div></Col>
              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@neifvn`} span='12'>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vyhlx2`}
                  fieldConfig={{ ...fieldMap['ipscope_v6_em'], ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </Col>
            </Row>
          }
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@vq2p4r`} gutter={16} className="ip_range">
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@fp23na`} span='21' offset='3'>
              <div className="ipscope">{i18n.label["503729"]()}</div>
            </Col>
          </Row>
        </div>
      );
    },
    ipscope_v6_em: (field, textAreaProps, form, formParams) => null,
    locationcheck: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      return (
        <div className="cust">
          <div className="child">
            <div>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@sw5f2j`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
          {
            formParams.locationcheck == '1' &&
            <div className='child child-checkbox'>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@o81ias`}
                fieldConfig={{
                  ...fieldMap["locationfacecheck"],
                  ...textAreaProps,
                  content: fieldMap["locationfacecheck"].label
                }}
                form={form}
                formParams={formParams}
              />
            </div>
          }
          {
            formParams.locationcheck == '1' && formParams.locationfacecheck == '1' &&
            <div className='child child-checkbox'>
              <WeaSwitch 
                fieldConfig={{
                  ...fieldMap["locationfacechecktype"],
                  ...textAreaProps
                }}
                form={form}
                formParams={formParams}
                onChange={
                  (v) => {
                    form.updateFields({ wififacechecktype: { value: v.locationfacechecktype.value } })
                  }
                }
              />
            </div>
          }
        </div>
      );
    },
    locationfacecheck: (field, textAreaProps, form, formParams) => null,
    locationfacechecktype: (field, textAreaProps, form, formParams) => null,
    locationshowaddress: (field, textAreaProps, form, formParams) => {
      if (formParams.locationcheck == '1') {
        return (
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tehbck`}
            fieldConfig={{
              ...field,
            }}
            form={form}
            formParams={formParams}
          />
        );
      } else {
        return null;
      }
    },
    wificheck: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      return (
        <div className="cust">
          <div className="child">
            <div>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@bjsq0q`}
                fieldConfig={{ ...field, ...textAreaProps }}
                form={form}
                formParams={formParams}
              />
            </div>
          </div>
          {
            formParams.wificheck == '1' &&
            <div className='child child-checkbox'>
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@yt8mdx`}
                fieldConfig={{
                  ...fieldMap["wififacecheck"],
                  ...textAreaProps,
                  content: fieldMap["wififacecheck"].label
                }}
                form={form}
                formParams={formParams}
              />
            </div>
          }
          {
            formParams.wificheck == '1' && formParams.wififacecheck == '1' &&
            <div className='child child-checkbox'>
              <WeaSwitch 
                fieldConfig={{
                  ...fieldMap["wififacechecktype"],
                  ...textAreaProps
                }}
                form={form}
                formParams={formParams}
                onChange={
                  (v) => {
                    form.updateFields({ locationfacechecktype: { value: v.wififacechecktype.value } })
                  }
                }
              />
            </div>
          }
        </div>
      );
    },
    wififacecheck: (field, textAreaProps, form, formParams) => null,
    wififacechecktype: (field, textAreaProps, form, formParams) => null,
    wifiname: (field, textAreaProps, form, formParams) => {
      return (
        <div className="cust">
          <div style={{ width: '80%' }}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rvy6kv`}
              fieldConfig={{
                ...field,
                ...textAreaProps
              }}
              form={form}
              formParams={formParams}
            />
          </div>
        </div>
      );
    },
    mac: (field, textAreaProps, form, formParams) => {
      return (
        <div className="cust">
          <div style={{ width: '80%' }}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0ltojk`}
              fieldConfig={{
                ...field,
                ...textAreaProps
              }}
              form={form}
              formParams={formParams}
            />
          </div>
        </div>
      );
    },
    auto_checkin: (field, textAreaProps, form, formParams) => {
      const { signintype, locationcheck, wificheck } = formParams;
      if ([1, 3].indexOf(parseInt(signintype)) > -1 && (locationcheck == '1' || wificheck == '1')) {
        return (
          <div className="cust">
            <div className="child">
              <div>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@aj7s7u`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </div>
            </div>
          </div>
        )
      }
      return null;
    },
    auto_checkin_before: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      const { signintype, locationcheck, wificheck, auto_checkin } = formParams;
      if ([1, 3].indexOf(parseInt(signintype)) > -1 && (locationcheck == '1' || wificheck == '1') && auto_checkin == '1') {
        return (
          <div className="cust">
            <div className="child" style={{ marginRight: '5px' }}>
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@lsrnxo`}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@pyj47s`} style={{ paddingRight: '5px' }}>{getLabel('519431', '上班前')}</Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@uja5g4`} style={{ width: 60, paddingRight: '5px' }}>
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@onot4e`}
                    fieldConfig={{ ...field, ...textAreaProps }}
                    form={form}
                    formParams={formParams}
                  />
                </Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@25uxpc`}>{getLabel('519434', '分钟开始')},{getLabel('519432', '上班后')}</Col>
              </Row>
            </div>
            {
              auto_checkin == '1' &&
              <div className='child'>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@iyk1cc`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@d56rmz`} style={{ width: 60, paddingRight: '5px' }}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@j538iz`}
                      fieldConfig={{
                        ...fieldMap["auto_checkin_after"],
                        ...textAreaProps,
                      }}
                      form={form}
                      formParams={formParams}
                    />
                  </Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4u0mcx`}>{getLabel('519435', '分钟结束')}</Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@249elo`} style={{ paddingLeft: '5px' }}>
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@eo920i`} title={this.helpTipMap && this.helpTipMap.auto_checkin_before || ''} />
                  </Col>
                </Row>
              </div>
            }
          </div>
        )
      }
      return null;
    },
    auto_checkin_after: (field, textAreaProps, form, formParams) => null,
    auto_checkout: (field, textAreaProps, form, formParams) => {
      const { signintype, locationcheck, wificheck } = formParams;
      if ([1, 3].indexOf(parseInt(signintype)) > -1 && (locationcheck == '1' || wificheck == '1')) {
        return (
          <div className="cust">
            <div className="child">
              <div>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@hicy1a`}
                  fieldConfig={{ ...field, ...textAreaProps }}
                  form={form}
                  formParams={formParams}
                />
              </div>
            </div>
          </div>
        )
      }
      return null;
    },
    auto_checkout_before: (field, textAreaProps, form, formParams) => {
      const { fieldMap } = form;
      const { signintype, locationcheck, wificheck, auto_checkout } = formParams;
      if ([1, 3].indexOf(parseInt(signintype)) > -1 && (locationcheck == '1' || wificheck == '1') && auto_checkout == '1') {
        return (
          <div className="cust">
            <div className="child" style={{ marginRight: '5px' }}>
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ktelq7`}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@bsum5u`} style={{ paddingRight: '5px' }}>{getLabel('519433', '下班后')}</Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@z63sr1`} style={{ width: 60, paddingRight: '5px' }}>
                  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@55z7k5`}
                    fieldConfig={{ ...field, ...textAreaProps }}
                    form={form}
                    formParams={formParams}
                  />
                </Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ap2ml4`}>{getLabel('519434', '分钟开始')},{getLabel('519433', '下班后')}</Col>
              </Row>
            </div>
            {
              auto_checkout == '1' &&
              <div className='child'>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@oscgxr`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@tmz7va`} style={{ width: 60, paddingRight: '5px' }}>
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@fl18ot`}
                      fieldConfig={{
                        ...fieldMap["auto_checkout_after"],
                        ...textAreaProps,
                      }}
                      form={form}
                      formParams={formParams}
                    />
                  </Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3vl1rk`}>{getLabel('519435', '分钟结束')}</Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@g9um5q`} style={{ paddingLeft: '5px' }}>
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@e2k122`} title={this.helpTipMap && this.helpTipMap.auto_checkout_before || ''} />
                  </Col>
                </Row>
              </div>
            }
          </div>
        )
      }
      return null;
    },
    auto_checkout_after: (field, textAreaProps, form, formParams) => null
  };
  @observable illustrateVisible = false
  calmethodHandle = () => {
    this.illustrateVisible = true;
  }
  calmethodcancel = () => {
    this.illustrateVisible = false;
  }

  _childrenComponents = () => ({
    kqtype: () => {
      const formParams = this.formTarget.baseForm.getFormParams();
      if (formParams.kqtype != "1") {
        return [];
      }

      const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedWorkdayKeys = selectedRowKeys;
          let datas = this.toJS(this.workdaySettingData);
          datas.map((d, i) => {
            if (selectedRowKeys.indexOf(i) < 0) {
              d.serialid = '-1';
              d.serialinfo = getLabel('26593', '休息');
            }
          })
          this.workdaySettingData = datas;
        },
        clear: () => {
          this.selectedWorkdayKeys = [];
        }
      };
      return [
        {
          com: (
            <div className="workdaySetting">
              <div className="workdaySetting-header">
                <div className="title">{i18n.label["389090"]()}</div>
                <div className="multiSetting">
                  {this.selectedWorkdayKeys.length > 0 && this.canAdd ? (
                    <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@q3prjm`}
                      icon="icon-coms-hrm"
                      iconBgcolor="#217346"
                      title={i18n.label["389091"]()}
                      type={"kqshift"}
                      customized
                      inputStyle={{ width: 200 }}
                      onChange={(ids, names, datas) => this.multiSetting(datas)}
                      quickSearchName='serial'
                    >
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m2fnp6`} type="default">{i18n.label["33511"]()}</Button>
                    </WeaBrowser>
                  ) : (
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tkssua`} type="default" disabled>
                        {i18n.label["33511"]()}
                      </Button>
                    )}
                </div>
              </div>
              <div className="table">
                <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@7o58qr`}
                  pagination={false}
                  columns={this.columns}
                  dataSource={this.toJS(this.workdaySettingData)}
                  rowSelection={{
                    ...rowSelection,
                    selectedRowKeys: this.selectedWorkdayKeys
                  }}
                />
              </div>
            </div>
          ),
          col: 1
        }
      ];
    },
    serialids: () => {
      const formParams = this.formTarget.baseForm.getFormParams();
      if (formParams.kqtype != "2") {
        return [];
      }

      let coms = [
        {
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@52twed`}
              label={i18n.label["389103"]()}
              labelCol={{ span: this.custLabelCol }}
              wrapperCol={{ span: 24 - this.custLabelCol }}
            >
              <div className='cust'>
                <div className='opBtns'>
                  {this.canAdd && <i className={this.addBtnClasses} onClick={() => this.getShiftCycleForm()} title={i18n.label.add()} />}
                </div>
              </div>
            </WeaFormItem>
          ),
          col: 1
        },
        {
          com: this.generateSerialTable(),
          col: 1
        }
      ]

      return coms;
    },
    shiftcycleday: () => {
      const options = this.toJS(this.groupShiftOptions);
      const formParams = this.formTarget.shiftSchedulceForm.getFormParams();
      const shiftcycleday = Number(formParams.shiftcycleday) || 0;
      if (this.currGroupSerialidsDirty.length === 0) {
        this.currGroupSerialidsDirty = fill(Array(shiftcycleday), this.groupShiftOptions[0].key);
      } else if (this.currGroupSerialidsDirty.length < shiftcycleday) {
        this.currGroupSerialidsDirty = concat(this.currGroupSerialidsDirty, fill(Array(shiftcycleday - this.currGroupSerialidsDirty.length), this.groupShiftOptions[0].key));
      } else {
        this.currGroupSerialidsDirty = dropRight(this.currGroupSerialidsDirty, this.currGroupSerialidsDirty.length - shiftcycleday);
      }
      for (let i = 0; i < this.currGroupSerialidsDirty[i]; i++) {
        if (this.currGroupSerialidsDirty[i] != '' && findIndex(options, { key: this.currGroupSerialidsDirty[i] }) < 0) {
          this.currGroupSerialidsDirty[i] = '';
        }
      }

      if (formParams.shiftcycleday != "" && formParams.shiftcycleday > 0) {
        let coms = [];
        for (let i = 0; i < Number(formParams.shiftcycleday); i++) {
          let lbl = i18n.label['389229']();
          lbl = lbl.replace("{params}", i + 1);
          coms.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@qyghvq@${i}`}
                label={lbl}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              >
                <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@4j74wb@${i}`}
                  options={options}
                  value={this.currGroupSerialidsDirty[i]}
                  onChange={v => {
                    this.currGroupSerialidsDirty[i] = v;
                  }
                  }
                />
              </WeaFormItem>
            ),
            col: 1
          })
        }
        return coms;
      } else {
        return [];
      }
    },
    // ipscope_v6_pc: () => {
    //   return [
    //     {
    //       com: (
    //         <div className="kqType">
    //           <div className="title">{i18n.label["388735"]()}</div>
    //           <div className="buttonBar">
    //             {/* <Button type="default">{i18n.label["389066"]()}</Button> */}
    //             <div className='upload'>
    //               <WeaUpload
    //                   uploadUrl='/api/doc/upload/uploadFile'
    //                   category='string'
    //                   limitType='xls,xlsx'
    //                   maxFilesNumber={1}
    //                   onChange = {
    //                       (ids, list) => {
    //                         this.importConfig(ids[0]);
    //                       }
    //                   } >
    //                   <Button type="default">{i18n.label["389066"]()}</Button>
    //               </WeaUpload>
    //             </div>
    //             <Button type="default" onClick={() => this.exportConfig()}>{i18n.label["389065"]()}</Button>
    //           </div>
    //         </div>
    //       ),
    //       col: 1
    //     }
    //   ];
    // },
    locationshowaddress: (type = "location") => {
      return [
        {
          com: this.generateTable(type),
          col: 1
        }
      ];
    },
    wificheck: () => this.childrenComponents().locationshowaddress("wifi")
  });

  @computed get itemRender () {
    this.refreshAttendanceForm;
    this.refreshTab;
    const form = this.formTarget.kqTypeForm;
    if (form == null)
      return this._itemRender;

    const formParams = form.getFormParams();
    const { signintype } = formParams;
    if (this.editTabsActiveKey == '1' || signintype < 4)
      return this._itemRender;
    else {
      const itemRender = {};
      Object.keys(formParams).map(key => Object.assign(itemRender, {
        [key]: (field, textAreaProps, form, formParams) => null
      }));
      Object.assign(itemRender, {
        signintype: (field, textAreaProps, form, formParams) => {
          return (
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@rwlqbt`}
              fieldConfig={{ ...field, ...textAreaProps }}
              form={form}
              formParams={formParams}
              onChange={() => this.refreshAttendanceForm = new Date().getTime()}
            />
          )
        }
      });
      return itemRender
    }
  }

  @computed get childrenComponents () {
    this.refreshAttendanceForm;
    const form = this.formTarget.kqTypeForm;
    if (form == null)
      return this._childrenComponents;

    const formParams = form.getFormParams();
    const { signintype } = formParams;
    if (this.editTabsActiveKey == '1' || signintype < 4) {
      let childKey = 'ipscope_v4_pc';
      if (has(formParams, 'ipscope_v6_pc'))
        childKey = 'ipscope_v6_pc';

      return () => ({
        ...this._childrenComponents(),
        [childKey]: () => {
          return [
            {
              com: (
                <div className="kqType">
                  <div className="title">{i18n.label["388735"]()}</div>
                  <div className="buttonBar">
                    <div className='upload'>
                      <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@aoe9th`}
                        uploadUrl='/api/doc/upload/uploadFile'
                        category='string'
                        limitType='xls,xlsx'
                        maxFilesNumber={1}
                        onChange={
                          (ids, list) => {
                            this.importConfig(ids[0]);
                          }
                        } >
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5pdsxz`} type="default" disabled={!this.canAdd}>{i18n.label["389066"]()}</Button>
                      </WeaUpload>
                    </div>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6q6cut`} type="default" onClick={() => this.exportConfig()}>{i18n.label["389065"]()}</Button>
                  </div>
                </div>
              ),
              col: 1
            }
          ];
        },
      })
    } else {
      return () => { };
    }
  }

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

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

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

  /********************* observable list *********************/
  @observable canAdd = false;
  @observable canCreate = false;
  @observable canDel = false;
  @observable canDelMember = false;

  @observable
  spinning = false;
  @observable
  selectedSubCompany;
  @observable
  table = new TableStore();
  @observable
  locationTable = new TableStore();
  @observable
  wifiTable = new TableStore();
  @observable
  memberTable = new TableStore();
  @observable
  selectedWorkdayKeys = [];
  @observable
  workdaySettingData = [];
  @observable
  groupShiftOptions = [];
  // @observable
  // currGroupSerialids = [];
  @observable _serialTableProps = {}
  @observable refreshTab = new Date().getTime();
  @observable bChange = new Date().getTime();

  // @observable rangeParams = { locationname: '', range: 500, longitude: '', latitude: '' };
  @computed get serialTableProps () {
    return this.toJS(this._serialTableProps);
  }

  @observable _rangeParams = {};
  @computed get rangeParams(){return this.toJS(this._rangeParams)}
  set rangeParams(v){this._rangeParams = v}

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

  @observable
  serialDialogParams = {
    ...this.dialogPropsDef,
    style: {
      width: 700,
      height: 500
    },
    onCancel: () => {
      this.serialDialogParams.visible = false;
    },
    onClose: formParams => {
      // this.currGroupSerialids = [...this.currGroupSerialidsDirty];
      const { record, isCreate } = this.toJS(this.serialDialogParams);
      this.serialDialogParams.visible = false;
      const d = { ...formParams, serial: this.currGroupSerialidsDirty.join(",") };
      let { columns, datas } = this.serialTableProps;
      if (isCreate)
        datas.push({ ...d, key: new Date().getTime() });
      else {
        datas = datas.map(data => {
          if ((data.id && data.id == record.id) || (data.key && data.key == record.key)) {
            return {
              ...data,
              ...d
            }
          } else {
            return data;
          }
        })
      }
      this._serialTableProps = { columns, datas };
    }
  };

  @observable
  locationDialogParams = {
    ...this.dialogPropsDef,
    style: {
      width: 900,
      height: 500
    },
    onCancel: () => {
      this.location = null;
      this.locationDialogParams.visible = false;
    }
  };

  //是否是新增考勤组成员
  @observable isNewMemberToAttendanceGroup = true;

  @observable
  wifiDialogParams = {
    ...this.dialogPropsDef,
    style: {
      width: 500,
      height: 135
    },
    onCancel: () => {
      this.wifiDialogParams.visible = false;
    }
  };

  @observable
  memberAuthParams = {
    icon: "icon-coms-hrm",
    iconBgcolor: "#217346",
    title: i18n.label["125217"](),
    visible: false,
    onOk: data =>{
     if(!this.isDateInValidRange(data))return;
      this.doSaveMember({
        ...data,
        groupId: this.opId
      })
    },
    onOkClose: false,
    onCancel: () => (this.memberAuthParams.visible = false)
  };

  @observable batchSetDateType = 'effective';

  @observable
  validityDialogParams = {
    icon: "icon-coms-hrm",
    iconBgcolor: "#217346",
    visible: false,
    onOk: data =>{
    },
    onOkClose: false,
    onCancel: () => {this.validityDialogParams.visible = false;this.validateDate = ''}
  };

  isDateInValidRange = (data) => {
    const { validateFromDate, validateToDate } = data;
    if (validateFromDate && validateToDate && (validateToDate < validateFromDate)) {
      message.warning(i18n.label[546176]());
      return;
    }
    return true;
  }

  @observable _editTabs = [];
  @observable editTabsActiveKey = '1';
  @observable refreshAttendanceForm = new Date().getTime();
  /********************* observable list *********************/

  /********************* computed list *********************/
  @computed
  get tableMultiDelete () {
    return this.table.selectedRowKeys.length === 0;
  }
  @computed
  get locationTableMultiDelete () {
    return this.locationTable.selectedRowKeys.length === 0;
  }
  @computed
  get wifiTableMultiDelete () {
    return this.wifiTable.selectedRowKeys.length === 0;
  }
  @computed
  get memberRemoveable () {
    return this.memberTable.selectedRowKeys.length === 0;
  }

  @computed get editTabs () {
    return this.toJS(this._editTabs);
  }

  @computed get editTabConfig () {
    let tabs = this.editTabs;
    const tabButtonDef = [];
    this.canAdd && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms-Add-to-hot",
      label: i18n.label.create,
      rightMenuIcon: this.menuIconCollection.create,
      onClickHandle: () =>{
        this.getMemberForm()
        this.isNewMemberToAttendanceGroup = true;
      } 
    });
    this.canAdd && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms-Planning-tasks",
      label: i18n.label[546729](),
      rightMenuIcon: this.menuIconCollection.remove,
      onClickHandle: () => {
        this.batchSetDateType = 'effective';
        this.batchSetEffectiveDates();
      },
      checkAction: "memberRemoveable"
    });
    this.canAdd && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms02-Warning-01",
      label: i18n.label[546730](),
      rightMenuIcon: this.menuIconCollection.remove,
      onClickHandle: () => {
        this.batchSetDateType = 'expiration';
        this.batchSetExpirationDates();
      },
      checkAction: "memberRemoveable"
    });
    this.canAdd && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms-form-delete-hot",
      label: i18n.label.multiDelete,
      rightMenuIcon: this.menuIconCollection.remove,
      onClickHandle: () => this.deleteMember(),
      checkAction: "memberRemoveable"
    });
    if (tabs.length > 2) {
      tabs[2].tabButtonDef = tabButtonDef;
    }

    return {
      tabs,
      keyParam: "viewCondition",
      activeTabKey: this.editTabsActiveKey,
      tabChangeHandle: key => this.setActiveTab(key)
    }
  };

  @action
  batchSetEffectiveDates = () => {
    this.validityDialogParams.visible = true;
  }

  @action
  batchSetExpirationDates = () => {
    this.validityDialogParams.visible = true;
  }

  validateDate = '';

  saveValidateDate  = () => {
    this.spinning = true;
    const params = {
      groupId:this.opId,
      validateId:this.memberTable.selectedRowKeys,
      updatevalidate:(this.batchSetDateType === 'effective') ? '0' : '1',
      validateDate:this.validateDate
    };
    api.saveValidateDate(params).then(resp => {
      this.spinning = false;
      if (resp.status == '1') {
        message.success(i18n.message.saveSuccess());
        this.validityDialogParams.visible = false;
        this.memberTable.getDatas(null, 1);
        this.getTableData();
        this.validateDate = '';
      }else{
        message.error(resp.message);
      }
    })
  }
  /********************* computed list *********************/

  /********************* action list *********************/
  getOsInfo = async () => {
    let data = await WeaTools.callApi('/api/system/info/getOSinfo', 'GET', {});
    if (data.status) {
      data.mapParams.ableToSwitchMap = "true";
      localStorage.setItem('getOsInfo', JSON.stringify(data));
    }
  }

  @action
  init = () => {
    // this.getOsInfo();
    this.selectedSubCompany = null;
    this.single = null;
    this.mainActiveTabKey = '1';
    api.init().then(
      rs => {
        rs.map((data, index) => {
          if (data.status === "1") {
            switch (index) {
              case 0:
                this.containerInitFinished.init = false;
                this.setFormData("conditionForm", data.conditions);
                if (this.formTarget.conditionForm.isFormInit)
                  this.containerInitFinished.init = true;
                break;
              case 1:
                let tabs = [];
                data.tabs.map((tab, index) => {
                  let tabInfo = {
                    color: "#000000",
                    groupId: `g{tab.key}`,
                    title: tab.title,
                    viewCondition: tab.key
                  };
                  if (index === 2) {
                    tabInfo.searchType = ['base', 'advanced'];
                    tabInfo.doSearch = () => this.getMemberList();
                    tabInfo.searchKey = 'hrmName';
                    // tabInfo.tabButtonDef = this.memberTabButtonDef;
                  }
                  tabs.push(tabInfo);
                });
                this._editTabs = tabs;
                break;
            }
          }
        });
        this.getTableData();
      },
      error => { }
    );
  };

  @computed get memberTabButtonDef () {
    const tabButtonDef = [];
    this.canAdd && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms-Add-to-hot",
      label: i18n.label.create,
      rightMenuIcon: this.menuIconCollection.create,
      onClickHandle: () => this.getMemberForm()
    });
    this.canDelMember && tabButtonDef.push({
      comType: "button",
      icon: "icon-coms-form-delete-hot",
      label: i18n.label.multiDelete,
      rightMenuIcon: this.menuIconCollection.remove,
      onClickHandle: () => this.deleteMember(),
      checkAction: "memberRemoveable"
    });
    return tabButtonDef;
  }

  @action
  initSingle = (id, callback) => {
    if (id == null)
      return;
    this.single = true;
    this.moduleCallback = callback;
    api.getTabs().then(data => {
      if (data.status === "1") {
        let tabs = [];
        data.tabs.map((tab, index) => {
          let tabInfo = {
            color: "#000000",
            groupId: `g{tab.key}`,
            title: tab.title,
            viewCondition: tab.key
          };
          if (index === 2) {
            tabInfo.searchType = ['base', 'advanced'];
            tabInfo.doSearch = () => this.getMemberList();
            tabInfo.searchKey = 'hrmName';
            tabInfo.tabButtonDef = [
              {
                comType: "button",
                icon: "icon-coms-Add-to-hot",
                label: i18n.label.create,
                rightMenuIcon: this.menuIconCollection.create,
                onClickHandle: () => this.getMemberForm()
              },
              {
                comType: "button",
                icon: "icon-coms-form-delete-hot",
                label: i18n.label.multiDelete,
                rightMenuIcon: this.menuIconCollection.remove,
                onClickHandle: () => this.deleteMember(),
                checkAction: "memberRemoveable"
              }
            ];
          }
          tabs.push(tabInfo);
        });
        this._editTabs = tabs;
        this.opId = id;
        this.doEdit(id, '1');
        this.containerInitFinished.init = true;
      } else {

      }
    }, error => { });
  };

  @computed get dialogFootButtons () {
    let buttons = [];
    if (this.canAdd) {
      buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8fte55`} type="primary" op="save" onClick={() => this.save()}>
          {i18n.label.save()}
        </Button>
      ];
    }

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

  @action
  getTopProps = (single) => {
    let buttons = [];
    if (single && this.canAdd) {
      buttons = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8fte55`} type="primary" op="save" onClick={() => this.save()}>
          {i18n.label.save()}
        </Button>
      ];
    } else {
      if (this.mainActiveTabKey == '1') {
        buttons = [];
        this.canCreate && buttons.push((
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ibub0u`} type="primary" op="create" onClick={() => this.getCreateForm()}>
            {i18n.label.create()}
          </Button>
        ));
        this.canDel && buttons.push((
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fozrtx`}
            type="primary"
            op="remove"
            disabled={this.tableMultiDelete}
            onClick={() => this.doDelete()}
          >
            {i18n.label.multiDelete()}
          </Button>
        ));
      }
      if (this.mainActiveTabKey == '2') {
        buttons = [
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6lgxvb`} type="primary" op="add" onClick={this.addToGroup} disabled={this.getRowKey}>
            {getLabel('515662', '加入到考勤组')}
          </Button>,
        ]
      }

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

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

  @action
  getTableData = () => {
    const params = this.formTarget.conditionForm.getFormParams();
    Object.assign(params, {
      subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null
    });
    api.getSearchList(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 resetBaseForm = () => {
    // this.currGroupSerialids.length = 0;;
    delete this.formTarget.shiftSchedulceForm;
    delete this.formTarget.shiftSchedulceFormFields;
  }

  @action setShiftOptions = (datas) => {
    this.groupShiftOptions.length = 0;
    datas.map(d => {
      ['', '-1'].indexOf(d.id) < 0 && this.groupShiftOptions.push({
        key: d.id,
        showname: d.name
      })
    })
    this.groupShiftOptions.push({
      key: '-1',
      showname: i18n.label['26593']()
    })
    this.bChange = new Date().getTime();
  }

  @action
  getBaseForm = (params, callback) => {
    params = params || {};
    Object.assign(params, {
      subcompanyid: this.selectedSubCompany ? this.selectedSubCompany.id : null
    });
    this.canAdd = false;
    api.getBaseForm(params).then(
      data => {
        if (data.status === "1") {
          this.canAdd = data.canAdd;
          this.resetBaseForm();
          this.setFormData("baseForm", data.formField);
          const idx = findIndex(data.formField[0].items, { domkey: ['serialids'] });
          if (idx > 0) {
            const { replaceDatas } = data.formField[0].items[idx].browserConditionParam;
            this.setShiftOptions(replaceDatas)
          }
          if (has(data, 'shiftSchedulceTable')) {
            this._serialTableProps = { ...data.shiftSchedulceTable };
            // this.setFormData("shiftSchedulceForm", data.shiftSchedulce.formField);
            // this.currGroupSerialids = (data.shiftSchedulce.shiftcycleserialids === '' ? [] : data.shiftSchedulce.shiftcycleserialids.split(','));
            // this.currGroupSerialidsDirty = [...this.currGroupSerialids];
          }
          if (this.formTarget.baseForm.isFormInit) {
            callback && callback(data.fixedSchedulce);
          }
        } else {
          message.error(data.message);
        }
      },
      error => { }
    );
  };

  @action
  getKQTypeForm = (params, callback) => {
    if (this.spinning) return;
    this.spinning = true;
    this.canAdd = false;
    api.getKQTypeForm(params).then(
      data => {
        if (data.status === "1") {
          this.canAdd = data.canAdd;
          this.setFormData("kqTypeForm", data.formField);
          if (this.formTarget.kqTypeForm.isFormInit) {
            this.refreshAttendanceForm = new Date().getTime();
            callback && callback(data);
          }
        } else {
          message.error(data.message);
        }
        this.spinning = false;
      },
      error => (this.spinning = false)
    );
  };

  @action
  getMemberSearchCondition = params => {
    api.getMemberSearchCondition().then(
      data => {
        if (data.status === "1") {
          this.setFormData("memberConditionForm", data.formField);
          if (this.formTarget.memberConditionForm.isFormInit) {
            this.refreshTab = new Date().getTime();
            this.getMemberList();
          }
        } else message.error(data.message);
      },
      erro => { }
    );
  };

  @action
  getMemberList = params => {
    this.canAdd = false;
    this.canDelMember = false;
    api.getMemberList({ groupId: this.opId, ...this.formTarget.memberConditionForm.getFormParams() }).then(
      data => {
        if (data.status === "1") {
          this.canAdd = data.canAdd;
          this.canDelMember = data.canDel;
          this.memberTable = new TableStore();
          this.memberTable.getDatas(data.sessionkey, 1);
        } else message.error(data.message);
      },
      error => { }
    );
  };

  @action
  setWorkdaySettingData = schedulce => {
    this.columns.length = 0;
    this.workdaySettingData.length = 0;
    try {
      if (schedulce != null) {
        schedulce.columns.map(column => {
          let c = {
            title: column.title,
            key: column.dataIndex,
            dataIndex: column.dataIndex,
            width: column.width
          };
          if (column.dataIndex === "operate") {
            c.render = (text, record, index) => this.canAdd ? (
              <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@ta65mi@${column.dataIndex}`}
                icon="icon-coms-hrm"
                iconBgcolor="#217346"
                title={i18n.label["389091"]()}
                type={"kqshift"}
                customized
                inputStyle={{ width: 200 }}
                quickSearchName='serial'
                onChange={(ids, names, datas) =>
                  this.setShift(datas, record.id)
                }
              >
                <a>{i18n.label["24833"]()}</a>
              </WeaBrowser>
            ) : '';
          }
          this.columns.push(c);
        });
        this.workdaySettingData = schedulce.datas;
        this.selectedWorkdayKeys = [0, 1, 2, 3, 4, 5, 6];
      }
    } catch (e) { }
  };

  @action
  getCreateForm = () => {
    this.getBaseForm(null, schedulce => {
      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.setWorkdaySettingData(schedulce);
      this.dialogParams.title = i18n.label["389073"]();
      this.dialogParams.opType = "create";
      this.dialogParams.style = {
        width: 800,
        height: 680
      };
      this.dialogParams.visible = true;
    });
  };

  @action
  multiSetting = records => {
    const selectedWorkdayKeys = this.toJS(this.selectedWorkdayKeys);
    let v = {
      shiftId: null,
      shiftInfo: ""
    };
    let datas = this.toJS(this.workdaySettingData);
    if (records.length === 0) {
      datas.map(d => {
        d.serialid = null;
        d.serialinfo = i18n.label["26593"]();
      });
    } else {
      datas.map((d, index) => {
        if (selectedWorkdayKeys.indexOf(index) > -1) {
          d.serialid = records[0].id;
          d.serialinfo = records[0].aliasidspan;
        }
      });
    }
    this.workdaySettingData = datas;
  };

  @action
  setShift = (records, id) => {
    const index = findIndex(this.toJS(this.workdaySettingData), { id });
    if (records.length === 0) {
      this.workdaySettingData[index].serialid = null;
      this.workdaySettingData[index].serialinfo = i18n.label["26593"]();
    } else {
      this.workdaySettingData[index].serialid = records[0].id;
      this.workdaySettingData[index].serialinfo = records[0].aliasidspan;
    }
  };

  @action doModuleCallback = () => {
    if (this.moduleCallback != null) {
      this.moduleCallback();
    } else {
      let dia = top.window.getParentDialog();
      if (dia != null) {
        const { callback } = dia.props;
        callback && callback();
      }
    }
  }

  @action
  save = (setting = false) => {
    if (this.spinning) return;
    this.spinning = true;
    window.e9HideFormFieldKeys = [];
    let form, formParams;
    let formType = "base";
    let autoSign = false;
    if (
      this.dialogParams.opType === "create" ||
      this.editTabsActiveKey === "1"
    ) {
      form = this.formTarget.baseForm;
      formParams = form.getFormParams();
      switch (formParams.kqtype) {
        case "1":
          window.e9HideFormFieldKeys.push(
            ...["serialids", "weekday", "signstart", "workhour", "self_shift"]
          );
          break;
        case "2":
          window.e9HideFormFieldKeys.push(...["serialids", "weekday", "signstart", "workhour"]);
          break;
        case "3":
          window.e9HideFormFieldKeys.push(...['serialids', "self_shift"]);
          break;
      }
      if (formParams.validity != '1') {
        window.e9HideFormFieldKeys.push(
          ...['validityfromdate', 'validityenddate']
        );
      }
    } else if (this.editTabsActiveKey === "2") {
      formType = "kqtype";
      form = this.formTarget.kqTypeForm;
      formParams = form.getFormParams();
      const { signintype, locationcheck, wificheck, auto_checkin, auto_checkout, auto_checkout_before, auto_checkout_after } = formParams;
      if ([1, 3].indexOf(parseInt(signintype)) > -1) {
        if (locationcheck != '1' && wificheck != '1' || this.currKQType == '3') {
          window.e9HideFormFieldKeys.push(
            ...['auto_checkin', 'auto_checkin_before', 'auto_checkin_after', 'auto_checkout', 'auto_checkout_before', 'auto_checkout_after']
          );
        } else {
          autoSign = true;
          auto_checkin == '0' && window.e9HideFormFieldKeys.push(
            ...['auto_checkin', 'auto_checkin_before', 'auto_checkin_after']
          );
          auto_checkout == '0' && window.e9HideFormFieldKeys.push(
            ...['auto_checkout', 'auto_checkout_before', 'auto_checkout_after']
          );
        }
      }
    } else if (this.editTabsActiveKey === "3") {
      message.success(i18n.message.saveSuccess());
      this.spinning = false;
      this.doModuleCallback();
      return;
    }

    form.validateForm().then(f => {
      if (f.isValid) {
        if (formType == "base") {
          this.saveBaseForm(formParams, setting);
        } else {
          const { auto_checkout, auto_checkout_before, auto_checkout_after } = formParams;
          if (autoSign && auto_checkout != '0' && parseInt(auto_checkout_after || '0') <= parseInt(auto_checkout_before || '0')) {
            f.showError('auto_checkout_before', getLabel('519436', '结束时间必须大于开始时间'));
            this.spinning = false;
            return;
          }
          this.saveKQTypeForm(formParams);
        }
      } else {
        f.showErrors();
        const fields = form.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = form.getError(fields[k]);
          if (e != null && e != "") {
            if (k.indexOf('auto_checkin') > -1) {
              form.showError('auto_checkin_before', e);
            } else if (k.indexOf('auto_checkout') > -1) {
              form.showError('auto_checkout_before', e);
            }
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
        this.spinning = false;
      }
    });
  };

  @action
  saveBaseForm = (formParams, setting = false) => {
    let params = { ...formParams };
    if (formParams.kqtype === "1") {
      params.fixedSchedulce = [];
      this.toJS(this.workdaySettingData).map(d => {
        params.fixedSchedulce.push({
          id: (this.opId ? d.id : ''),
          serialid: d.serialid
        });
      });
    } else if (formParams.kqtype === "2") {
      // const shiftSchedulceFormParams = this.formTarget.shiftSchedulceForm.getFormParams();
      // this.currGroupSerialids.splice(shiftSchedulceFormParams.shiftcycleday, this.currGroupSerialids.length);
      // params.shiftSchedulce = {
      //   ...shiftSchedulceFormParams,
      //   shiftcycleserialids: this.currGroupSerialids.join()
      // }
      params.shiftSchedulce = this.serialTableProps.datas;
    }
    if (this.opId != null) params.id = this.opId;
    api.saveBaseForm({ data: JSON.stringify(params) }).then(
      data => {
        this.spinning = false;
        if (data.status === "1") {
          message.success(i18n.message.saveSuccess());
          // if(params.id == null && formParams.kqtype === "2")
          //   this.doEditSchedule(data);
          if (!this.single) {
            this.dialogParams.onCancel();
            this.getTableData();
          }
          this.doModuleCallback();
          if (setting) this.doEdit(data.id, "2");
        } else {
          message.error(data.message);
        }
      },
      error => (this.spinning = false)
    );
  };

  @action
  saveKQTypeForm = formParams => {
    let params = { ...formParams, id: this.opId };
    api.saveKQTypeForm({ data: JSON.stringify(params) }).then(
      data => {
        if (data.status === "1") {
          message.success(i18n.message.saveSuccess());
          if (!this.single) {
            this.dialogParams.onCancel();
            this.getTableData();
          }
          this.doModuleCallback();
        } else {
          message.error(data.message);
        }
        this.spinning = false;
      },
      error => (this.spinning = false)
    );
  };

  @action
  doEdit = (id, tabKey) => {
    this.opId = id;
    this.dialogParams.title = i18n.label["389108"]();
    this.dialogParams.opType = "edit";
    this.dialogParams.style = {
      width: 900,
      height: 680
    };
    this.dialogParams.visible = true;
    this.setActiveTab(tabKey);
  };

  currKQType = '';
  @action
  setActiveTab = key => {
    const tabIndex = this.getTabIndex(this.editTabConfig.tabs, key);
    if (tabIndex < 0) return;
    this.currKQType = '';
    switch (key) {
      case "1":
        this.getBaseForm({ id: this.opId }, schedulce => {
          this.setWorkdaySettingData(schedulce);
          this.refreshTab = new Date().getTime();
        });
        break;
      case "2":
        this.getKQTypeForm({ id: this.opId }, data => {
          this.currKQType = data.kqtype;
          this.helpTipMap = data.helpTipMap;
          this.locationTable = new TableStore();
          this.wifiTable = new TableStore();
          this.locationSessionKey = data.locationSessionKey;
          this.wifiSessionKey = data.wifiSessionKey;
          this.locationTable.getDatas(data.locationSessionKey, 1);
          this.wifiTable.getDatas(data.wifiSessionKey, 1);
          this.refreshTab = new Date().getTime();
        });
        break;
      case "3":
        this.getMemberSearchCondition();
        break;
    }
    this.editTabsActiveKey =
      key || this.editTabConfig.tabs[0].viewCondition;
  };

  @action
  generateSerialTable = () => {
    if (isEmpty(this.serialTableProps))
      return null;

    return (<SerialTableList ecId={`${this && this.props && this.props.ecId || ''}_SerialTableList@hv76vu`} store={this} />);
  }

  @action
  generateTable = type => {
    let title, removeable, tableStore, addFunc, removeFunc;
    switch (type) {
      case "location":
        title = i18n.label["389125"]();
        removeable = this.locationTableMultiDelete;
        tableStore = this.locationTable;
        addFunc = this.addLocation;
        removeFunc = () => this.removeLocation();
        break;
      case "wifi":
        title = i18n.label["389126"]();
        removeable = this.wifiTableMultiDelete;
        tableStore = this.wifiTable;
        addFunc = this.addWifi;
        removeFunc = () => this.removeWifi();
        break;
    }
    const removeBtnClasses = classnames({
      ["icon-coms-form-delete-hot"]: true,
      ["btn"]: true,
      ["btn-active"]: !removeable,
      ["btn-disable"]: removeable
    });

    const renderCol = (cols) => {
      cols.map((col, i) => {
        if (col.dataIndex == 'id') {
          col.render = (text, record) => {
            return this.canAdd && [
              <a onClick={() => this.editLocationOrWifi(record, type)}>{i18n.label.modify()}</a>,
              <a style={{ marginLeft: '8px' }} onClick={() => this.deleteLocationOrWifi(record.id, type)}>{i18n.label.delete()}</a>
            ]
          }
        } else if (col.dataIndex == 'locationname' || col.dataIndex == 'wifiname') {
          col.render = (text, record) => {
            return <a onClick={() => this.editLocationOrWifi(record, type)}>{record[`${col.dataIndex}span`]}</a>
          }
        }
      })
    }

    const tableProps = {
      scroll: {
        y: 400
      }
    }

    return (
      <div className="listSetting">
        <div className="listSetting-header">
          <div className="title">{title}</div>
          <div style={{ float: 'right', paddingRight: '5px' }}>
            <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@bkmvbr`} placeholder={type == 'location' ? getLabel('529681', '请输入考勤地址') : getLabel('529682', '请输入WiFi名称')} onSearch={value => this.doSearchLocationWifi(type, value)} />
          </div>
          {this.canAdd && <i
            className={removeBtnClasses}
            title={i18n.label.delete()}
            onClick={!removeable ? removeFunc : null}
          />}
          {this.canAdd && <i
            className={this.addBtnClasses}
            onClick={addFunc}
            title={i18n.label.add()}
          />}
        </div>
        <div className="table">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@${type}@c35thf`}
            comsWeaTableStore={type == 'location' ? this.locationTable : this.wifiTable}
            hasOrder={true}
            {...tableProps}
            getColumns={renderCol}
          />
        </div>
      </div>
    );
  };

  @action doSearchLocationWifi = async (type, value) => {
    const callApi = type == 'location' ? api.getGroupLocationList : api.getGroupWifiList;
    const params = {
      id: this.opId,
      [type == 'location' ? 'locationname' : 'wifiname']: value
    }
    const tableStore = type == 'location' ? this.locationTable : this.wifiTable
    const data = await callApi(params);
    if (data.status == '1') {
      tableStore.getDatas(data.sessionkey, 1);
    } else {
      message.error(data.message);
    }
  }

  @action
  addLocation = () => {
    this.locationOrWifiId = null;
    this.clearRangeParams();
    this.locationDialogParams.title = i18n.label['389213']();
    this.locationDialogParams.visible = true;
    // api.getLocationForm().then(data => {
    //   if(data.status == '1'){
    //     this.locationFormStore = new WeaForm();
    //     this.locationFormStore.initFormFields(data.formField);
    //     if (this.locationFormStore.isFormInit) {
    //       this.locationDialogParams.title = i18n.label['389213']();
    //       this.locationDialogParams.visible = true;
    //     }
    //   }
    // })
  };

  @action editLocation = record => {
    this.clearRangeParams();
    ['locationname', 'address', 'checkscope', 'longitude', 'latitude'].map(k => {
      this.setRangeParam(k, record[k]);
    })
    this.locationDialogParams.title = getLabel('386247', '编辑办公地点');
    this.locationDialogParams.visible = true;
  }

  @action
  removeLocation = (params) => {
    let content;
    if (params == null) {
      params = {
        ids: this.locationTable.selectedRowKeys
      };
      content = i18n.confirm.deleteSelected();
    } else {
      content = i18n.confirm.delete();
    }
    this.confirmInfo({
      content,
      onOk: () => {
        api.delLocation({ ...params, groupId: this.opId }).then(data => {
          if (data.status === "1") {
            this.locationTable.setSelectedRowKeys([]);
            this.locationTable.getDatas(null, 1);
          } else {
            message.error(data.message);
          }
        });
      }
    });
  };

  @action
  saveLocation = () => {
    // if(this.location == null) {
    //   message.error(i18n.label['389218']());
    //   return;
    // }
    if (this.rangeParams.locationname == null || this.rangeParams.locationname == '') {
      this.mapInfoError && this.mapInfoError['locationname'] && this.mapInfoError['locationname'].showError();
      return;
    }
    if (this.rangeParams.longitude == null || this.rangeParams.longitude == '') {
      this.mapInfoError && this.mapInfoError['longitude'] && this.mapInfoError['longitude'].showError('123');
      return;
    } else if (!/^(\-)?\d+(\.\d+)?$/.test(this.rangeParams.longitude)) {
      message.error(getLabel('529869', '请输入正确的经纬度坐标！'));
      return;
    }
    if (this.rangeParams.latitude == null || this.rangeParams.latitude == '') {
      this.mapInfoError && this.mapInfoError['latitude'] && this.mapInfoError['latitude'].showError();
      return;
    } else if (!/^(\-)?\d+(\.\d+)?$/.test(this.rangeParams.latitude)) {
      message.error(getLabel('529869', '请输入正确的经纬度坐标！'));
      return;
    }
    if (this.spinning) return;
    this.spinning = true;
    api.saveLocation({ groupId: this.opId, data: JSON.stringify({ ...this.location, groupId: this.opId, ...this.toJS(this.rangeParams), id: this.locationOrWifiId }) }).then(data => {
      if (data.status === "1") {
        this.locationDialogParams.onCancel();
        //this.locationTable = new TableStore();
        this.locationTable.getDatas(this.locationSessionKey, 1);
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }, error => this.spinning = false)
  }

  @action
  onPositionSelected = (data) => {
    this.location = data;
    ['locationname', 'address', 'longitude', 'latitude'].map(k => {
      this.setRangeParam(k, data[k]);
    });
  }

  @action
  addWifi = () => {
    this.locationOrWifiId = null;
    api.getWifiForm().then(
      data => {
        if (data.status === "1") {
          this.setFormData("wifiForm", data.formField);
          if (this.formTarget.wifiForm.isFormInit) {
            this.wifiDialogParams.title = i18n.label['389212']();
            this.wifiDialogParams.visible = true;
          }
        } else {
          message.error(data.message);
        }
      },
      error => { }
    );
  };

  @action editWifi = async record => {
    this.locationOrWifiId = record.id;
    const data = await api.getWifiForm();
    if (data.status === "1") {
      this.setFormData("wifiForm", data.formField);
      if (this.formTarget.wifiForm.isFormInit) {
        this.formTarget.wifiForm.updateFields({
          wifiname: { value: record.wifiname },
          mac: { value: record.mac },
        })
        this.wifiDialogParams.title = getLabel('529576', '编辑wifi信息');
        this.wifiDialogParams.visible = true;
      }
    } else {
      message.error(data.message);
    }
  }

  @action
  saveWifi = () => {
    if (this.spinning) return;
    this.spinning = true;
    const form = this.formTarget.wifiForm,
      formParams = form.getFormParams();
    form.validateForm().then(f => {
      if (f.isValid) {
        if (!/(([a-f0-9]{2}:)|([a-f0-9]{2}-)){5}[a-f0-9]{2}/gi.test(formParams.mac)) {
          f.showError('mac', i18n.label['389320']());
          this.spinning = false;
          return;
        }
        let params = { ...formParams, groupId: this.opId, id: this.locationOrWifiId };
        api.saveWifiForm({ groupId: this.opId, data: JSON.stringify(params) }).then(
          data => {
            if (data.status === "1") {
              this.wifiDialogParams.onCancel();
              //this.wifiTable = new TableStore();
              this.wifiTable.getDatas(this.wifiSessionKey, 1);
            } else {
              message.error(data.message);
            }
            this.spinning = false;
          },
          error => (this.spinning = false)
        );
      } else {
        this.spinning = false;
        f.showErrors();
        const fields = this.formTarget.wifiForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.wifiForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
      }
    });
  };

  @action
  removeWifi = params => {
    let content;
    if (params == null) {
      params = {
        ids: this.wifiTable.selectedRowKeys
      };
      content = i18n.confirm.deleteSelected();
    } else {
      content = i18n.confirm.delete();
    }
    this.confirmInfo({
      content,
      onOk: () => {
        api.delWifiForm({ ...params, groupId: this.opId }).then(data => {
          if (data.status === "1") {
            this.wifiTable.getDatas(null, 1);
          } else {
            message.error(data.message);
          }
        });
      }
    });
  };

  @observable memberForm = new WeaForm();
  groupmemberId = '';

  @action
  getMemberForm = (params = {}) => {
    this.groupmemberId = params.groupmemberId || '';
    this.memberForm = new WeaForm();
    api.getMemberForm(params).then(
      data => {
        if (data.status === "1") {
          this.memberAuthParams.title = i18n.label["125217"]();
          this.memberAuthParams.conditions = data.conditions;
          this.memberAuthParams.visible = true;
          this.memberForm.setCondition([
            {
              defaultshow: true,
              items: data.conditions
            }
          ]);
        } else {
          message.error(data.message);
        }
      },
      error => { }
    );
  };

  @action
  doSaveMember = (params) => {
    if (this.spinning)
      return;
    this.spinning = true;
    api.saveMemberForm(params).then(data => {
      if (data.status === '1') {
        message.success(i18n.message.saveSuccess());
        this.formTarget.memberConditionForm.resetConditionValue();
      } else
        message.error(data.message);
      this.getMemberList();
      this.memberAuthParams.onCancel();
      this.spinning = false;
    }, error => this.spinning = false)
  }

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

  @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.deleteGroup(params).then(data => {
          if (data.status === "1") {
            message.success(i18n.message.deleteSuccess());
            this.table.getDatas(null, 1);
          }
        });
      }
    });
  };

  @action
  saveSerial = () => {
    this.formTarget.shiftSchedulceForm.validateForm().then(f => {
      if (f.isValid) {
        this.serialDialogParams.onClose(f.getFormParams());
      } else {
        f.showErrors();
        const fields = this.formTarget.wifiForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.wifiForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
      }
    });
  }

  locationOrWifiId;
  @action editLocationOrWifi = (record, type) => {
    this.locationOrWifiId = record.id;
    if (type === 'location') {
      this.editLocation(record);
    }
    else
      this.editWifi(record);
  }

  @action
  deleteLocationOrWifi = (id, type) => {
    if (type === 'location')
      this.removeLocation({ ids: id });
    else
      this.removeWifi({ ids: id });
  }

  @action
  importConfig = (fileid) => {
    api.importExcel({ groupId: this.opId, filename: fileid }).then(data => {
      if (data.status === '1') {
        message.success(i18n.message.uploadSuccess());
        this.locationTable.getDatas(this.locationSessionKey, 1);
        this.wifiTable.getDatas(this.wifiSessionKey, 1);
      } else {
        message.error(data.message);
      }
    }, error => { })
  }

  @action
  exportConfig = () => {
    const downloadUrl = addContentPath('/api/hrm/kq/group/exportExcel');
    let formElement = document.createElement('form');
    formElement.style.display = "display:none;";
    formElement.method = 'post';
    formElement.action = downloadUrl;
    let inputElement = document.createElement('input');
    inputElement.type = 'hidden';
    inputElement.name = "groupId";
    inputElement.value = this.opId;
    formElement.appendChild(inputElement);
    document.body.appendChild(formElement);
    formElement.submit();
    document.body.removeChild(formElement);
  }

  @action
  doEditSchedule = record => {
    const url = `/spa/hrm/staticAttendance4engine/engine.html#/attendance/scheduleSetting/${record.id}?_key=${new Date().getTime()}`;
    window.open(url);
  }

  @action compareSearial = (v, form) => {
    if (this.showConfirm)
      return;
    this.showConfirm = true;
    let datas = [];
    v.serialids.valueObj.map(d => {
      datas.push({ id: d.id, name: d.name });
    });

    const options = filter(this.toJS(this.groupShiftOptions), v => ['', '-1'].indexOf(v.key) < 0);
    let removedIds = [], removedNames = [];
    if (options.length > 0) {
      options.map(op => {
        if (findIndex(datas, { id: op.key }) < 0) {
          removedIds.push(op.key);
          removedNames.push(op.showname);
        }
      });
      if (removedIds.length > 0) {
        this.confirmInfo({
          width: 640,
          content: (
            <div className='shiftChangeConfirm'>
              <div className='title'>{getLabel('500703', '确认从考勤组移除下列班次吗？')}</div>
              <div className='detail'>
                {
                  removedNames.map(name => <div className='name text-elli' title={name}>{name}</div>)
                }
              </div>
              <div className='tips'>{getLabel('500704', '移除后，排班周期将自动去除该班次，排班设置中已排班次不受影响')}</div>
            </div>
          ),
          onOk: () => {
            this.setShiftOptions(datas);
            let tableDatas = this.toJS(this.serialTableProps.datas);
            tableDatas = tableDatas.map(row => {
              let { serial } = row;
              let arr = serial.split(',');
              arr = arr.map(d => {
                if (findIndex(datas, { id: d }) > -1)
                  return d;
                return -1;
              })
              return {
                ...row,
                serial: arr.join(',')
              };
            })
            this._serialTableProps.datas = tableDatas;
            this.showConfirm = false;
          },
          onCancel: () => {
            let value = [], valueSpan = [], valueObj = [];
            options.map(op => {
              value.push(op.key);
              valueSpan.push(op.showname);
              valueObj.push({
                id: op.key,
                name: op.showname
              })
            })
            form.updateFields({
              serialids: {
                value: value.join(','),
                valueSpan: valueSpan.join(','),
                valueObj
              }
            });
            this.bChange = new Date().getTime();
            this.showConfirm = false;
          }
        });
      } else {
        this.setShiftOptions(datas);
        this.showConfirm = false;
      }
    } else {
      let datas = [];
      v.serialids.valueObj.map(d => {
        datas.push({ id: d.id, name: d.name });
      })
      this.setShiftOptions(datas);
      this.showConfirm = false;
    }
  }

  @action clearRangeParams = () => this.rangeParams = { locationname: '', checkscope: 500, longitude: '', latitude: '' };

  @action setRangeParam = (k, v) => {
    this.rangeParams = {...this.rangeParams, [k]: v};
    // this.rangeParams[k] = v;
  }

  mapInfoError = {};
  @action setMapInfoError = (key, ref) => this.mapInfoError[key] = ref;

  @action getShiftCycleForm = record => {
    if (this.groupShiftOptions.length > 1) {
      if (record) {
        this.currGroupSerialidsDirty = record.serial.split(',');
      } else {
        this.currGroupSerialidsDirty = this.currGroupSerialidsDirty || [];
        this.currGroupSerialidsDirty.length = 0;
      }
      api.getShiftCycleForm().then(data => {
        this.setFormData("shiftSchedulceForm", data.formField);
        this.formTarget.shiftSchedulceForm.isFormInit && record != null && this.formTarget.shiftSchedulceForm.updateFields({
          shiftcyclename: {
            value: record.shiftcyclename
          },
          shiftcycleday: {
            value: record.shiftcycleday
          }
        });
        this.showSerialDialog(record == null);
      })
      this.serialDialogParams.record = record;
    } else {
      message.error(getLabel('500479', '请选择班次'));
    }
  }

  @action showSerialDialog = (isCreate = true) => {
    if (this.formTarget.shiftSchedulceForm.isFormInit) {
      this.serialDialogParams.title = i18n.label['389225']();
      this.serialDialogParams.visible = true;
      this.serialDialogParams.isCreate = isCreate;
    }
  }

  @action deleteSerial = record => {
    const { id, key } = record;
    this.confirmInfo({
      content: i18n.confirm.delete(),
      onOk: () => {
        let { columns, datas } = this.serialTableProps;
        datas = _.filter(datas, v => v.id != id || v.key != key);
        this._serialTableProps = { columns, datas };
        // api.delLocation({...params, groupId: this.opId}).then(data => {
        //   if (data.status === "1") {
        //     this.locationTable.setSelectedRowKeys([]);
        //     this.locationTable.getDatas(null, 1);
        //   }
        // });
      }
    });
  }
  /********************* action list *********************/

  //************************************************************** */ 人员考勤组查询 */ **********************************************************
  buttons = [
    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@08207j`} type="primary" onClick={this.saveGroup} loading={this.spinning}>{i18n.label.save()}</Button>,
    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uadfxk`} type="ghost" onClick={this.onCancel}>{i18n.label.cancel()}</Button>
  ]

  @observable config = [];
  @observable searchTable = new TableStore();
  @observable searchColumns = [];
  @observable searchDatas = [];
  @observable addToGroupForm = new WeaForm();
  @observable addToGroupCondition = [];
  @observable loading = false;
  @observable selectId = ''; // 人员id
  @observable groupId = ''; // 考勤组id
  @observable selectedGroupRow = [];
  @observable rowKey = [];
  @observable lastparams = {};

  @observable pageIndex = 1;
  @observable pageSize = 10;
  @observable total = 0;

  @observable radioParams = {};
  @observable orderParams = {};

  @observable order = '';
  @observable columnKey = '';

  @observable spinning = false;


  @computed get tableProps () {
    return ({
      rowSelection: {
        selectedRowKeys: this.toJS(this.rowKey),
        getCheckboxProps: record => { // 选择框默认属性配置
          return { disabled: record.groupIds.length > 0 || !record.canEdit };
        },
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowKey = selectedRowKeys;
          this.selectedGroupRow = selectedRows;
        }
      }
    }
    )
  }

  // 加入考勤组按钮disabled计算
  @computed get getRowKey () {
    return this.rowKey.length === 0;
  }


  @observable addDialogParams = {
    title: getLabel('515662', '加入到考勤组'),
    icon: "icon-coms-hrm",
    iconBgcolor: "#217346",
    visible: false,
    style: { height: 100, width: 700 },
    buttons: this.buttons,
    onCancel: () => {
      this.addDialogParams.visible = false;
    }
  }


  @action tabChangeHandle = (key) => {
    this.mainActiveTabKey = key;
    key == '1' && this.init();
  }

  // @action initSearchGroup = () => {
  //   this.initData();

  // }

  // 数据初始化
  @action initData = () => {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.total = 0;
    this.selectId = ''; // 人员id
    this.groupId = ''; // 考勤组id
    this.selectedGroupRow = [];
    this.rowKey = [];
    this.lastparams = {};
    this.radioParams = {};
    this.config = [];
    this.getGroupMemeberCondition();
  }

  // 考勤组查询groupRadio
  @action getGroupMemeberCondition = () => {
    api.getGroupMemeberCondition().then(resp => {
      this.config = resp.conditions;
    })
  }

  // 考勤组查询列表渲染
  @action getGroupMemberList = (params) => {
    if (this.spinning)
      return;
    this.loading = true;
    this.spinning = true;
    api.getGroupMemberList(params).then(resp => {
      if (resp.status == '1') {
        this.pageIndex = resp.pageIndex;
        this.total = resp.total;
        this.searchDatas = resp.dataSource;
        this.searchColumns = this.setColumns(resp.columns);
        this.loading = false;
        this.spinning = false;
      } else {
        message.error(resp.message);
        this.loading = false;
      }

    })
  }

  // 设置定制列
  @action setColumns = (columns) => {
    columns.map((c, i) => {
      if (c.key == 'lastname') {
        c.sorter = true;
        c.render = (text, record, index) => {
          return <a href={`javaScript:openhrm(${record.id});`} onClick={e => window.pointerXY(e)} title={text}><div className='text-elli' >{text}</div></a>;
        }
      }
      if (c.key == "departmentid") {
        c.sorter = true;
        c.render = (text, record, index) => {
          return record.departmentName
        }
      }
      if (c.key == 'subcompanyid1') {
        c.sorter = true;
        c.render = (text, record, index) => {
          return record.subcompanyName
        }
      }
      if (c.key == 'groups') {
        c.render = (text, record, index) => {
          if (isEmpty(text) && record.canEdit) {
            return <a onClick={() => this.getAddMemberCondition(record.id)} ><div className='text-elli' style={{ color: 'red' }}>{getLabel('514133', '未设置')}</div></a>
          }
          else if (isEmpty(text) && !record.canEdit) {
            return <div className='text-elli' >{getLabel('514133', '未设置')}</div>
          } else {
            return record.groups.map((item, index) => {
              return index === record.groups.length - 1 ?
                <span style={{ wordBreak: "break-all" }}><div style={{ display: 'inline' }}>{item}</div></span>
                :
                <span style={{ wordBreak: "break-all" }}><div style={{ display: 'inline' }}>{item}</div>{'，'}</span>;
            })
          }

        }
      }

    })

    return columns;
  }

  // 点击未设置的a标签，获取添加考勤组的表单
  @action getAddMemberCondition = (id) => {
    api.getAddMemberCondition().then(resp => {
      this.addToGroupForm = new WeaForm();
      this.addToGroupCondition.length = 0;
      this.addToGroupCondition = resp.condition;
      this.addToGroupForm.initFormFields(this.addToGroupCondition);
      this.addDialogParams.visible = true;
      this.selectId = id; //选中的那行数据的人员id
    })
  }

  // 弹框取消、关闭
  @action onCancel = () => {
    this.addDialogParams.visible = false;
  }

  // 选择考勤组加入
  @action chooseGroup = (data) => {
    this.groupId = data.groupId.value;
  }

  //加入考勤组保存
  @action saveGroup = () => {
    this.spinning = true
    let params = {
      ids: this.selectId,
      groupId: this.groupId
    }
    this.addToGroupForm.validateForm().then(f => {
      if (f.isValid) {
        api.saveAddMember(params).then(resp => {
          this.spinning = false;
          if (resp.status == '1') {
            message.success(i18n.message.saveSuccess());
            this.rowKey.length = 0;
            this.addDialogParams.visible = false;
            this.getGroupMemberList(this.radioParams);

          }
        })
      } else {
        f.showErrors();
        this.spinning = false;
      }
    });

  }

  //点击加入考勤组
  @action addToGroup = () => {
    const id = [];
    this.selectedGroupRow.map(c => {
      id.push(c.id)
    })
    id.join(',');
    this.getAddMemberCondition(id);
  }

  // 范围条件切换
  @action radioChange = (data) => {
    if (!data.viewScope) {
      data.viewScope = '0'
    }
    this.radioParams = data;
    if (data.viewScope == '0' && (data.groupType == '0' || data.groupType == '1') || data.subcompanyId || data.departmentId || data.resourceId || data.allLevel || data.viewScope == '4' || data.groupType == '2' && data.groupId && (data.viewScope == '0' || data.viewScope == '1' && data.subcompanyId || data.viewScope == '2' && data.departmentId || data.viewScope == '3' && data.resourceId)) {
      this.getGroupMemberList({
        ...this.orderParams,
        ...data,
        pageSize: this.pageSize,
        pageIndex: 1
      })
    }

  }

  // 获取分页参数
  @action getPagenitionParams = (pageIndex, pageSize) => {
    this.pageIndex = pageIndex || 1;
    this.pageSize = pageSize || this.pageSize;
    const params = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize
    }
    this.getGroupMemberList({
      ...params,
      ...this.radioParams,
      ...this.orderParams
    })
  }

  // 排序
  @action tableChange = (pagination, filters, sorter) => {
    if (sorter.order && sorter.order != this.order || sorter.columnKey && sorter.columnKey != this.columnKey) {
      this.order = sorter.order;
      this.columnKey = sorter.columnKey;
      let type = '';
      if (sorter.order == "descend") {
        type = 'desc'
      }
      if (sorter.order == "ascend") {
        type = 'asc'
      }
      this.orderParams = {
        orderParams: JSON.stringify([{
          orderKey: sorter.columnKey,
          orderType: type
        }])
      }
      this.getGroupMemberList({
        ...this.radioParams,
        ...this.orderParams,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex
      })
    } else {
      return;
    }
  }

  @action setRadioConfig = (data) => {
    const b = !!this.config.length
    b && this.config[0] && Object.assign(this.config[0].selectLinkageDatas[1].browserConditionParam.replaceDatas, [
      {
        id: data.id,
        name: data.name
      }
    ])

    b && this.config[0] && this.config[0].options.map(c => {
      if (c.key == '1') {
        c.selected = true;
      } else {
        c.selected = false;
      }
    })
  }


}

export const hrmGroupSetting = new HrmGroupSetting();