import _ from "lodash"
import commonDeclare from "./commonDeclare"
import commonApi from "./commonApi"
export default {
  mixins: [commonApi,commonDeclare],
  data: function () {
    return {
      defFlag:true
    }
  },
  created() {
  },
  mounted() {
    if(!this.isInDisplay){
      // this.ruleWatcher()
      this.ruleCheck()
    }
  },
  methods: {
    openWatch(flag){
      this.defFlag = !!flag
    },
    ruleWatcher() {
      if(!this.defaultRules)
        return
      const that = this;
      Object.keys(that.defaultRules).forEach(key => {
        let func = function(){
          if(that.defFlag){
            that.defaultRules[key].apply(that)
          }
        }
        that.$watch("model." + key, _.debounce(func, 1000))
      })
    },
    ruleCheck() {
      if(!this.pattern)
        return
      const keySet = new Set(Object.keys(this.pattern).concat(Object.keys(this.checkRules).concat(Object.keys(this.defaultRules))))
      const res = {};
      const that = this;
      for (let key of keySet.keys()) {
        const rule = []
        if(that.pattern[key]){
          rule.push(...that.pattern[key])
        }
        const triggerType = that.getTriggerType(key)
        if(that.checkRules[key]){
          for (let j = 0; j < that.checkRules[key].length; j++) {
            const check = that.checkRules[key][j];
            rule.push({
              validator: check.bind(that),
              trigger: triggerType
            })
          }
        }
        if (that.defaultRules[key]) {
          rule.push({
            validator: that.defaultRules[key].bind(that),
            trigger: triggerType
          })
        }
        if(rule.length > 0) {
          res[key] = rule;
        }
      }
      that.rules = res;
    },
    getTriggerType(prop) {
      const fields = this.$refs.modelForm.fields;
      for (let i = 0; i < fields.length; i++) {
        const field = fields[i];
        if (field.prop === prop) {
          // select、checkbox使用change触发
          if (field.$children[1].$children[0].$el.className.startsWith("el-select") || field.$children[1].$children[0].$el.className.startsWith("el-checkbox")) {
            return "change";
          }
          return "blur";
        }
      }
      return "blur";
    }
  },
  computed:{
    isInDisplay(){
      return this.$store.state.Status.mode === 'display'
    }
  }
}