import {
  message
} from 'antd';
import {
  observable,
  action
} from 'mobx';
import {
  WeaForm
} from 'comsMobx';
import * as API from '../apis/systeminfo';
import * as Util from '../util/index';
import moment from 'moment';
import _isNaN from 'lodash/isNaN';
import * as mobx from 'mobx';
import {
  WeaTools
} from 'ecCom'
import * as PublicFunc from '../util/pulic-func';
import {
  i18n
} from '../public/i18n';
import {
  WeaLocaleProvider
} from 'ecCom';
import {
  checkWeakPass
} from "../util/PASSUtil.js";

const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;

export class HrmSystemInfo {
  loading = false;
  title = i18n.label.sysInfo;
  viewDate = new moment().format('YYYY-MM-DD');
  pickerValue = new moment().add(1, 'day').format('YYYY-MM-DD');

  @observable hrmId = '';
  @observable isEditor = false;
  @observable checkValue = '0';
  @observable inputVlaue = '';
  @observable selectValue = '0';
  @observable form = new WeaForm();
  @observable buttons = {};
  @observable formFields = [];
  @observable settings = {};
  @observable weekInfo = {};
  @observable date = new Date().getTime();
  @observable isSelef = false;
  @observable openRSA = "0";

  @observable options = [{
    key: '0',
    showname: '启用'
  }, {
    key: '2',
    showname: '网段策略'
  }];

  @observable bodyConf = [{
    title: '签到信息',
    icon: 'icon-Human-resources-Sign-in-information',
    fields: ['signintime', 'signinip'],
    isRow: false,
    fieldsConf: [{
      title: '时间',
      icon: 'icon-Human-resources-late',
    }, {
      title: 'IP',
      icon: 'icon-Human-resources-IP',
      isIp: true,
    }]
  }, {
    title: '签退信息',
    icon: 'icon-Human-resources-Sign-out',
    fields: ['signouttime', 'signoutip'],
    isRow: false,
    fieldsConf: [{
      title: '时间',
      icon: 'icon-Human-resources-late',
    }, {
      title: 'IP',
      icon: 'icon-Human-resources-IP',
      isIp: true,
    }]
  }, {
    title: '微博填写',
    icon: 'icon-Human-resources-micro-blog',
    fields: ['blogcreated'],
    isRow: true,
    fieldsConf: [{
      title: '时间',
      icon: 'icon-Human-resources-late',
    }]
  }, {
    title: '出差信息',
    icon: 'icon-Human-resources-business-travel',
    fields: ['businesstravelbegin', 'businesstravelend'],
    isRow: false,
    fieldsConf: [{
      title: '开始',
      icon: 'icon-Human-resources-late',
    }, {
      title: '结束',
      icon: 'icon-Human-resources-late',
    }]
  }, {
    title: '移动签到',
    icon: 'icon-Human-resources-Mobile-sign-in',
    fields: ['mobilesignaddr'],
    isRow: true,
    fieldsConf: [{
      title: '地址',
      icon: 'icon-Human-resources-Mobile-sign-in',
    }]
  }]

  @action
  init = () => {
    this.viewDate = new moment().format('YYYY-MM-DD');
    this.isEditor = false;
    this.checkValue = '0';
    this.inputVlaue = '';
    this.selectValue = '0';
    this.form = new WeaForm();
    this.buttons = {};
    this.formFields = [];
    this.settings = {};
    this.weekInfo = {};
  }

  getFormField = () => {
    let params = {
      id: this.hrmId
    };
    API.getFormField(params).then((data) => {
      this.buttons = data.buttons;
      this.formFields = data.condition;
      this.checkValue = data.needauto,
        this.pickerValue = data.enableDate,
        this.selectValue = data.enableUsbType,
        this.inputVlaue = data.enableDate && data.enableDate != '' && moment(data.enableDate).diff(moment(), 'days') + 1,
        this.settings = data.settings;
      this.isSelef = data.isSelef;
      this.openRSA = data.openRSA;
      this.form.initFormFields(data.condition);
    });
  }

  getWeekInfo = (v) => {
    let params = {
      id: this.hrmId,
      datefrom: v
    };
    API.getWeekInfo(params).then((data) => {
      this.weekInfo = data
    });
  }

  getDateLabel = () => {
    let str = this.viewDate;
    if (new moment().format('YYYY-MM-DD') == this.viewDate) str = '今天';
    return str;
  }

  onCheckChange = (v) => {
    this.checkValue = v;
  }

  onInputChange = (v) => {
    if (v && !_isNaN(parseInt(v)) && parseInt(v) > 0) {
      this.inputVlaue = v;
      this.pickerValue = new moment().add(parseInt(v), 'day').format('YYYY-MM-DD');
    } else {
      this.inputVlaue = '';
    }
  }

  onPickerChange = (v) => {
    this.pickerValue = v;
    this.inputVlaue = moment(v).diff(moment(), 'days') + 1;
  }

  onSelectChange = (v) => {
    this.selectValue = v;
  }

  edit = () => {
    const formParams = this.getFormParams();
    const usbState = formParams.usbstate || '';

    this.formFields && this.formFields.forEach(c => {
      c.items.forEach(field => {
        let domkey = field.domkey[0] || '';
        if ((usbState == '0' && (domkey == 'tokenKey' || domkey == 'serial')) || domkey === 'validatecode') {
          field.viewAttr = 3;
        } else {
          field.viewAttr = 2;
        }
        if (field.conditionType == 'BROWSER') {
          field.browserConditionParam.viewAttr = 2;
        }
        if (domkey === 'classification' && this.isSelef) {
          field.viewAttr = 1;
        }
      });
    });
    this.isEditor = true;
  }

  doSave = () =>{
    if(this.loading) return;
    this.loading = true;
    const formParams = this.form.getFormParams();
    const userUsbType = formParams.userUsbType || '';
    const usbstate = formParams.usbstate || '';
    const tokenKey = formParams.tokenKey || '';
    const hrmId = this.hrmId;
    if (!this.beforeSave()) {
      this.loading = false;
      return false;
    }

    let __this = this;

    if (userUsbType == "3" && usbstate != "1" && tokenKey != "") { //动态令牌
      let params = {};
      params.id = hrmId;
      params.tokenKey = tokenKey;
      WeaTools.callApi('/api/hrm/sysadmin/checkIsUsed', 'POST', params).then((data) => {
        if (data.isUsed) {
          message.warning('令牌序列号已经绑定给' + data.lastname + '，不能重复绑定！');
          this.loading = false;
        } else {
          __this.doAjaxSave();
        }
      })
    } else {
      __this.doAjaxSave();
    }
  }

  RSAEcrypt = (password,password1) => {
    return new Promise( (resolve, reject) => {
      //异步加载ras文件
      loadjs.isDefined('rsa') ? loadjs.ready('rsa', () => {
        if ( this.openRSA &&  this.openRSA == '1') {
          password = __RSAEcrypt__.rsa_data_encrypt(password);
          password1 = __RSAEcrypt__.rsa_data_encrypt(password1);
        }
        resolve({password,password1});
      }) : loadjs(["/js/rsa/jsencrypt.js", "/js/rsa/rsa.js"], 'rsa', {
        async: false,
        success: () => {
          if (this.openRSA && this.openRSA == '1') {
            const callback = () => {
              password = __RSAEcrypt__.rsa_data_encrypt(password);
              password1 = __RSAEcrypt__.rsa_data_encrypt(password1);
              resolve({password, password1});
            }
            __RSAEcrypt__.initRsaCode(callback);
          } else {
            resolve({password, password1});
          }
        }
      });
    })
  }

  doAjaxSave = () => {
    const hrmId = this.hrmId;
    const formParams = this.form.getFormParams();
    let params = {
      needauto: this.checkValue,
      enableDate: this.pickerValue,
      enableUsbType: this.selectValue
    };
    params = { ...{
        id: hrmId
      },
      ...params,
      ...formParams
    };

    let {
      password,
      password1
    } = params;

    this.RSAEcrypt(password,password1).then(data => {
        params = {
          ...params,
          password:data.password,
          password1:data.password1
        }

      const {
        validatecode
      } = formParams;

      if (!validatecode) {
        message.warning(getLabel(386319, '必填字段不完整！'));
        this.loading = false;
        return
      }
      const save = () => {
        API.doSave(params).then((data) => {
          if (data.status == '1') {
            message.success(i18n.message.saveSuccess());
            this.isEditor = false;
            this.getFormField();

            this.form.updateFields({
              validatecode: {
                value: ''
              }
            });
          } else {
            message.warning(data.message);
          }
          this.loading = false;
          this.date = new Date().getTime();
        }, error => {
          message.warning(error.message);
          this.loading = false;
        })
      }
      if (formParams.password === "qwertyuiop") {
        save();
      }else{
        checkWeakPass(params.password,() => {
          save();
        },() =>{
          this.loading = false;
          this.date = new Date().getTime();
        })
      }

    })

  }

  backCard = () => {
    this.form.updateFields({
      validatecode: {
        value: ''
      }
    });
    const hrmId = this.hrmId;
    this.isEditor = false;
    this.getFormField({
      hrmId
    });
  }

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

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

  beforeSave = () => {
    const formParams = this.form.getFormParams();
    const userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    const isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    const isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
    const userUsbType = formParams.userUsbType || '';
    const usbstate = formParams.usbstate || '';
    const serial = formParams.serial || '';
    const tokenKey = formParams.tokenKey || '';
    const loginid = formParams.loginid || '';
    const email = formParams.email || '';
    const needauto = this.checkValue || '';
    const enableDate = this.pickerValue || '';

    let username = "";

    if (userUsbType == 2) {
      if (!isIE) {
        message.warning("您的浏览器不支持修改使用海泰key的账号密码，请使用IE浏览器");
        return false;
      }
      //读取硬件usbkey赋值
      username = PublicFunc.getUserName();
      if (username == '') return false;
    }

    if (usbstate != "1") {
      let flag = true;
      if (userUsbType == "2" && serial == "") {
        flag = false;
      } else if (userUsbType == "3" && tokenKey == "") {
        flag = false;
      }
      if (!flag) {
        message.warning(i18n.message.requireFieldNone());
        return false;
      }
    }

    if (needauto == '1' && enableDate == '') {
      message.warning(i18n.message.requireFieldNone());
      return false;
    }

    if (userUsbType == '3' && tokenKey != "" && (!this.isdigit(tokenKey) || tokenKey.length != 10)) {
      message.warning(getLabel(387344, "令牌序列号必须为10位数字！"));
      return false;
    }



    if (loginid.indexOf(" ") != -1 || loginid.indexOf(";") != -1 || loginid.indexOf("--") != -1 || loginid.indexOf("'") != -1) {
      message.warning(getLabel(387345, "登录名中不能有“空格、分号、--、单引号”字符"));
      return false;
    }

    if ("2" == userUsbType) { //海泰key
      if (loginid != username) {
        message.warning(getLabel(387346, "系统用户名与Key中的不匹配！"));
        return false;
      }
    }
    if (!this.checkPassword()) return false;
    if (!PublicFunc.chkMail(email)) return false;
    return true;
  }

  isdigit = (s) => {
    var r, re;
    re = /\d*/i; //\d表示数字,*表示匹配多个数字
    r = s.match(re);
    return (r == s) ? true : false;
  }

  checkPassword = () => {
    const formParams = this.form.getFormParams();
    let cs = formParams.password || ''; //新密码
    let cs1 = formParams.password1 || ''; //确认密码
    let passwordComplexity = this.settings.passwordComplexity;
    let minpasslen = this.settings.minpasslen;
    let checkpass = true;

    if (cs == '' || cs == "qwertyuiop") return checkpass;

    if (cs.length < minpasslen) {
      message.warning(getLabel(387347, "密码长度不能小于") + minpasslen);
      return false;
    }
    if (cs != cs1) {
      message.warning(getLabel(387351, "密码确认不正确"));
      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;
        }
      }
    }
    return checkpass;
  }

  onPickerHandler = (v) => {
    v = new moment(v).format('YYYY-MM-DD');
    this.getWeekInfo(v);
    this.viewDate = v;
  }

  getFormParams = () => {
    return this.form.getFormParams();
  }

}