import request from "./axios";
import store from "../store";

/**
 * 封装字典工具类
 */
const $dict = {
  vueStore: null,
  url: "/admin/dictionary/queryValsByCodeList",
  setUrl(v) {
    this.url = v
  },
  load(...code) {
    if (!this.vueStore) this.vueStore = store
    return request.post(this.url, null, {
      params: {
        codeList: code.join(',')
      }
    }).then((res) => {
      this.vueStore.commit("setDicts", res.data)
    })
  },
  getDict(key) {
    let dict = this.vueStore.getters.getDict(key)
    return dict ? dict.values : []
  },
  getValue(key, label) {
    let dict = this.vueStore.getters.getDict(key)
    if (dict) {
      let item = dict.values.find(v => v.dictName == label)
      return item ? item.dictValue : label
    } else return label
  },
  getLabel(key, value) {
    let dict = this.vueStore.getters.getDict(key)
    if (dict) {
      let item = dict.values.find(v => v.dictValue == value)
      return item ? item.dictName : value
    } else return value
  },
  getColor(key, value) {
    let dict = this.vueStore.getters.getDict(key)
    if (dict) {
      let item = dict.values.find(v => v.dictValue == value)
      return item ? item.dictColor : value
    } else return value
  },
}

export default $dict
