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

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

  },
  actions: {
    async loadDicts(dictNames: string[]) {
      if (!dictNames.length) {
        return Promise.resolve(true);
      }
      for (const dictName of dictNames) {
        if (this.dicts[dictName]) {
          continue;
        }
        this.dicts[dictName] = [];
      }
      const name = dictNames.join(',');
      const { data } = await getDictData(name);
      for (const dictName in data) {
        this.dicts[dictName].push(...data[dictName]);
      }
      return await Promise.resolve(true);
    },
    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 = {};
    }
  }
});