| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- /**
- * 业务字典的唯一内存权威(票 07)。
- *
- * 分层(规格 §4):内存 → 持久化快照 → 原码。这里只管内存这一层与翻译:
- * 快照的编解码在 `dictSnapshot.js`,读写 localStorage 在 `services/cockpitDict.js`。
- * **不内置第二份可漂移词表** —— 命中就出中文,没命中由调用方决定回原码。
- *
- * 既有设施词表(泵站类型等)不在此列,迁移另票。
- */
- export const DICT_TYPES = Object.freeze({
- riskLevel: 'risk_level',
- riskColor: 'risk_color',
- hazardType: 'hazard_type',
- hazardLevel: 'hazard_level',
- hazardSource: 'hazard_source',
- hazardStatus: 'hazard_status',
- })
- export const DICT_TYPE_LIST = Object.freeze(Object.values(DICT_TYPES))
- const field = (row, camel, snake) => {
- if (!row || typeof row !== 'object') return ''
- const value = row[camel] !== undefined ? row[camel] : row[snake]
- return value === null || value === undefined ? '' : String(value).trim()
- }
- /** 字典端点的行 → `{ dictValue: dictLabel }`;缺值行不收,一行都收不出就回 null。 */
- export function toDictLabels(raw) {
- const rows = Array.isArray(raw) ? raw
- : (raw && Array.isArray(raw.rows) ? raw.rows : (raw && Array.isArray(raw.data) ? raw.data : []))
- const result = {}
- for (const row of rows) {
- const value = field(row, 'dictValue', 'dict_value')
- const label = field(row, 'dictLabel', 'dict_label')
- if (value && label) result[value] = label
- }
- return Object.keys(result).length ? result : null
- }
- /** 纯标签表(键非空、值为非空字符串),避免把任意对象当字典。 */
- export function isLabelMap(value) {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false
- const entries = Object.entries(value)
- return entries.length > 0 && entries.every(([key, label]) => key !== '' && typeof label === 'string' && label !== '')
- }
- /** 已注入的字典;冻结后整体替换,避免调用方原地改内存。 */
- let memory = Object.freeze({})
- /**
- * 注入一类字典(行数组或已解析的标签表都收)。
- *
- * 空表**不**覆盖已有值:接口某次返回空列表时,应当继续用上一份可用字典
- * (规格「接口失败保留快照」的同一口径),而不是把界面打回原码。
- */
- export function setDictLabels(type, value) {
- if (!DICT_TYPE_LIST.includes(type)) return false
- const map = toDictLabels(value) || (isLabelMap(value) ? { ...value } : null)
- if (!map) return false
- memory = { ...memory, [type]: map }
- return true
- }
- /** 当前已注入的字典表(快照写入用;回的是浅拷贝)。 */
- export function dictSnapshotSource() {
- return { ...memory }
- }
- /** 仅测试用:回到「字典未取到」。 */
- export function resetDictLabelsForTest() {
- memory = Object.freeze({})
- }
- export function hasDictLabels(type) {
- return !!memory[type]
- }
- /** 码 → 中文;这类字典没取到、或没有这个码,一律回空串,由调用方决定回什么原码。 */
- export function dictLabel(type, value) {
- const code = value === null || value === undefined ? '' : String(value).trim()
- if (!code) return ''
- const map = memory[type]
- return map && Object.hasOwn(map, code) ? map[code] : ''
- }
|