import Vue from "vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  computed: {
    systemCodeRule() {
      // 系统编码规则
      return this.$store.state.app.systemCodeRule || {};
    },
  },
  methods: {
    /**
     * Vue observable
     * @param property
     * @param args
     * @returns {T}
     */
    $observable(property, ...args) {
      const key = `${this._uid}-${property}-observable`;
      if (!this[key]) {
        this[key] = Vue.observable.apply(null, args);
      }
      return this[key];
    },
    /**
     * 获取数据对象中 某一个对象 的 某一个属性值
     * @param array 数组对象
     * @param value 属性对应值
     * @param compareAttribute 哪个属性
     * @param attribute 想要的属性
     * @returns {string} 属性值
     */
    getAttrValue(
      array,
      value,
      compareAttribute = "value",
      attribute = "label"
    ) {
      const itemList = Array.isArray(array) ? array : [];
      const find = itemList.find((item) => {
        let attrValue = item[compareAttribute];
        let compareValue = value;
        if (typeof attrValue === "number") {
          attrValue += "";
        }
        if (typeof compareValue === "number") {
          compareValue += "";
        }
        return attrValue === compareValue;
      });
      if (find) {
        return find[attribute] || "";
      }
      return "";
    },
    /**
     * 获取数据字典
     * @param dictCode
     * @param options
     * @returns {*}
     */
    getDictByCode(dictCode, options = {}) {
      return this.$axios.get(
        `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/${dictCode}`,
        {
          params: { enableFlag: "Y", ...options },
        }
      );
    },
    validateLengthMsg(min, max) {
      return this.$t("LENGTH_LIMIT_ERROR")
        .replace("{}", min)
        .replace("{}", max);
    },
    validateFieldLength(min, max) {
      return {
        min,
        max,
        message: this.validateLengthMsg(min, max),
        trigger: "blur",
      };
    },
    isJSON(str) {
      if (typeof str === "string") {
        try {
          const js = str
            .replace(/\n/g, "")
            .replace(/\r/g, "")
            .replace(/\s|\xA0/g, "");
          const obj = JSON.parse(js);
          if (typeof obj === "object" && obj) {
            return true;
          }
          return false;
        } catch (e) {
          return false;
        }
      }
      return false;
    },
    ifJSON(str) {
      const js = str
        .replace(/\n/g, "")
        .replace(/\r/g, "")
        .replace(/\s|\xA0/g, "");
      const a = /^{.*}$/;
      const b = /^\[.*\]$/;
      if (a.test(js) || b.test(js)) {
        return this.isJSON(js);
      }
      return false;
    },
  },
};
