import { defineStore } from 'pinia';
import { getDictData } from '@/api/modules/system';
import { DictItem, DictStoreState } from '@/types';
import _ from 'lodash';

export const useDictStore = defineStore('ie-dict', {
  state: (): DictStoreState => {
    return {
      dicts: {}
    }
  },
  getters: {

  },
  actions: {
    async loadDicts(dictNames: string[]) {
      if (!dictNames.length) return
      // 已有的字段不需要重新加载
      const newDictNames = _.difference(dictNames, _.keys(this.dicts))
      if (!newDictNames.length) return
      // 并发时可能会重复请求，但多请求比不请求好
      const name = newDictNames.join(',');
      const { data } = await getDictData(name);
      for (const dictName in data) {
        this.dicts[dictName] = data[dictName];
      }
    },
    async loadDict(dictName: string) {
      if (this.dicts[dictName]) {
        return Promise.resolve(true);
      }
      return await this.loadDicts([dictName]);
    },
    getDictLabel(dictName: string, value: string | number) {
      if (!value) {
        return value;
      }
      const dict = this.dicts[dictName];
      if (!dict) {
        this.loadDicts([dictName]);
        return value;
      }
      return dict.find((item) => item.dictValue === value)?.dictLabel || value;
    },
    getDictValue(dictName: string, value: string | number) {
      if (!value) {
        return value;
      }
      const dict = this.dicts[dictName];
      return dict.find((item) => item.dictValue === value)?.dictValue || value;
    },
    getDictValues(dictName: string) {
      if (!this.dicts[dictName]) {
        this.loadDicts([dictName]);
      }
      return this.dicts[dictName] || [];
    },
    clear() {
      this.dicts = {};
    }
  }
});