import Rule from './rule'
import { isFunction, isRegExp } from './index'
import fyForm from '@/util/fy'

/**
 * @des 路由参数校验
 */
class Param {
  constructor (params) {
    this.params = params
    this.error = ''
  }

  checkParams () {
    let params = this.params

    for (let i in params) {
      if (!this._validate(i, params[i])) {
        return false
      }
    }

    return true
  }

  _validate (key, rules) {
    for (var i = 1; i < rules.length; i++) {
      if (!this._validateType(key, rules[0], rules[i])) {
        return false
      }
    }

    return true
  }

  _validateType (type, val, rule) {
    if (rule === 'require') return this._execRequire(type, val)
    else if (isFunction(rule)) return rule(val)
    else if (isRegExp(rule)) return this._execReg(type, val, rule)
    else if(/^length_[0-9]{1,}-[0-9]{1,}$/) return this._execLength(type, val, rule)
    else return true
  }
  /**
     * 验证是否为空
     * @param {string} type key
     * @param {any} val     val
     */
  _execRequire (type, val) {
    let flag = Rule.Reg_Require.test(val)
    if (!flag) this.error = `${fyForm[type] || type}不能为空`
    return flag
  }
  /**
     *
     * @param {string} type  key
     * @param {any} val      val
     * @param {RegExp} rule  正则表达式
     */
  _execReg (type, val, rule) {
    let flag = rule.test(val)
    if (!flag) this.error = `${fyForm[type] || type}格式不对`
    return flag
  }

  _execLength (type, val, rule) {
    let range = (rule.replace('length_','')).split("-")
    if(val.length>=range[0] && val.length<=range[1]){
      return true
    }else{
      this.error = `${fyForm[type] || type}长度在${range[0]}-${range[1]}之间`
      return false
    }
  }
}

export default Param
