import commonDeclare from "./commonDeclare"
import commonApi from "./commonApi"
import Utils from "~/utils"
import _ from "~/utils/Lodash.js";

export default {
  mixins: [commonApi, commonDeclare],
  data: function () {
    return {
      // 弹框回填
      promptData: {
        title: '',
        columnStr: '',
        data: [],
        rulePath: ''
      }
    }
  },
  created() {
  },
  mounted() {
    if (!this.isInDisplay) {
      this.ruleCheck()
    }
  },
  methods: {
    /**
     * 表单校验 rules 的赋值
     * @returns void
     */
    ruleCheck() {
      if (!this.pattern)
        return
      // const keySet = new Set(Object.keys(this.pattern).concat(Object.keys(this.checkRules).concat(Object.keys(this.defaultRules))))
      const keySet = new Set(Object.keys(this.pattern).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]){
        //   if (Array.isArray(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
        //       })
        //     }
        //   } else {
        //     rule.push({
        //       validator: that.checkRules[key].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;
    },
    /**
     * 触发方式
     * @param {String} prop item属性
     * @returns 
     */
    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";
    },
    /**
     * Tabs切换事件
     * @param {VM} tab 
     */
    tabClick(tab) {
      if (this.isInDisplay) {
        return
      }
      const name = tab.name
      let rulePath;
      if (name === "setpan") {
        rulePath = "setmod.setpan";
      }
      if (name === "glepan") {
        rulePath = "setmod.glemod.glepan";
      }
      if (name === "docpan") {
        rulePath = "trnmod.trndoc.docpan"
      }
      if (name === "doctre") {
        rulePath = "trnmod.trndoc.doctre"
      }
      if (name === "engp") {
        rulePath = "liaall.engp"
      }
      if (name === "limitbody") {
        rulePath = "liaall.limmod.limitbody"
      }
      if (name === "ccvpan") {
        rulePath = "liaall.liaccv.ccvpan"
      }
      if (!!rulePath) {
        this.executeRule(rulePath).then(res => {
          if (res.respCode == SUCCESS) {
            this.updateModel(res.data)
          }
        })
      }
    },
    /**
     * 以函数形式获取model（请求参数），保证取到的是最新赋值的
     * @param {any} params 参数
     * @returns 
     */
    wrapper(params) {
      params = params || {}
      const fn = async () => {
        const that = this;
        const data = await new Promise(resolve => {
          // 保证前一次请求结果赋值VO完成
          setTimeout(() => {
            const d = Utils.flatObject(that.model)
            resolve(d)
          }, 0)
        })
        return { ...data, params }
      }
      return fn;
    },
    /**
     * 用于手动的触发model里属性的 executeDefault 
     * @param {string} rule 执行的 rule path
     * @param {any} value   更改的值
     */
    defaultFunction(rule, value) {
      Utils.defaultFunction.call(this, rule, value)
    },
    /**
     * 更新Model
     * @param {any} data model数据
     */
    updateModel(data) {
      Utils.copyValueFromVO(this.model, data);
    },
    /**
     * 弹出机构选择框
     * @param {String} rulePath 
     * @param {String} columns 自定义需要展示列
     * @param {String} shadow 自定义列后需要保留的影藏字段
     * @param {String} modelUrl 非机构双击后需要回填的字段路劲,k:对应列，value:应用model路劲,如{TXT:'ledgrp.blk.lcrgod'}
     * @param {String} isCover 非机构双击后需要回填的字段值是覆盖还是叠加，部分覆盖值为对象，false为叠加，如{TXT:false}，k值为modelUrl的k，如全部覆盖则isCover='T',如全部叠加则isCover='',默认全部覆盖
     */
    showGridPromptDialog(rulePath, columns, shadow, modelUrl, isCover = "T") {
      this.executeRule(rulePath).then((res) => {
        if (res.respCode = SUCCESS) {
          if (res.data.params) {
            Utils.copyValueFromVO(this.model, res.data);
          } else {
            this.root.$refs.etyDialog.show = true
            this.root.promptData = {
              title: res.data.title,
              columnStr: columns ? columns : res.data.columns,
              shadow: shadow,
              data: res.data.vals.rows,
              rulePath: rulePath,
              modelUrl: modelUrl,
              isCover: isCover,
            }
          }
        }
      })
    },
    /**
     * 机构回填
     * @param {String} val 选种行的值（一般是首列）
     * @param {String} rulePath 路径
     */
    selectEty(val, rulePath) {
      const props = rulePath.replaceAll(".", "_")
      const obj = {}
      obj[props] = val;
      Utils.copyValueFromVO(this.model, obj);
      this.executeRule(rulePath).then((res) => {
        if (res.respCode = SUCCESS) {
          Utils.copyValueFromVO(this.model, res.data);
        }
      });
    },

    /**
        * 货物条款等非机构栏位回填
        * @param {Object} val 选种行的值
        * @param {Object} url 字段路劲 需要回填的字段路劲
        *  @param {Object} url 对应字段值是否覆盖 ，需要为true,否则合并叠加
        * @param {String} rulePath 路径
        */
    selectMsg(val, modelUrl, isCover, rulePath) {
      for (let k in val) {
        let msg = val[k]
        if ((typeof isCover === 'string' && isCover === '') || !isCover[k]) {
          let ms = _.get(this.model, modelUrl[k], '')
          msg = (ms ? ms + '\r\n' : '') + msg
        }
        _.set(this.model, modelUrl[k], msg);
      }
    },
    /**
     * 改变表单项的是否必填属性
     * @param {String} property 属性
     * @param {Boolean} required 是否必填
     */
    changeFormItemRequired(property, required) {
      this.pattern[property][0].required = required
    },
    /**
     * 在 A 交易中打开 B 交易视图（详情、开立...）。
     * 
     * 路由视图跳转，例：
     *    this.gotoView("Ditopn", {inr: "001021021"}, {name: "lisi"})   实际请求的 url 为 /business/ditopn/001021021?name=lisi
     *    params, query按需传入（得提前配置好 Router ），在对应的vue页面做好处理
     * @param {String} name 路由的name
     * @param {Object} params 路由的params
     * @param {Object} query 路由的query
     */
    gotoView(name, params, query) {
      params = params || {}
      query = query || {}
      this.$router.push({ name, params, query })
    },
    gotoUrl(url) {
      this.$router.push(url)
    }
  },
  computed: {
    isInDisplay() {
      return this.$store.state.Status.mode === 'display'
    }
  }
}