import { defineStore } from 'pinia';
import { Notify } from 'quasar';

import { dictDataApi } from 'src/api/dict/dictDataApi';
import { ref } from 'vue';

export const useDictStore = defineStore('dict', {
  state: () => ({
    dict: new Map() as Map<string, Map<string, string>>,
    lock: false
  }),

  actions: {
    getDictMap(dictType: string) {
      //判断是否存在字典缓存
      const dictMap = this.dict.get(dictType);
      if (dictMap && dictMap.size >= 0) {
        return;
      }

      //若不存在则从后台获取字典数据
      dictDataApi.getList(dictType).then((res) => {
        if (res && res != '{}') {
          this.dict.set(dictType, new Map(Object.entries(res)));
          // console.log('数据完全加载完成');
        } else {
          Notify.create({
            progress: true,
            type: 'negative',
            position: 'top',
            message: '字典获取错误'
          });
        }
      });
    },

    removeDictMap(dictType: string) {
      this.dict.delete(dictType);
    },

    getDict(type: string, data: string) {
      // console.log(data);
      return ref(this.dict.get(type)?.get(data)).value;
    }
  }
});
