Files
hzdyjs/mobile/src/common/dict.js
T
2025-08-08 20:35:17 +08:00

310 lines
9.3 KiB
JavaScript

// 移动端字典数据获取公共方法 - 适配Vue 2.6.14 + uni-app 2.x
import { get } from './request.js';
/**
* 字典数据缓存管理
*/
const dictCache = {
// 获取缓存的字典数据
get(dictType) {
try {
const cacheKey = `dict_${dictType}`;
const cached = uni.getStorageSync(cacheKey);
if (cached) {
const data = JSON.parse(cached);
// 检查缓存是否过期(24小时)
if (Date.now() - data.timestamp < 24 * 60 * 60 * 1000) {
console.log(`📋 从缓存获取字典: ${dictType}`, data.data);
return data.data;
} else {
// 缓存过期,删除
uni.removeStorageSync(cacheKey);
console.log(`⏰ 字典缓存已过期: ${dictType}`);
}
}
return null;
} catch (error) {
console.error(`❌ 获取字典缓存失败 ${dictType}:`, error);
return null;
}
},
// 设置字典数据缓存
set(dictType, data) {
try {
const cacheKey = `dict_${dictType}`;
const cacheData = {
data: data,
timestamp: Date.now(),
};
uni.setStorageSync(cacheKey, JSON.stringify(cacheData));
console.log(`💾 字典数据已缓存: ${dictType}`);
} catch (error) {
console.error(`❌ 设置字典缓存失败 ${dictType}:`, error);
}
},
// 清除指定字典缓存
remove(dictType) {
try {
const cacheKey = `dict_${dictType}`;
uni.removeStorageSync(cacheKey);
console.log(`🗑️ 已清除字典缓存: ${dictType}`);
} catch (error) {
console.error(`❌ 清除字典缓存失败 ${dictType}:`, error);
}
},
// 清除所有字典缓存
clear() {
try {
const storageInfo = uni.getStorageInfoSync();
const dictKeys = storageInfo.keys.filter((key) => key.startsWith('dict_'));
dictKeys.forEach((key) => {
uni.removeStorageSync(key);
});
console.log('🗑️ 已清除所有字典缓存');
} catch (error) {
console.error('❌ 清除所有字典缓存失败:', error);
}
},
};
/**
* 获取字典数据API
* @param {string} dictType - 字典类型
* @returns {Promise} 字典数据Promise
*/
export const getDicts = (dictType) => {
return get(`/system/dict/data/type/${dictType}`, null, {
isToken: false, // 字典数据不需要token认证
});
};
/**
* 字典数据排序处理
* @param {Array} dictDataRaw - 原始字典数据数组
* @returns {Array} 排序后的字典选项数组
*/
const sortAndTransformDict = (dictDataRaw) => {
if (!Array.isArray(dictDataRaw)) {
return [];
}
// 按dictSort升序,dictSort相同再按dictValue排序
const sortedDictDataRaw = dictDataRaw.sort((a, b) => {
if (a.dictSort !== b.dictSort) {
return a.dictSort - b.dictSort;
}
// dictSort相同,按dictValue数值排序
const valueA = Number(a.dictValue);
const valueB = Number(b.dictValue);
if (!isNaN(valueA) && !isNaN(valueB)) {
return valueA - valueB;
}
return String(a.dictValue).localeCompare(String(b.dictValue));
});
// 转换为标准字典选项格式
return sortedDictDataRaw.map((item) => ({
label: item.dictLabel,
value: item.dictValue,
elTagType: item.listClass,
elTagClass: item.cssClass,
remark: item.remark,
}));
};
/**
* 获取单个字典数据
* @param {string} dictType - 字典类型
* @param {boolean} useCache - 是否使用缓存,默认true
* @returns {Promise<Array>} 字典数据数组
*/
export const getDict = async (dictType, useCache = true) => {
if (!dictType) {
console.warn('字典类型不能为空');
return [];
}
try {
// 尝试从缓存获取
if (useCache) {
const cached = dictCache.get(dictType);
if (cached && Array.isArray(cached)) {
return cached;
}
}
// 从API获取
console.log(`🔍 开始加载字典类型: ${dictType}`);
const resp = await getDicts(dictType);
console.log(`📋 字典 ${dictType} API响应:`, resp);
if (resp && resp.data && Array.isArray(resp.data) && resp.data.length > 0) {
const dictData = sortAndTransformDict(resp.data);
// 缓存数据
if (useCache) {
dictCache.set(dictType, dictData);
}
console.log(`✅ 字典 ${dictType} 加载成功,数据条数:`, dictData.length);
return dictData;
} else {
console.warn(`⚠️ 字典类型 ${dictType} 没有返回有效数据`);
return [];
}
} catch (error) {
console.error(`❌ 获取字典类型 ${dictType} 失败:`, error);
return [];
}
};
/**
* 批量获取多个字典数据(Vue 2适配版本)
* 由于Vue 2没有reactive,返回普通对象并提供响应式更新方法
* @param {...string} dictTypes - 字典类型列表
* @returns {Object} 包含字典数据和更新方法的对象
*/
export const useDict = (...dictTypes) => {
// 初始化字典数据对象
const dictData = {};
dictTypes.forEach((dictType) => {
dictData[dictType] = [];
});
// 响应式数据更新回调
let updateCallback = null;
// 批量加载字典数据
const loadAllDicts = async () => {
try {
console.log('🚀 开始批量加载字典数据:', dictTypes);
const promises = dictTypes.map(async (dictType) => {
try {
const data = await getDict(dictType);
dictData[dictType] = data;
// 触发响应式更新
if (typeof updateCallback === 'function') {
updateCallback(dictType, data);
}
return { dictType, data };
} catch (error) {
console.error(`加载字典 ${dictType} 失败:`, error);
dictData[dictType] = [];
return { dictType, data: [] };
}
});
await Promise.all(promises);
console.log('✅ 批量加载字典数据完成:', dictData);
} catch (error) {
console.error('❌ 批量加载字典数据失败:', error);
}
};
// 立即执行加载
loadAllDicts();
return {
// 字典数据对象
data: dictData,
// 设置响应式更新回调(用于在组件中触发视图更新)
setUpdateCallback: (callback) => {
updateCallback = callback;
},
// 重新加载指定字典
reload: (dictType) => {
if (dictType) {
return getDict(dictType, false); // 不使用缓存
} else {
return loadAllDicts();
}
},
// 清除缓存
clearCache: (dictType) => {
if (dictType) {
dictCache.remove(dictType);
} else {
dictCache.clear();
}
},
};
};
/**
* 获取字典标签
* @param {Array} dictData - 字典数据数组
* @param {string|number} value - 字典值
* @returns {string} 字典标签
*/
export const getDictLabel = (dictData, value) => {
if (!Array.isArray(dictData) || value === null || value === undefined) {
return '';
}
const item = dictData.find((dict) => String(dict.value) === String(value));
return item ? item.label : value;
};
/**
* 获取字典值
* @param {Array} dictData - 字典数据数组
* @param {string} label - 字典标签
* @returns {string} 字典值
*/
export const getDictValue = (dictData, label) => {
if (!Array.isArray(dictData) || !label) {
return '';
}
const item = dictData.find((dict) => dict.label === label);
return item ? item.value : '';
};
/**
* 检查字典值是否存在
* @param {Array} dictData - 字典数据数组
* @param {string|number} value - 字典值
* @returns {boolean} 是否存在
*/
export const hasDictValue = (dictData, value) => {
if (!Array.isArray(dictData) || value === null || value === undefined) {
return false;
}
return dictData.some((dict) => String(dict.value) === String(value));
};
/**
* 刷新字典缓存
* @param {string|Array<string>} dictTypes - 字典类型或字典类型数组
* @returns {Promise} 刷新Promise
*/
export const refreshDict = async (dictTypes) => {
if (!dictTypes) {
return Promise.resolve();
}
const types = Array.isArray(dictTypes) ? dictTypes : [dictTypes];
try {
const promises = types.map((dictType) => {
dictCache.remove(dictType); // 清除缓存
return getDict(dictType, false); // 重新获取
});
await Promise.all(promises);
console.log('✅ 字典缓存刷新完成:', types);
} catch (error) {
console.error('❌ 字典缓存刷新失败:', error);
}
};
// 导出缓存管理对象(用于高级用法)
export { dictCache };