import { defineStore } from 'pinia'
import { store } from '/@/store'
import { Storage } from '@/utils/storage'
import * as UserInfoAPI from '@/api/model/userInfo'

interface dictItem {
    color: string
    jsonObject?: string
    label: string
    text: string
    title: string
    value: string | number
}
// 定义字典列表的类型
export interface DictListVO {
    [key: string]: dictItem[]
}
export const useDictStore = defineStore({
    id: 'dict',
    state: () => ({
        dictList: {} as DictListVO,
    }),
    getters: {
        getDictList(): DictListVO {
            if (Object.keys(this.dictList).length === 0) {
                this.dictList = JSON.parse(Storage.get('dictList'))
            }
            return this.dictList
        },
        // 获取指定类型的字典项（同步方法，需要先确保数据已加载）
        getDictByType:
            (state) =>
            (type: string): dictItem[] => {
                return state.dictList[type] || []
            },
    },
    actions: {
        async setDictList() {
            if (Object.keys(this.dictList).length === 0) {
                try {
                    const res = await UserInfoAPI.dictList()
                    this.dictList = res as DictListVO
                    Storage.set('dictList', JSON.stringify(this.dictList))
                } catch (error) {
                    console.log('获取字典列表失败', error)
                }
            }
        },
        /**
         * 清空字典数据
         */
        clearDict(): void {
            this.dictList = {}
            Storage.remove('dictList')
        },
    },
})

// Need to be used outside the setup
export function useAppStoreWithOut() {
    return useDictStore(store)
}
