/** * 字段格式化工具函数 */ import { commonApi } from '@/api/common' import { formatDate } from '@/utils/date' /** * 获取字典翻译 * @param {string} cbName - 字典名称 * @param {string|number} value - 值 * @param {string} cacheKey - 缓存键 * @param {Map} dictCache - 字典缓存 * @param {Function} updateCallback - 更新回调函数 */ export const getDictTranslation = async (cbName, value, cacheKey, dictCache, updateCallback) => { try { const result = await commonApi.getDictByCbNameAndValue(cbName, value) // console.log(`字典翻译 [${cbName}:${value}] API返回:`, result) // 处理新的数据格式:{"result":{"40211":"A班","40212":"A2班"}} let translatedValue = value // 默认返回原值 if (result && result.data && result.data.result) { // 从result对象中根据value查找对应的翻译 translatedValue = result.data.result[value] || value // console.log(`字典翻译结果: ${value} -> ${translatedValue}`) } dictCache.set(cacheKey, translatedValue) // 触发页面更新 if (updateCallback) { updateCallback() } } catch (error) { console.error(`字典翻译失败 [${cbName}:${value}]:`, error) dictCache.set(cacheKey, value) } } /** * 格式化字段值(处理字典翻译、日期格式等) * @param {Object} fieldObj - 字段对象 {field, value} * @param {Map} dictCache - 字典缓存 * @param {Function} getDictTranslationFn - 字典翻译函数 * @returns {string} 格式化后的值 */ export const formatFieldValue = (fieldObj, dictCache, getDictTranslationFn) => { if (!fieldObj || !fieldObj.field || fieldObj.value === undefined) { return '' } const { field, value } = fieldObj // 分支1: 字典翻译处理 if (field.cbName) { const cacheKey = `${field.cbName}_${value}` // 从缓存获取翻译结果 if (dictCache.has(cacheKey)) { return dictCache.get(cacheKey) } // 异步获取字典翻译 if (getDictTranslationFn) { getDictTranslationFn(field.cbName, value, cacheKey) } // 翻译完成前先显示原值 return value } // 分支2: 日期格式化处理 if (field.type === 3 || field.fmt) { return formatDate(value, field.fmt) } // 分支3: 数字格式化处理 if (field.type === 2 && typeof value === 'number') { return value.toString() } // 分支4: 布尔值处理 if (field.type === 1 && typeof value === 'boolean') { return value ? '是' : '否' } // 分支5: 默认处理 - 直接返回原值 return value } /** * 字段类型常量 */ export const FIELD_TYPES = { BOOLEAN: 1, // 布尔值 NUMBER: 2, // 数字 DATE: 3, // 日期 STRING: 4 // 字符串 }