// utils/dict.ts
import { getDicts } from '@/apis/system/dictData'

// 字典缓存
const dictCache = new Map<string, any[]>()

/**
 * 获取字典数据
 */
export const getDict = async (dictType: string): Promise<any[]> => {
  // 先从缓存中获取
  if (dictCache.has(dictType)) {
    return dictCache.get(dictType)!
  }
  try {
    const response = await getDicts(dictType)
    const dictData: any[] = Array.isArray(response.data) ? response.data : []
    // // 缓存字典数据
    dictCache.set(dictType, dictData)
    return dictData
  } catch (error) {
    console.error(`获取字典 ${dictType} 失败:`, error)
    return []
  }
}

/**
 * 清除字典缓存
 */
export const clearDictCache = (dictType?: string) => {
  if (dictType) {
    dictCache.delete(dictType)
  } else {
    dictCache.clear()
  }
}

/**
 * 预加载多个字典
 */
export const preloadDicts = async (dictTypes: string[]) => {
  const promises = dictTypes.map(type => getDict(type))
  await Promise.all(promises)
}
