// composables/useDict.ts
import { ref, onMounted } from 'vue'
import { getDict, preloadDicts, clearDictCache } from '@/utils/dict'

/**
 * 字典组合式函数
 */
export function useDict() {
  const dict = ref<Record<string, any[]>>({})

  /**
   * 加载字典数据
   */
  const loadDict = async (dictType: string): Promise<any[]> => {
    const data = await getDict(dictType)
    dict.value[dictType] = data
    return data
  }

  /**
   * 批量加载字典
   */
  const loadDicts = async (dictTypes: string[]) => {
    await preloadDicts(dictTypes)
    for (const type of dictTypes) {
      dict.value[type] = await getDict(type)
    }
  }

  /**
   * 获取字典数据（如果已加载则直接返回，否则加载）
   */
  const getDictData = (dictType: string): any[] => {
    return dict.value[dictType] || []
  }

  /**
   * 清除字典缓存
   */
  const clearDict = (dictType?: string) => {
    clearDictCache(dictType)
    if (dictType) {
      delete dict.value[dictType]
    } else {
      dict.value = {}
    }
  }

  return {
    dict,
    loadDict,
    loadDicts,
    getDictData,
    clearDict
  }
}

/**
 * 快速使用字典的简写函数
 */
export function useDictType(...dictTypes: string[]) {
  const { dict, loadDicts } = useDict()

  onMounted(async () => {
    await loadDicts(dictTypes)
  })

  return {
    dict
  }
}
