/*
 * @Author: micky
 * @Date: 2024-07-17 17:01:15
 * @LastEditors: micky
 * @LastEditTime: 2024-10-27 16:04:37
 * @FilePath: \chargingpile-uniapp\src\hooks\useDictOptions.ts
 */
import { dictAllDataList } from '@/api/dict'
import { reactive, toRaw } from 'vue'
import cache from '@/utils/cache'
import { DICT_KEY } from '@/enums/appEnums'

// 获取所有的字典数据并缓存起来
export const getAllDict = async () => {
    const { lists } = await dictAllDataList()
    try {
        const dictObj: any = {}
        lists.map((dict: any) => {
            dictObj[dict.dictType] = dict.dictDataVoList.map((dictdata: any) => {
                return {
                    name: dictdata.name,
                    value: dictdata.value
                }
            })
        })
        cache.set(DICT_KEY, dictObj)
    } catch {}
}

interface Options {
    [propName: string]: {
        api: PromiseFun
        params?: Record<string, any>
        transformData?(data: any): any
    }
}

export function useDictOptions<T = any>(options: Options) {
    const optionsData: any = reactive({})
    const optionsKey = Object.keys(options)
    const apiLists = optionsKey.map(key => {
        const value = options[key]
        optionsData[key] = []
        return () => value.api(toRaw(value.params) || {})
    })

    const refresh = async () => {
        const res = await Promise.allSettled<Promise<any>>(apiLists.map(api => api()))
        res.forEach((item, index) => {
            const key = optionsKey[index]

            if (item.status == 'fulfilled') {
                const { transformData } = options[key]
                const data = transformData ? transformData(item.value) : item.value
                optionsData[key] = data
            }
        })
    }
    refresh()
    return {
        optionsData: optionsData as T,
        refresh
    }
}

let allDict = cache.get(DICT_KEY)
// 获取字典数据
export function useDictData(dict: string[]) {
    if (!allDict) allDict = cache.get(DICT_KEY)
    const optionsData: Options = {}
    for (const type of dict) {
        optionsData[type] = allDict?.[type] || []
    }
    return {
        dictData: optionsData
    }
}

// 根据字典值获取字典名称
export function getDictName(arr: any[], key: string | number) {
    if (!arr) return
    const obj = arr.find(i => i.value == key)
    if (obj) return obj.name
    else return '--'
}
