import { ref, type Ref } from 'vue'
import { getDictTree, buildDictOptions, type DictOptions } from '@/api/dict'

interface UseDictOptionsReturn {
  options: Ref<DictOptions>
  loading: Ref<boolean>
  load: () => Promise<void>
}

/**
 * 通用字典选项加载 hook
 * @param dictType 字典类型，如 construction_type / construction_facility
 * @param fallback 字典接口失败时的兜底选项
 */
export function useDictOptions(
  dictType: string,
  fallback: { value: string; label: string }[] = []
): UseDictOptionsReturn {
  const options = ref<DictOptions>({
    options: fallback,
    labelMap: fallback.reduce<Record<string, string>>((acc, item) => {
      acc[item.value] = item.label
      return acc
    }, {}),
    colorMap: {},
    data: []
  })
  const loading = ref(false)

  async function load() {
    if (loading.value) return
    loading.value = true
    try {
      const data = await getDictTree(dictType)
      const opts = buildDictOptions(data)
      if (opts.options.length > 0) {
        options.value = opts
      }
    } catch {
      // 失败时保持兜底
    } finally {
      loading.value = false
    }
  }

  return { options, loading, load }
}

/**
 * 批量加载多个字典类型
 * @param dictTypes 字典类型数组
 * @returns 每个类型对应的 DictOptions ref 对象
 */
export function useMultipleDictOptions(
  dictTypes: string[]
): Record<string, UseDictOptionsReturn> {
  return dictTypes.reduce<Record<string, UseDictOptionsReturn>>((acc, type) => {
    acc[type] = useDictOptions(type)
    return acc
  }, {})
}
