fieldFormatter.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * 字段格式化工具函数
  3. */
  4. import { commonApi } from '@/api/common'
  5. import { formatDate } from '@/utils/date'
  6. /**
  7. * 获取字典翻译
  8. * @param {string} cbName - 字典名称
  9. * @param {string|number} value - 值
  10. * @param {string} cacheKey - 缓存键
  11. * @param {Map} dictCache - 字典缓存
  12. * @param {Function} updateCallback - 更新回调函数
  13. */
  14. export const getDictTranslation = async (cbName, value, cacheKey, dictCache, updateCallback) => {
  15. try {
  16. const result = await commonApi.getDictByCbNameAndValue(cbName, value)
  17. // console.log(`字典翻译 [${cbName}:${value}] API返回:`, result)
  18. // 处理新的数据格式:{"result":{"40211":"A班","40212":"A2班"}}
  19. let translatedValue = value // 默认返回原值
  20. if (result && result.data && result.data.result) {
  21. // 从result对象中根据value查找对应的翻译
  22. translatedValue = result.data.result[value] || value
  23. // console.log(`字典翻译结果: ${value} -> ${translatedValue}`)
  24. }
  25. dictCache.set(cacheKey, translatedValue)
  26. // 触发页面更新
  27. if (updateCallback) {
  28. updateCallback()
  29. }
  30. } catch (error) {
  31. console.error(`字典翻译失败 [${cbName}:${value}]:`, error)
  32. dictCache.set(cacheKey, value)
  33. }
  34. }
  35. /**
  36. * 格式化字段值(处理字典翻译、日期格式等)
  37. * @param {Object} fieldObj - 字段对象 {field, value}
  38. * @param {Map} dictCache - 字典缓存
  39. * @param {Function} getDictTranslationFn - 字典翻译函数
  40. * @returns {string} 格式化后的值
  41. */
  42. export const formatFieldValue = (fieldObj, dictCache, getDictTranslationFn) => {
  43. if (!fieldObj || !fieldObj.field || fieldObj.value === undefined) {
  44. return ''
  45. }
  46. const { field, value } = fieldObj
  47. // 分支1: 字典翻译处理
  48. if (field.cbName) {
  49. const cacheKey = `${field.cbName}_${value}`
  50. // 从缓存获取翻译结果
  51. if (dictCache.has(cacheKey)) {
  52. return dictCache.get(cacheKey)
  53. }
  54. // 异步获取字典翻译
  55. if (getDictTranslationFn) {
  56. getDictTranslationFn(field.cbName, value, cacheKey)
  57. }
  58. // 翻译完成前先显示原值
  59. return value
  60. }
  61. // 分支2: 日期格式化处理
  62. if (field.type === 3 || field.fmt) {
  63. return formatDate(value, field.fmt)
  64. }
  65. // 分支3: 数字格式化处理
  66. if (field.type === 2 && typeof value === 'number') {
  67. return value.toString()
  68. }
  69. // 分支4: 布尔值处理
  70. if (field.type === 1 && typeof value === 'boolean') {
  71. return value ? '是' : '否'
  72. }
  73. // 分支5: 默认处理 - 直接返回原值
  74. return value
  75. }
  76. /**
  77. * 字段类型常量
  78. */
  79. export const FIELD_TYPES = {
  80. BOOLEAN: 1, // 布尔值
  81. NUMBER: 2, // 数字
  82. DATE: 3, // 日期
  83. STRING: 4 // 字符串
  84. }