import { getDict } from '@/api/profile';
const CACHE_KEY = 'DICT_CACHE';
let dictCache = new Map();
// 初始化時加載緩存
const loadCache = () => {
? const cache = uni.getStorageSync(CACHE_KEY);
? if (cache) {
? ? dictCache = new Map(JSON.parse(cache));
? }
};
// 保存緩存到Storage
const saveCache = () => {
? uni.setStorageSync(CACHE_KEY, JSON.stringify([...dictCache]));
};
/**
?* 獲取字典數據(支持多字段、緩存)
?* @param {string} dictCodes - 字典編碼,支持逗號拼接,如 'VISIT_REASON,VISITOR_TYPE'
?* @param {string} url - 請求 URL
?* @returns {Promise<Object>} 返回包含所有字典的 map 對象,如 { VISIT_REASON: { ... }, VISITOR_TYPE: { ... } }
?*/
// 獲取字典數據(帶緩存和持久化)
export const dictWithUrl = async(dictCodes) => {
? loadCache(); // 每次調用先加載緩存
? const codes = typeof dictCodes === 'string' ? dictCodes.split(',').map(code => code.trim()) : dictCodes;
? // 檢查緩存
? const cachedData = {};
? const uncachedCodes = codes.filter(code => {
? ? if (dictCache.has(code)) {
? ? ? cachedData[code] = dictCache.get(code);
? ? ? return false;
? ? }
? ? return true;
? });
? // 全部命中緩存
? if (!uncachedCodes.length) {
? ? return { data: cachedData };
? }
? // 請求未緩存數據
? const res = await getDict(uncachedCodes.join(','));
? // 成功后合并更新緩存
? Object.entries(res.data).forEach(([code, data]) => {
? ? dictCache.set(code, data);
? ? cachedData[code] = data;
? });
? saveCache(); // 保存最新緩存
? return { data: cachedData };
};
// 清空緩存(可選)
export const clearDictCache = () => {
? dictCache.clear();
? uni.removeStorageSync(CACHE_KEY);
};
export const getDictLabel = (dictOptions, dictKey, value, defaultValue = '') => {
? if (!dictKey) return value || defaultValue;
? if (dictOptions[dictKey]) {
? ? return dictOptions[dictKey][value] || value || defaultValue;
? }
};