import { observable, action } from 'mobx';
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import { Modal, message } from 'antd'
const confirm = Modal.confirm;
import { WeaForm } from 'comsMobx';
import * as API from '../apis/add';
import { validate, getFormParamValue } from '../util'
import * as PublicFunc from '../util/pulic-func';
import cloneDeep from 'lodash/cloneDeep'
import isEmpty from 'lodash/isEmpty'
import forEach from 'lodash/forEach'
import filter from 'lodash/filter'
import { WeaTableNew } from 'comsMobx'
const { TableStore } = WeaTableNew;
import { i18n } from '../public/i18n';
import * as mobx from 'mobx';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;
import {
  RSAEcrypt
} from "../util/RSAUtil";
import {
  checkWeakPass
} from "../util/PASSUtil.js";
//gai
export class HrmAdd {
  @observable title = i18n.module.createResource;
  @observable hasRight = false;
  @observable verified = false;
  @observable simpleVisible = false;
  @observable fullVisible = false;
  @observable formSearch = new WeaForm();
  @observable formSimple = new WeaForm();
  @observable formFull = new WeaForm();
  @observable table = new TableStore();
  @observable condition = [];
  @observable showSearchAd = false;
  @observable searchParamsAd = {};
  @observable dataKey = '';
  @observable passwordComplexity = "0";
  @observable minpasslen = 1;
  @observable canSave = true;
  @observable loading = false;
  @observable hrmId = '';
  @observable conditionInfo = [];
  @observable saveAndNew = false;
  @observable updateScroll = false;
  @observable current = 0;
  @observable conditionInfo0 = [];
  @observable conditionInfo1 = [];
  @observable conditionInfo2 = [];
  @observable conditionInfo3 = [];
  @observable tableInfo1 = [];
  @observable tableInfo2 = [];
  @observable tabInfo1 = [];
  @observable tabInfo2 = [];
  @observable tabkey1 = 0;
  @observable tabkey2 = 0;
  @observable departmentid = '';
  @observable openRSA = '';
  @observable jobtitleVisible = false;
  @observable searchsValue = "";//存储快捷搜索的值
  showFormFields = [];
  @observable dialogDefShow = '';//默认弹窗控制变量
  @observable isUsedAsSingle = false;

  @action setSearchsValue = (v) => {
    this.searchsValue = v;
  }

  updateTabkey = (key) => {
    const current = this.current;
    if (current == 1) this.tabkey1 = key;
    if (current == 2) this.tabkey2 = key;
  }

  getTabInfo = () => {
    this.tabInfo1 = [];
    this.tabInfo2 = [];
    this.tableInfo1 && this.tableInfo1.forEach((c, idx) => {
      !c.hide && this.tabInfo1.push({
        key: `${idx}`,
        title: c.tabname,
      })
    })
    this.tableInfo2 && this.tableInfo2.forEach((c, idx) => {
      !c.hide && this.tabInfo2.push({
        key: `${idx}`,
        title: c.tabname,
      })
    })
  }

  @action getData = (params = {}) => {
    this.getSearchCondition();
    this.getSearchList();
  }

  checkRight = () => {
    this.verified = false;
    API.hasRight().then((data) => {
      this.hasRight = data.hasRight;
      this.verified = true;
    });
  }

  getSearchCondition = (params = {}) => {
    API.getSearchCondition(params).then((data) => {
      this.formSearch = new WeaForm();
      this.condition = data.condition;
      this.formSearch.initFormFields(data.condition);
    });
  }

  doSearch = (params = {}) => {
    this.formSearch.updateFields({
      resourcename: { name: 'resourcename', value: this.searchsValue },
    });
    const formParams = this.formSearch.getFormParams();
    formParams.search = "search";
    this.getSearchList({ ...params, ...formParams });
    this.departmentid = params.departmentid;
  }

  getSearchList = (params = {}) => {
    API.getSearchList(params).then((data) => {
      this.dataKey = data.sessionkey;
      this.table.getDatas(data.sessionkey, 1);
    });
  }

  getHrmResourceAddForm = (params = {}) => {
    this.loading = true;
    const { type } = params;
    params.departmentid = this.departmentid;
    API.getHrmResourceAddForm(params).then((data) => {
      this.loading = false;
      this.hasJobTitlesAdd = data.hasJobTitlesAdd;
      if (type == 'simple') {
        this.saveAndNew = false;
        this.conditionInfo = this.processCondition(data.condition);
        this.formSimple = new WeaForm();
        this.formSimple.initFormFields(data.condition);
        let resourceimageid = getFormParamValue(data.condition, 'resourceimageid');
        this.formSimple.updateFields({
          resourceimageid: { name: 'resourceimageid', value: resourceimageid }
        });
        this.openRSA = data.openRSA;
      } else {
        this.conditionInfo0 = this.processCondition(data.basecondition);
        this.conditionInfo1 = data.personalcondition || [];
        this.conditionInfo2 = data.workcondition || [];
        this.conditionInfo3 = data.systeminfocondition || [];
        this.tableInfo1 = filter(data.personaltables || [], { hide: false });
        this.tableInfo2 = filter(data.worktables || [], { hide: false });
        this.getTabInfo();
        this.tabkey1 = 0;
        this.tabkey2 = 0;
        this.hrmId = data.hrmId;
        let conditions = [...this.conditionInfo0, ...this.conditionInfo1, ...this.conditionInfo2, ...this.conditionInfo3];
        this.formFull = new WeaForm();
        this.formFull.initFormFields(conditions);
        let resourceimageid = getFormParamValue(conditions, 'resourceimageid');
        this.formFull.updateFields({
          resourceimageid: { name: 'resourceimageid', value: resourceimageid }
        });

        this.collectShowFields(data.basecondition);
      }
      this.passwordComplexity = data.passwordComplexity;
      this.minpasslen = data.minpasslen;
      this.openRSA = data.openRSA;
    });
  }

  processCondition = (condition) => {
    condition.map(c => c.items.map(item => {
      if (item.domkey[0] === "jobtitle") {
        item.otherParams = {
          hasAddBtn: true,
          addOnClick: () => {
            this.openJobtitleDialog()
          }
        }
      }
    }));
    return condition;
  }

  openJobtitleDialog = () => {
    this.jobtitleVisible = true;
  }

  closeJobtitleDialog = () => {
    this.jobtitleVisible = false;
  }

  update = () => {
    this.table.tableUpdate({ datas: [] });//清空缓存
    this.table.getDatas(this.dataKey, 1);//刷新table
  }

  setShowSearchAd = (bool) => {
    this.showSearchAd = bool;
    if (bool) {
      this.formSearch.updateFields({
        resourcename: { name: 'resourcename', value: this.searchsValue },
      });
    }
  }

  collectShowFields = (conditions) => {
    this.showFormFields = [];
    conditions.map(c => c.items.map(item => {
      const { otherParams, domkey } = item;
      if (
        !otherParams ||
        (otherParams && !otherParams.hide)
      ) {
        this.showFormFields.push(domkey[0]);
      }
    }));
  }

  save = (callback) => {
    const __this = this;
    const conditionInfo = this.conditionInfo;
    const formParams = this.formSimple.getFormParams();
    const lastname = formParams.lastname || '';
    const workcode = formParams.workcode || '';
    const managerid = formParams.managerid || '';
    const accounttype = formParams.accounttype || '';
    const belongto = formParams.belongto || '';
    const email = formParams.email || '';
    const telephone = formParams.telephone || '';
    const mobile = formParams.mobile || '';
    if (validate(conditionInfo, formParams)) {
      //选次账号后，必须选主账号
      if (accounttype && accounttype == 1) {
        if (!belongto || belongto == '') {
          message.warning(getLabel('386411', "主账号未填写"));
          callback && callback();
          return;
        }
      }
      if (!this.checkPassword()) {
        callback && callback();
        return;
      }
      if (!PublicFunc.chkMail(email)) {
        callback && callback();
        return false;
      }
      if (managerid == '') {
        confirm({
          title: i18n.confirm.systemhints(),
          content: getLabel('16072', "此员工还没有输入直接上级，确定不输入吗？"),
          onOk () {
            WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET',
              { ...{ lastname, workcode, managerid, telephone, mobile,sensitiveWordconfirm: 1 } }).
              then(data => {
                if (data.status == '-1') {
                  if (data.messagetype == 'confirm') {
                    confirm({
                      title: i18n.confirm.systemhints(),
                      content: data.message,
                      onOk () {
                        __this.doSave(callback);
                      },
                      onCancel () { },
                    });
                  } else {
                    message.warning(data.message);
                    callback && callback();
                  }
                } else {
                  __this.doSave(callback);
                }
              }, error => {
                message.warning(error.message);
                callback && callback();
              })
          },
          onCancel () { },
        });
      } else {
        WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET',
          { ...{ lastname, workcode, managerid, telephone, mobile,sensitiveWordconfirm: 1 } }).
          then(data => {
            if (data.status == '-1') {
              if (data.messagetype == 'confirm') {
                confirm({
                  title: i18n.confirm.systemhints(),
                  content: data.message,
                  onOk () {
                    __this.doSave(callback);
                  },
                  onCancel () { },
                });
              } else {
                message.warning(data.message);
                callback && callback();
              }
            } else {
              __this.doSave(callback);
            }
          }, error => {
            message.warning(error.message);
            callback && callback();
          })
      }

    }
  }

  myvalidate = (cb) => {
    const current = this.current;
    const formFull = this.formFull;
    const formParams = formFull.getFormParams();
    if (current == 0) {
      const conditionInfo0 = this.conditionInfo0;
      const lastname = formParams.lastname || '';
      const workcode = formParams.workcode || '';
      const managerid = formParams.managerid || '';
      const accounttype = formParams.accounttype || '';
      const belongto = formParams.belongto || '';
      const email = formParams.email || '';
      const telephone = formParams.telephone || '';
      const mobile = formParams.mobile || '';

      if (validate(conditionInfo0, formParams)) {
        //选次账号后，必须选主账号
        if (accounttype && accounttype == 1) {
          if (!belongto || belongto == '') {
            message.warning(getLabel('386411', "主账号未填写"));
            return;
          }
        }
        if (this.showFormFields.includes('email') && !PublicFunc.chkMail(email)) return false;
        if (managerid == '') {
          confirm({
            title: i18n.confirm.systemhints(),
            content: getLabel('16072', "此员工还没有输入直接上级，确定不输入吗？"),
            onOk () {
              WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET',
                { ...{ lastname, workcode, managerid, telephone, mobile,sensitiveWordconfirm: 1 } }).
                then(data => {
                  if (data.status == '-1') {
                    if (data.messagetype == 'confirm') {
                      confirm({
                        title: i18n.confirm.systemhints(),
                        content: data.message,
                        onOk () {
                          cb();
                        },
                        onCancel () { },
                      });
                    } else {
                      message.warning(data.message);
                    }
                  } else {
                    cb();
                  }
                }, error => {
                  message.warning(error.message);
                })
            },
            onCancel () { },
          });
        } else {
          WeaTools.callApi('/api/hrm/resource/hrmResourceCheck', 'GET',
            { ...{ lastname, workcode, managerid, telephone, mobile,sensitiveWordconfirm: 1 } }).
            then(data => {
              if (data.status == '-1') {
                if (data.messagetype == 'confirm') {
                  confirm({
                    title: i18n.confirm.systemhints(),
                    content: data.message,
                    onOk () {
                      cb();
                    },
                    onCancel () { },
                  });
                } else {
                  message.warning(data.message);
                }
              } else {
                cb();
              }
            }, error => {
              message.warning(error.message);
            })
        }

      }
    } else {
      if (validate(this[`conditionInfo${this.current}`], formParams)) {
        cb();
      }
    }
  }

  saveFull = (callback) => {
    const formParams = this.formFull.getFormParams();
    if (!this.checkPassword()) return false;
    this.doSaveFull(callback);
  }

  doSaveFull = (callback) => {
    const canSave = this.canSave;
    if (canSave) {
      let pDatas = this.formFull.getFormParams();
      if (this.conditionInfo3.length > 0 && pDatas.validatecode.trim() == '') {
        message.error(getLabel('84270', "请输入验证码"), 3);
        return;
      }
      let saveAndNew = this.saveAndNew;
      let tableInfo1 = this.tableInfo1;
      let tableInfo2 = this.tableInfo2;
      tableInfo1 && tableInfo1.forEach(t => {
        t.tabinfo.datas = t.tabinfo.datas || [];
        pDatas[t.tabinfo.rownum] = t.tabinfo.datas.length;
        t.tabinfo && t.tabinfo.datas && t.tabinfo.datas.forEach((item, index) => {
          !isEmpty(item) && forEach(item, (value, key) => {
            pDatas[`${key}_${index}`] = value;
          })
        })
      })
      const { loginid } = pDatas;

      tableInfo2 && tableInfo2.forEach(t => {
        t.tabinfo.datas = t.tabinfo.datas || [];
        pDatas[t.tabinfo.rownum] = t.tabinfo.datas.length;
        t.tabinfo && t.tabinfo.datas && t.tabinfo.datas.forEach((item, index) => {
          !isEmpty(item) && forEach(item, (value, key) => {
            pDatas[`${key}_${index}`] = value;
          })
        })
      })
      let RSAParam = {
        'password': pDatas.password,
        'password1': pDatas.password1
      }
      RSAEcrypt(this.openRSA, RSAParam).then(RSAParam => {
        pDatas = {
          ...pDatas,
          ...RSAParam
        }

        const save = () => {
          this.canSave = false;
          WeaTools.callApi('/api/hrm/resource/add/save', 'POST', pDatas).
            then(data => {
              this.canSave = true;
              if (data.status == '1') {
                message.success(i18n.message.saveSuccess());
                this.conditionInfo0 = [];
                this.conditionInfo1 = [];
                this.conditionInfo2 = [];
                this.conditionInfo3 = [];
                this.tableInfo1 = [];
                this.tableInfo2 = [];
                this.passwordComplexity = "0";
                this.minpasslen = 1;
                this.hrmId = '';
                this.fullVisible = false;
                this.update();
              } else {
                message.warning(data.message);
                callback && callback();
              }
            }, error => {
              message.warning(error.message);
              callback && callback();
            })
        }
        if (!loginid) {//没有填写登录名,不需要校验弱密码
          save();
        } else {
          const { password, accounttype } = pDatas;
          if ((accounttype != "1") && ("password" in pDatas) && password != "") {
            checkWeakPass(RSAParam.password, () => save())
          } else {
            save();
          }
        }
      });
    }
  }

  updateKey = () => {
    const formParams = this.formFull.getFormParams();
    const needusb = formParams.userUsbType;
    if (needusb == "2") {
      let returnstr = this.getUserName() || '';
      if (returnstr != "") {
        this.formFull.updateFields({
          loginid: { name: 'loginid', value: returnstr },
        });
      }
    } else if (needusb == "3") {
      this.bindTokenKey();
    }
  }

  bindTokenKey = () => {
    const title = "";
    let url = "/spa/hrm/index_mobx.html#/main/hrm/BindTokenKey?requestFrom=system&userid=";
    const dialog = ecCom.WeaTools.createDialog({
      title,
      url,
      style: {
        width: 700,
        height: 365
      }
    });
    dialog.show();
  }

  getUserName = () => {
    try {
      let vbsserial = "";
      let hCard = htactx.OpenDevice(1);//打开设备
      if (hCard == 0) {
        message.warning(getLabel('21607', "请确认您已经正确地安装了驱动程序并插入了usb令牌"));
        return vbsserial;
      }

      try {
        vbsserial = htactx.GetUserName(hCard);//获取用户名
        htactx.CloseDevice(hCard)
        return vbsserial;
      } catch (e) {
        message.warning(getLabel('21607', "请确认您已经正确地安装了驱动程序并插入了usb令牌") + '2');
        htactx.CloseDevice(hCard);
        return vbsserial;
      }
    } catch (e) {
      message.warning(getLabel('21607', "请确认您已经正确地安装了驱动程序并插入了usb令牌"));
      htactx.CloseDevice(hCard);
      return vbsserial;
    }
  }

  doSave = (callback) => {
    const canSave = this.canSave;
    if (canSave) {
      const saveAndNew = this.saveAndNew;
      const formParams = this.formSimple.getFormParams();
      let RSAParam = {
        'password': formParams.password,
        'password1': formParams.password1,
      }
      const { loginid } = formParams;
      RSAEcrypt(this.openRSA, RSAParam).then(RSAParam => {
        const save = () => {
          this.canSave = false;
          WeaTools.callApi('/api/hrm/resource/add/save', 'POST', {
            ...{
              type: 'simple'
            },
            ...toJS(formParams),
            ...RSAParam
          }).
            then(data => {
              this.canSave = true;
              if (data.status == '1') {
                message.success(i18n.message.saveSuccess());
                if (!this.saveAndNew) {
                  this.simpleVisible = false;
                } else {
                  this.conditionInfo = [];
                  this.getHrmResourceAddForm({
                    'type': 'simple'
                  });
                }
               let dialogMapper =  top.window.dialogMapper;
               
                if (dialogMapper) {
                  for(let id in dialogMapper){
                    let dialog = dialogMapper[id];
                    dialog.close();
                    dialog.callback({}); 
                  }
                }else{
                   this.update();
                }
              } else {
                message.warning(data.message);
                callback && callback();
              }
            }, error => {
              message.warning(error.message);
              callback && callback();
            })
        }
        if (!loginid) {//没有填写登录名,不需要校验弱密码
          save();
        } else {
          const { password, accounttype } = formParams;
          if ((accounttype != "1") && ("password" in formParams) && password != "") {
            checkWeakPass(RSAParam.password, () => save())
          } else {
            save();
          }
        }
      });
    }
  }

  onTabChange = (key) => {
    const current = this.current;
    if (current === 1) this.tabkey1 = key;
    if (current === 2) this.tabkey2 = key;
  }

  tableEditChange = (data) => {
    let current = this.current;
    let tabkey1 = this.tabkey1;
    let tabkey2 = this.tabkey2;
    let tableInfo1 = this.tableInfo1;
    let tableInfo2 = this.tableInfo2;
    let tableInfo, key;
    if (current === 1) {
      key = tabkey1 || 0;
      tableInfo1 = toJS(tableInfo1);
      tableInfo = cloneDeep(tableInfo1);
      tableInfo[Number(key)].tabinfo.datas = data;
      this.tableInfo1 = tableInfo;
    }
    if (current === 2) {
      key = tabkey2 || 0;
      tableInfo2 = toJS(tableInfo2);
      tableInfo = cloneDeep(tableInfo2);
      tableInfo[Number(key)].tabinfo.datas = data;
      this.tableInfo2 = tableInfo;
    }
  }

  doSaveAndNew = (callback) => {
    this.saveAndNew = true;
    this.save(callback);
  }

  openSimplemode = () => {
    this.conditionInfo = [];
    this.simpleVisible = true;
    this.fullVisible = false;
  }

  openFullmode = () => {
    this.conditionInfo = [];
    this.simpleVisible = false;
    this.fullVisible = true;
  }

  checkPassword = () => {
    const passwordComplexity = this.passwordComplexity;
    const minpasslen = this.minpasslen;
    let formParams = {};
    if (this.simpleVisible) {
      formParams = this.formSimple.getFormParams();
    } else {
      formParams = this.formFull.getFormParams();
    }
    let accounttype = formParams.accounttype || '';//登录名
    if (accounttype && accounttype == 1) {//主账号才校验密码
      return true;
    }
    let loginid = formParams.loginid || '';//登录名
    let cs = formParams.password || '';//新密码
    let cs1 = formParams.password1 || '';//确认密码
    let checkpass = true;

    if (cs == '') return checkpass;

    if (("loginid" in formParams) && loginid == '') {
      message.warning(getLabel('386412', "登录名不能为空!"));
      return false;
    }

    if (cs.length < minpasslen) {
      message.warning(getLabel('386413', "密码长度不能小于") + minpasslen);
      return false;
    }
    if (cs != cs1) {
      message.warning(getLabel('386414', "密码确认不正确"));
      return false;
    }

    if (passwordComplexity == "1") {
      const complexity11 = /[a-z]+/;
      const complexity12 = /[A-Z]+/;
      const complexity13 = /\d+/;
      if (cs != "") {
        if (complexity11.test(cs) && complexity12.test(cs) && complexity13.test(cs)) {
          checkpass = true;
        } else {
          message.warning(getLabel('533396', "新密码不符合要求，必须包含字母大写、字母小写、数字！请重新输入！"));
          checkpass = false;
        }
      }
    } else if (passwordComplexity == "2") {
      const complexity21 = /[a-zA-Z_]+/;
      const complexity22 = /\W+/;
      const complexity23 = /\d+/;
      if (cs != "") {
        if (complexity21.test(cs) && complexity22.test(cs) && complexity23.test(cs)) {
          checkpass = true;
        } else {
          message.warning(getLabel('533374', "新密码不符合要求，必须包含字母、数字、特殊字符！请重新输入！"));
          checkpass = false;
        }
      }
    } else if (passwordComplexity == "3") {
      const complexity31 = /[a-zA-Z_]+/;
      const complexity32 = /\d+/;
      if (cs != "") {
        if (complexity31.test(cs) && complexity32.test(cs)) {
          checkpass = true;
        } else {
          message.warning(getLabel('533397', "新密码不符合要求，必须包含字母、数字！请重新输入！"));
          checkpass = false;
        }
      }
    }
    return checkpass;
  }

  calYear = (startdate) => {
    let value = 0.00;
    if (startdate) {
      const beginTime = new Date(startdate).getTime();
      const endTime = new Date(this.getToday()).getTime();
      if (endTime > beginTime) {
        value = ((endTime - beginTime) / (24 * 3600 * 1000 * 365.0)).toFixed(2);
      }
    }
    return value;
  }

  getToday = () => {
    let now = new Date(); //当前日期
    let nowYear = now.getFullYear(); //当前年
    let nowMonth = now.getMonth(); //当前月
    let nowDay = now.getDate(); //当前日
    let today = this.formatDate(new Date(nowYear, nowMonth, nowDay));//今天
    return today;
  }

  formatDate = (date) => {
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1;
    var dd = date.getDate();
    return (yy + "-" + this.adjust(mm) + "-" + this.adjust(dd));
  }

  adjust = (num) => {
    if (num < 10) {
      return "0" + num;
    } else {
      return "" + num;
    }
  }
  //从后端获取默认显示的dialog
  @action setDefDialog = () => {
    API.getNewResourceMode().then(data => {
      console.log(data);
      this.dialogDefShow = data.newResourceMode;
      console.log(this.dialogDefShow);
      if (this.dialogDefShow == '0') {
        this.simpleVisible = true;
      } if (this.dialogDefShow == '1') {
        this.fullVisible = true;
      }
    })
  }

}