// src/mixins/useDictMixin.js
import { getDicts } from '@/api/system/dict/data';

export default {
  methods: {
    async useDict(...args) {
      const res = {};

      for (const dictType of args) {
        let dicts = this.getDictFromStore(dictType);

        if (!dicts) {
          try {
            const response = await getDicts(dictType);
            dicts = response.data.map(p => ({
              label: p.dictLabel,
              value: p.dictValue,
              elTagType: p.listClass,
              elTagClass: p.cssClass
            }));
            res[dictType] = dicts;
            this.setDictToStore(dictType, dicts);
          } catch (err) {
            console.error(`获取字典 ${dictType} 失败`, err);
            res[dictType] = [];
          }
        } else {
          res[dictType] = dicts;
        }
      }

      return res;
    },

    getDictFromStore(key) {
      if (!key) return null;
      const item = this.$store.state.dict.dict.find(item => item.key === key);
      return item ? item.value : null;
    },

    setDictToStore(key, value) {
      this.$store.dispatch('dict/setDict', { key, value }, { root: true });
    }
  }
}