import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDictionaryItemListByDicID, getDictionaryList } from '@/service/api/dictionary'

export const useBusinessStore = defineStore('business-store', () => {
  const dictList = ref<Api.Dictionary.DictionaryItem[]>([])
  const dictData = ref<Record<string, Api.Dictionary.DictionaryUIItem[]>>({})
  const isInitialized = ref(false)
  const loadingMap = ref<Record<string, boolean>>({})

  /** 初始化字典 */
  async function initDict() {
    if (isInitialized.value)
      return
    const { data: res, error } = await getDictionaryList()
    if (!error && res) {
      dictList.value = res.data || []
      isInitialized.value = true
    }
  }

  /** 获取字典数据 */
  async function getDict(key: string) {
    // 已经加载过，直接返回
    if (dictData.value[key] && dictData.value[key].length > 0)
      return dictData.value[key]

    if (loadingMap.value[key]) {
      return []
    }

    loadingMap.value[key] = true
    try {
      const { data: res, error } = await getDictionaryItemListByDicID(key)
      if (!error && res) {
        const list = res.data || []
        // 使用新对象赋值，确保触发响应式更新
        dictData.value = {
          ...dictData.value,
          [key]: list,
        }
      }
    }
    finally {
      loadingMap.value[key] = false
    }
    // eslint-disable-next-line no-console
    console.log(`获取字典数据 ${key}`, dictData.value[key])
    return dictData.value[key]
  }

  return {
    dictList,
    dictData,
    loadingMap,
    initDict,
    getDict,
  }
})
