import { ref } from 'vue'
import { defineStore } from 'pinia'
import { customStorage } from '../persist'
import systemApi from '@/api/system'

export const useDictionaryStore = defineStore(
	'dictionary',
	() => {
		// 字典数据缓存（按 code 缓存字典项列表）
		const dictionaries = ref({})
		// 字典元数据缓存（按 code 缓存字典信息）
		const dictionaryMeta = ref({})
		// 字典ID到Code的映射（用于通过ID清除缓存）
		const dictionaryIdToCodeMap = ref({})
		// 字典数据加载状态
		const loading = ref(false)
		// 最后加载时间
		const lastLoadTime = ref(null)

		/**
		 * 加载所有字典数据
		 */
		async function loadAllDictionaries(forceRefresh = false) {
			// 如果已加载且不是强制刷新，直接返回
			if (!forceRefresh && Object.keys(dictionaries.value).length > 0) {
				return
			}

			if (loading.value) return

			loading.value = true
			try {
				const res = await systemApi.dictionaryItem.all.get()
				if (res.code === 200 && res.data) {
					// 将字典数据按 code 缓存
					const dictMap = {}
					const metaMap = {}

					res.data.forEach((dict) => {
						if (dict.code) {
							// 缓存字典项列表
							dictMap[dict.code] = dict.items || []
							// 缓存字典元数据（包含id以便通过id清除缓存）
							metaMap[dict.code] = {
								id: dict.code, // 使用code作为唯一标识
								name: dict.name,
								code: dict.code,
								description: dict.description,
							}
						}
					})

					dictionaries.value = dictMap
					dictionaryMeta.value = metaMap
					lastLoadTime.value = new Date().getTime()
				}
			} catch (error) {
				console.error('加载字典数据失败:', error)
			} finally {
				loading.value = false
			}
		}

		/**
		 * 根据字典 code 获取字典数据
		 * @param {string} code 字典编码
		 * @param {boolean} forceRefresh 是否强制刷新
		 * @returns {Array} 字典数据数组
		 */
		async function getDictionary(code, forceRefresh = false) {
			// 如果缓存为空或强制刷新，则重新加载所有字典
			if (!dictionaries.value || Object.keys(dictionaries.value).length === 0 || forceRefresh) {
				await loadAllDictionaries()
			}

			return dictionaries.value[code] || []
		}

		/**
		 * 批量获取字典数据
		 * @param {Array<string>} codes 字典编码数组
		 * @param {boolean} forceRefresh 是否强制刷新
		 * @returns {Object} 字典数据对象
		 */
		async function getDictionaries(codes, forceRefresh = false) {
			// 如果缓存为空或强制刷新，则重新加载所有字典
			if (!dictionaries.value || Object.keys(dictionaries.value).length === 0 || forceRefresh) {
				await loadAllDictionaries()
			}

			const result = {}
			codes.forEach((code) => {
				result[code] = dictionaries.value[code] || []
			})
			return result
		}

		/**
		 * 根据字典 code 和 value 获取 label
		 * @param {string} code 字典编码
		 * @param {any} value 字典值
		 * @returns {string} 字典标签
		 */
		function getLabelByValue(code, value) {
			const dict = dictionaries.value[code]
			if (!dict) return value

			const item = dict.find((item) => item.value === value)
			return item ? item.label : value
		}

		/**
		 * 清空字典缓存
		 */
		function clearCache() {
			dictionaries.value = {}
			dictionaryMeta.value = {}
			dictionaryIdToCodeMap.value = {}
			lastLoadTime.value = null
		}

		/**
		 * 清除特定字典的缓存
		 * @param {string|number} dictionaryIdOrCode 字典ID或编码
		 */
		function clearDictionary(dictionaryIdOrCode) {
			// 如果传入的是字典ID，需要先找到对应的code
			let code = dictionaryIdOrCode

			if (typeof dictionaryIdOrCode === 'number') {
				// 直接从ID映射表中查找
				code = dictionaryIdToCodeMap.value[dictionaryIdOrCode]
			}

			// 删除对应字典的缓存
			if (code && dictionaries.value[code]) {
				delete dictionaries.value[code]
				delete dictionaryMeta.value[code]
				if (dictionaryIdOrCode && typeof dictionaryIdOrCode === 'number') {
					delete dictionaryIdToCodeMap.value[dictionaryIdOrCode]
				}
			}
		}

		/**
		 * 建立字典ID到Code的映射
		 * @param {Array} dictionaryList 字典列表（包含id和code）
		 */
		function buildIdToCodeMap(dictionaryList) {
			dictionaryList.forEach((dict) => {
				if (dict.id && dict.code) {
					dictionaryIdToCodeMap.value[dict.id] = dict.code
				}
			})
		}

		/**
		 * 刷新字典缓存
		 * @param {boolean} force 是否强制刷新
		 */
		async function refresh(force = true) {
			await loadAllDictionaries(force)
		}

		/**
		 * 获取缓存信息
		 */
		function getCacheInfo() {
			return {
				count: Object.keys(dictionaries.value).length,
				lastLoadTime: lastLoadTime.value,
			}
		}

		return {
			dictionaries,
			dictionaryMeta,
			dictionaryIdToCodeMap,
			loading,
			lastLoadTime,
			loadAllDictionaries,
			getDictionary,
			getDictionaries,
			getLabelByValue,
			clearCache,
			clearDictionary,
			buildIdToCodeMap,
			refresh,
			getCacheInfo,
		}
	},
	{
		persist: {
			key: 'dictionary-store',
			storage: customStorage,
			pick: ['dictionaries', 'lastLoadTime'],
		},
	},
)
