import useDictStore from '@/store/modules/dict'
import { getDicts } from '@/api/system/dict/data'
import { getMoreDicts } from '@/api/common'

/**
 * 获取字典数据
 */
export function useDict(...args) {
  const res = ref({})
  return (() => {
    args.forEach((dictType, index) => {
      res.value[dictType] = []
      const dicts = useDictStore().getDict(dictType)
      // if (dicts) {
      //   res.value[dictType] = dicts
      // } else {
      //   getDicts(dictType).then(resp => {
      //     res.value[dictType] = resp.data.map(p => ({ label: p.itemLabel, value: p.itemValue }))
      //     useDictStore().setDict(dictType, res.value[dictType])
      //   })
      // }
      getDicts(dictType).then(resp => {
        res.value[dictType] = resp.data.map(p => ({ label: p.itemLabel, value: p.itemValue }))
        useDictStore().setDict(dictType, res.value[dictType])
      })
    })
    return toRefs(res.value)
  })()
}
/**
 * 获取多个字典数据
 */
export function useDictLists(typeLists) {
  let params = { typeList: typeLists }
  console.log(params)
  let dictArray = []
  return (() => {
    getMoreDicts(params).then(resp => {
      if (resp.code === 200) {
        dictArray = resp.data.map(item => {
          item.dictItemList.forEach(dict => {
            dict.label = dict.itemLabel
            if (item.dictType == 'sys_no_yes') {
              dict.value = Number(dict.itemValue)
            } else {
              dict.value = dict.itemValue
            }
          })
          return item
        })
        useDictStore().setDictTypeLists(dictArray)
      }
    })
  })()
}
/**
 * 获取多个字典数据  返回promise
 */
export function useDictLists1(typeLists) {
  const params = { typeList: typeLists }
  console.log(params)

  // 返回 Promise，以便调用方可以 await
  return getMoreDicts(params).then(resp => {
    if (resp.code === 200) {
      const dictArray = resp.data.map(item => {
        item.dictItemList.forEach(dict => {
          dict.label = dict.itemLabel
          if (item.dictType === 'sys_no_yes') {
            dict.value = Number(dict.itemValue)
          } else {
            dict.value = dict.itemValue
          }
        })
        return item
      })
      useDictStore().setDictTypeLists(dictArray)
      return dictArray // 可选：返回数据供后续使用
    } else {
      // 可选：抛出错误便于 catch
      throw new Error('获取字典数据失败')
    }
  })
}


