import { CACHE_KEY, useCache } from '@/hooks/web/useCache';
import type { DictDataVO } from '@/services/system/dict/dict.data';
import { getSimpleDictDataList } from '@/services/system/dict/dict.data';

export interface DictValueType {
  value: any;
  label: string;
  clorType?: string;
  cssClass?: string;
}

export interface DictTypeType {
  dictType: string;
  dictValue: DictValueType[];
}

export interface DictState {
  dictMap: Record<string, any[]>;
  isSetDict: boolean;
}

export const useDictStore = () => {
  const { wsCache } = useCache();
  const state: DictState = {
    dictMap: {},
    isSetDict: false,
  };

  const getDictMap = (): Recordable => {
    const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE);
    if (dictMap) {
      state.dictMap = dictMap;
    }
    return state.dictMap;
  };

  const getIsSetDict = (): boolean => {
    return state.isSetDict;
  };

  const setDictMap = async () => {
    const dictMap = wsCache.get(CACHE_KEY.DICT_CACHE);
    if (dictMap) {
      state.dictMap = dictMap;
      state.isSetDict = true;
    } else {
      const res = await getSimpleDictDataList();
      // 设置数据
      const dictDataMap: Record<string, any[]> = {};

      res.forEach((dictData: DictDataVO) => {
        // 获得 dictType 层级
        if (!dictDataMap[dictData.dictType]) {
          dictDataMap[dictData.dictType] = [];
        }

        // 处理 dictValue 层级
        dictDataMap[dictData.dictType].push({
          value: dictData.value,
          label: dictData.label,
          colorType: dictData.colorType,
          cssClass: dictData.cssClass,
        });
      });
      state.dictMap = dictDataMap;
      state.isSetDict = true;
      wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 }); // 60 秒 过期
    }
  };

  const getDictByType = (type: string) => {
    if (!state.isSetDict) {
      setDictMap();
    }
    return state.dictMap[type];
  };

  const resetDict = async () => {
    wsCache.delete(CACHE_KEY.DICT_CACHE);
    const res = await getSimpleDictDataList();
    // 设置数据
    const dictDataMap: Record<string, any[]> = {};

    res.forEach((dictData: DictDataVO) => {
      // 获得 dictType 层级
      if (!dictDataMap[dictData.dictType]) {
        dictDataMap[dictData.dictType] = [];
      }

      // 处理 dictValue 层级
      dictDataMap[dictData.dictType].push({
        value: dictData.value,
        label: dictData.label,
        colorType: dictData.colorType,
        cssClass: dictData.cssClass,
      });
    });
    state.dictMap = dictDataMap;
    state.isSetDict = true;
    wsCache.set(CACHE_KEY.DICT_CACHE, dictDataMap, { exp: 60 }); // 60 秒 过期
  };

  return {
    state,
    getDictMap,
    getIsSetDict,
    setDictMap,
    getDictByType,
    resetDict,
  };
};
