import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDictTree, buildDictOptions } from '../api/dict'

export const useDictStore = defineStore('dict', () => {
  const maps = ref<Record<string, Record<string, string>>>({})

  async function loadDict(type: string) {
    if (maps.value[type]) return
    try {
      const data = await getDictTree(type)
      const opts = buildDictOptions(data)
      maps.value[type] = opts.labelMap
    } catch {
      maps.value[type] = {}
    }
  }

  function getLabel(type: string, value: string): string {
    return maps.value[type]?.[value] || value
  }

  /** 加载任务/项目展示常用的字典映射 */
  async function loadCommonDicts() {
    await Promise.all([
      loadDict('facility_type'),
      loadDict('construction_facility'),
      loadDict('construction_type'),
      loadDict('service_method'),
      loadDict('suggested_vehicle'),
      loadDict('water_distance'),
      loadDict('acceptance_method'),
    ])
  }

  return {
    maps,
    loadDict,
    loadCommonDicts,
    getLabel,
  }
})
