import { dict } from '/@/stores/dict';
import { getDictsByTypes } from '/@/api/admin/dict';
import { ref, toRefs } from 'vue';

/**
 * 获取字典数据
 * 支持批量获取，自动使用批量 API 减少请求次数
 */
export function useDict(...args: any): any {
	const res = ref({});
	return (() => {
		// 初始化所有字典类型为空数组
		args.forEach((dictType: String) => {
			// @ts-ignore
			res.value[dictType] = [];
		});

		// 分离已缓存和未缓存的字典类型
		const cachedDicts: string[] = [];
		const uncachedDicts: string[] = [];

		args.forEach((dictType: String) => {
			const dicts = dict().getDict(dictType);
			if (dicts) {
				// @ts-ignore
				res.value[dictType] = dicts;
				cachedDicts.push(dictType as string);
			} else {
				uncachedDicts.push(dictType as string);
			}
		});

		// 如果有未缓存的字典，使用批量 API 获取
		if (uncachedDicts.length > 0) {
			getDictsByTypes(uncachedDicts).then((resp) => {
				uncachedDicts.forEach((dictType: string) => {
					// @ts-ignore
					const dictData = resp.data[dictType] || [];
					// @ts-ignore
					res.value[dictType] = dictData.map((p: any) => ({
						label: p.label,
						value: p.value,
						elTagType: p.listClass,
						elTagClass: p.cssClass
					}));
					// @ts-ignore
					dict().setDict(dictType, res.value[dictType]);
				});
				});
			}

		return toRefs(res.value);
	})();
}
