/*
 * 校验扩展
 * this.validator = new ValidatorUtils({
      rules: this.rules,
      data: this.formData })
    this.formData = this.validator.Data
 */
import AsyncValidator from 'async-validator'
import _ from 'lodash'

function isDate(v,dateFormat){
	var MONTH = "MM";
    var DAY = "dd";
    var YEAR = "yyyy";
    var regex = '^'+ dateFormat.replace(YEAR,'\\d{4}').replace(MONTH,'\\d{2}').replace(DAY,'\\d{2}')+'$';
    if(!new RegExp(regex).test(v)) return false;

    var year = v.substr(dateFormat.indexOf(YEAR),4);
    var month = v.substr(dateFormat.indexOf(MONTH),2);
    var day = v.substr(dateFormat.indexOf(DAY),2);

    var d = new Date(format('%s/%s/%s',[year,month,day]));
    return ( parseInt(month, 10) == (1+d.getMonth()) ) &&
        (parseInt(day, 10) == d.getDate()) &&
        (parseInt(year, 10) == d.getFullYear() );
}

function format(str,args) {
  args = args || [];
  var result = str;
  for (var i = 0; i < args.length; i++){
      result = result.replace(/%s/, args[i]);
  }
  return result;
} 

function isIdcard(v){
  if(!(/^\d{17}(\d|x)$/i.test(v) || /^\d{15}$/i.test(v))) return false;
  var provinceCode = parseInt(v.substr(0,2));
  if((provinceCode < 11) || (provinceCode > 91)) return false;
  var forTestDate = v.length == 18 ? v : v.substr(0,6)+"19"+v.substr(6,15);
  var birthday = forTestDate.substr(6,8);
  if(!isDate(birthday,'yyyyMMdd')) return false;
  // if(v.length == 18) {
  //     v = v.replace(/x$/i,"a");
  //     var verifyCode = 0;
  //     for(var i = 17;i >= 0;i--)
  //         verifyCode += (Math.pow(2,i) % 11) * parseInt(v.charAt(17 - i),11);
  //     if(verifyCode % 11 != 1) return false;
  // }
  return true;
}
export {
  isIdcard
}


/**
 * 校验辅助类
 *
 * @export
 * @class ValidatorUtils
 */
export default class ValidatorUtils {
  /**
   * Creates an instance of ValidatorUtils.
   * @param {Object} rules
   * @param {Object} data
   * @param {Object} errMsg 错误信息文本key 同data
   * @param {Boolean} automatic 自动校验
   *
   * @memberOf ValidatorUtils
   */
  constructor({ rules, data, errMsg = {}, automatic = false }) {
    this.setRules(rules)
    this.data = data
    this.errMsg = errMsg
    automatic && this.setProxyValidate()
  }
  // #region 属性
  get Rules() {
    return this.rules
  }
  set Data(value) {
    this.data = value
  }
  get Data() {
    return this.data
  }
  get Validators() {
    return this.validators
  }
  set Validators(value) {
    this.validators = value
  }
  set ErrMsg(value) {
    this.errMsg = this.value
  }
  get ErrMsg() {
    return this.errMsg
  }
  // #endregion

  /**
   * 自动校验代理设置
   *
   * @returns
   *
   * @memberOf ValidatorUtils
   */
  setProxyValidate() {
    let that = this
    let p = {
      set(target, key, value, receiver) {
        target[key] = value
        that
          .validate(key)
          .then(result => {})
          .catch(() => {})
        return true
      }
    }
    this.data = new Proxy(this.data, p)
  }

  /**
   * 设定规则
   * @param rules rules object async-validator rules
   * @param cover 是否替换旧规则
   */
  setRules(rules, cover = true) {
    !cover || (this.Validators = {})
    _(rules)
      .mapKeys(
        (value, key) =>
          (this.Validators[key] = new AsyncValidator({ [key]: value }))
      )
      .value()
  }

  /**
   * 执行验证
   *
   * @param {String,Array} tempData 可选 传空将验证构造data 支持key，list<key>
   * @returns Promise
   *
   * @memberOf ValidatorUtils
   */
  validate(tempData) {
    // 错误数组
    const err = []
    let tempdata = _(this.Validators)
      .keys()
      .filter(
        p =>
          !tempData ||
          (tempData &&
            ((_.isString(tempData) && tempData === p) ||
              (_.isArray(tempData) && tempData.indexOf(p) > -1)))
      )
      .value()
    let promises = []  
    tempdata.forEach(p =>
      {
        let promise = new Promise((resolve, reject) => {
            this.Validators[p].validate({ [p]: this.Data[p] }, error => {
                error && err.push(error[0])
                this.setErrMsg(p, error)
                resolve()
            })
        })
        promises.push(promise)
      }
    )
    
    return Promise.all(promises).then(() => {
        if (err.length > 0) {
            return Promise.reject(err)
        }
        else return Promise.resolve(tempData)
    })
    
  }
  /**
   *
   * 设置error消息
   * @param {any} error
   *
   * @memberOf ValidatorUtils
   */
  setErrMsg(key, error) {
    this.errMsg[key] = error ? error[0].message : undefined
  }
}