entityDetail.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /**
  2. * 统一实体详情领域边界(issue 65)。
  3. *
  4. * 列表只传 { kind, id };本模块负责身份校验、不同后端载荷的正规化和紧凑详情视图。
  5. * point/device 沿用既有详情链,不在此重复实现。
  6. */
  7. import { eventLevelFromBucket, eventLevelTag, eventStatusText, eventTypeText, eventNameText, formatEventTime } from './eventList.js'
  8. import { statusDisplayTone } from './eventStatusVocab.js'
  9. import { DEFAULT_TONE } from './statusTones.js'
  10. import { toWorkOrder, toWorkOrderTimeline, workOrderStateName } from './workOrder.js'
  11. import { trackOf } from './workOrderTimeline.js'
  12. import { facilityStatusTone } from './facilityStatus.js'
  13. import { pumpStationTypeText } from './facilityTypeDict.js'
  14. import { DICT_TYPES, dictLabel } from './dictLabels.js'
  15. export { facilityStatusTone } from './facilityStatus.js'
  16. export const ENTITY_DETAIL_KIND = Object.freeze({
  17. FACILITY: 'facility',
  18. EMERGENCY: 'emergency',
  19. EVENT: 'event',
  20. WORK_ORDER: 'work-order',
  21. })
  22. const KINDS = Object.freeze(Object.values(ENTITY_DETAIL_KIND))
  23. const PLACEHOLDER = '—'
  24. export function entityIdentity(input, fallbackKind = '') {
  25. const source = input && typeof input === 'object' ? input : {}
  26. const kind = String(source.kind || source.identityKind || fallbackKind || '').trim()
  27. const id = String(source.id ?? source.code ?? source.identityCode ?? '').trim()
  28. const category = String(source.category || source.identityCategory || '').trim().toUpperCase()
  29. const family = String(source.family || source.eventFamily || source.identityFamily || '').trim().toUpperCase()
  30. return { kind: KINDS.includes(kind) ? kind : '', id, category, family, valid: KINDS.includes(kind) && !!id }
  31. }
  32. export function sameEntity(left, right) {
  33. const a = entityIdentity(left)
  34. const b = entityIdentity(right)
  35. return a.valid && b.valid && a.kind === b.kind && a.id === b.id && a.category === b.category && a.family === b.family
  36. }
  37. /** AjaxResult / page / list 三种常见外形收成同一份有效载荷。 */
  38. export function unwrapEntityPayload(raw) {
  39. let value = raw
  40. if (value && typeof value === 'object' && typeof value.code === 'number') {
  41. if (value.code !== 200) return null
  42. value = value.data
  43. }
  44. if (value && typeof value === 'object' && value.data !== undefined && !Array.isArray(value.data)) {
  45. const keys = Object.keys(value)
  46. if (keys.every((key) => ['data', 'msg', 'message', 'success', 'timestamp'].includes(key))) value = value.data
  47. }
  48. return value
  49. }
  50. export function normalizePage(raw) {
  51. const payload = unwrapEntityPayload(raw)
  52. if (Array.isArray(payload)) return { rows: payload, page: 1, pageSize: payload.length, total: payload.length, totalPages: 1 }
  53. const source = payload && typeof payload === 'object' ? payload : {}
  54. const rows = [source.rows, source.records, source.list, source.items, source.content].find(Array.isArray) || []
  55. const paging = source.pagination && typeof source.pagination === 'object' ? source.pagination : source
  56. const page = positive(paging.page ?? paging.current ?? paging.pageNum, 1)
  57. const pageSize = positive(paging.pageSize ?? paging.size ?? paging.limit, rows.length)
  58. const total = nonNegative(paging.total, rows.length)
  59. const totalPages = positive(paging.totalPages ?? paging.pages, pageSize ? Math.ceil(total / pageSize) : 1)
  60. return { rows, page, pageSize, total, totalPages }
  61. }
  62. export function normalizeEntityDetail(identityInput, raw, prefill = null) {
  63. const identity = entityIdentity(identityInput)
  64. if (!identity.valid) return null
  65. const payload = unwrapEntityPayload(raw)
  66. const page = normalizePage(payload)
  67. let source = payload
  68. if (Array.isArray(payload)) source = payload.find((row) => matchesId(row, identity.id)) || null
  69. else if (payload && typeof payload === 'object' && page.rows.length) source = page.rows.find((row) => matchesId(row, identity.id)) || null
  70. const seed = prefill && typeof prefill === 'object' ? prefill : {}
  71. const publishedCodeKey = identity.kind === ENTITY_DETAIL_KIND.EVENT && source && source.codeText === undefined
  72. ? ['code', 'eventCode', 'warningNo', 'alarmNo'].find((key) => Object.hasOwn(source, key)) : ''
  73. const publishedCode = publishedCodeKey ? text(source[publishedCodeKey]) : undefined
  74. source = source && typeof source === 'object' ? { ...seed, ...source } : { ...seed }
  75. if (publishedCode !== undefined) source.codeText = publishedCode
  76. if (identity.kind === ENTITY_DETAIL_KIND.WORK_ORDER) return normalizeWorkOrder(identity, source)
  77. if (identity.kind === ENTITY_DETAIL_KIND.EVENT) return normalizeEvent(identity, source)
  78. return normalizeAsset(identity, source)
  79. }
  80. export function prefilledEntityDetail(identity, prefill) {
  81. return normalizeEntityDetail(identity, {}, prefill)
  82. }
  83. /** 抬头:类别 + 业务编码;没有业务编码列时只留类别,有列缺值才补「编码未提供」。 */
  84. function assetSubtitle(kindLabel, displayCode, hasCodeColumn = true) {
  85. return [kindLabel, hasCodeColumn ? displayCode || '编码未提供' : ''].filter(Boolean).join(' · ')
  86. }
  87. export function entityDetailView(detail) {
  88. const current = detail || {}
  89. return {
  90. kind: current.kind || '',
  91. title: current.title || current.name || '实体详情',
  92. // 副标题仅用业务编号;缺码不回退主键。
  93. subtitle: current.subtitle || assetSubtitle(current.kindLabel, current.displayCode),
  94. tone: current.tone || 'neutral',
  95. status: current.statusText || '',
  96. // 徽标的抬头:防护目标写「风险等级」,其它对象的状态不加抬头。
  97. statusCaption: current.statusCaption || '',
  98. // 等级与状态各有自己的语义色:等级沿用卡片那张四级词表,不与状态色混用。
  99. levelLabel: current.levelLabel || '',
  100. levelTone: current.levelTone || '',
  101. // 类别是身份而不是普通字段:抬头要能一眼看出是什么对象。
  102. categoryText: current.categoryText || '',
  103. summary: Array.isArray(current.summary) ? current.summary : [],
  104. tabs: Array.isArray(current.tabs) ? current.tabs : [],
  105. relatedAlarms: Array.isArray(current.relatedAlarms) ? current.relatedAlarms : [],
  106. stage: Array.isArray(current.stage) ? current.stage : [],
  107. sections: Array.isArray(current.sections) ? current.sections : [],
  108. people: Array.isArray(current.people) ? current.people : [],
  109. devices: Array.isArray(current.devices) ? current.devices : [],
  110. relations: Array.isArray(current.relations) ? current.relations : [],
  111. sectionMap: current.sectionMap && typeof current.sectionMap === 'object' ? current.sectionMap : {},
  112. attachments: Array.isArray(current.attachments) ? current.attachments : [],
  113. maintenanceImages: Array.isArray(current.maintenanceImages) ? current.maintenanceImages : [],
  114. records: Array.isArray(current.records) ? current.records : [],
  115. track: current.track || null,
  116. }
  117. }
  118. /** 源表只有内部主键、没有业务编码列的资产类别(目前只有风险评估表)。 */
  119. const ASSET_WITHOUT_BUSINESS_CODE = new Set(['PROTECTION_TARGET'])
  120. function normalizeAsset(identity, source) {
  121. const emergency = identity.kind === ENTITY_DETAIL_KIND.EMERGENCY
  122. const category = text(source.category || identity.category).toUpperCase()
  123. const attributes = source.attributes && typeof source.attributes === 'object' ? source.attributes : {}
  124. // 编码字段只跟随源表的列:没有业务编码列就不生成该字段(防护目标的 riskId 是主键,不是编码)。
  125. const hasCodeColumn = !ASSET_WITHOUT_BUSINESS_CODE.has(category)
  126. const displayCode = hasCodeColumn ? text(source.code) : ''
  127. const name = text(source.name || source.facilityName || source.resourceName || source.title) || (emergency ? '应急对象名称未提供' : '设施名称未提供')
  128. // 状态是码值时翻成中文(设施:0 正常 / 1 异常;后端若直接给人话则原样用)。
  129. const statusRaw = source.status ?? source.state ?? source.statusName ?? source.stateName
  130. const isRiskTarget = category === 'PROTECTION_TARGET'
  131. const status = (isRiskTarget ? riskLevelText(statusRaw) : emergency ? undefinedEnumText(statusRaw) : facilityStatusText(statusRaw)) || '状态未发布'
  132. // 防护目标的「状态」就是风险等级(规格 §5):抬头只留一个「风险等级」徽标,配色跟 risk_color。
  133. const riskColorRaw = isRiskTarget ? attributes.riskColor ?? statusRaw : ''
  134. const location = text(source.address || source.location || source.position)
  135. const fields = assetFields(category, attributes)
  136. const kindLabel = emergency ? '应急对象' : '设施'
  137. const noun = emergency ? '对象' : '设施'
  138. return {
  139. ...identity, category, name, title: name, displayCode,
  140. kindLabel,
  141. // 抬头只拼接真实存在的业务编码;没有编码列时不留「编码未提供」。
  142. subtitle: assetSubtitle(kindLabel, displayCode, hasCodeColumn),
  143. statusText: status, statusCaption: isRiskTarget ? '风险等级' : '',
  144. tone: isRiskTarget ? riskTone(riskColorRaw) : emergency ? 'neutral' : facilityStatusTone(source.status),
  145. raw: source,
  146. categoryText: facilityCategoryText(category),
  147. coordinates: source.coordinates || null,
  148. summary: assetSummary(category, attributes, location),
  149. tabs: [tab('overview', '基本信息'), tab('business', '业务详情'), tab('related', '关联信息')],
  150. people: assetPeople(attributes),
  151. devices: assetDevices(attributes),
  152. attachments: assetAttachments(attributes),
  153. sections: compactSections([
  154. section('基本信息', [
  155. ...(hasCodeColumn ? [field(`${noun}编码`, displayCode || '未提供', true)] : []),
  156. field(`${noun}类别`, facilityCategoryText(category)),
  157. field('数据更新时间', formatEventTime(source.updatedAt)),
  158. ]),
  159. section('位置与归属', [field('位置描述', location, true), field('所属片区', source.districtName), field('坐标', coordinatesText(source.coordinates), true)]),
  160. section('业务详情', fields),
  161. ]),
  162. }
  163. }
  164. /**
  165. * 数值型指标的**单位登记**(维护者 2026-10-29「所有数值都要带单位」)。
  166. *
  167. * 只在这里写一次,摘要网格与业务明细都从这里取 —— 两处各写一份单位必然漂移
  168. * (已经踩过:摘要写「长度(米)」、明细写「长度」+ 单位,同一份数据两种长相)。
  169. * 单位来自后端领域注释,不由前端猜。
  170. */
  171. const COMMON_UNITS = {
  172. lengthMeters: '米',
  173. diameterMillimeters: '毫米',
  174. designCapacity: '万m³/d',
  175. currentCapacity: '万m³/d',
  176. designHead: 'm',
  177. storageCapacity: 'm³',
  178. pumpCount: '台',
  179. powerCapacity: 'kW',
  180. assetValue: '元',
  181. useLifeYears: '年',
  182. riskScore: '分',
  183. }
  184. /**
  185. * 同一字段名在不同设施里量纲不同:泵站设计流量是 m³/h,排水工程设施设计流量是 m³/s。
  186. * 所以单位必须**按类别**登记,"一个键一个单位"会张冠李戴。
  187. */
  188. const UNIT_BY_CATEGORY = {
  189. PIPE_NETWORK: {},
  190. WATER_PLANT: {},
  191. WATER_SOURCE: {},
  192. PUMP_STATION: { designFlow: 'm³/h' },
  193. ENGINEERING_FACILITY: { designFlow: 'm³/s' },
  194. DRAINAGE_GATE: { designFlow: 'm³/s' },
  195. DRAINAGE_STORAGE: { designFlow: 'm³/s' },
  196. WATER_USER: { initialReading: 'm³', currentReading: 'm³', annualWaterConsumption: 'm³' },
  197. MANHOLE: { manholeDepth: 'm' },
  198. EMERGENCY_RESOURCE: {},
  199. HAZARD: {},
  200. PROTECTION_TARGET: {},
  201. }
  202. /** 字段在该设施类别下的单位;没登记返回空串(纯文本字段)。 */
  203. function unitOf(category, key) {
  204. const scoped = UNIT_BY_CATEGORY[category] || {}
  205. return scoped[key] !== undefined ? scoped[key] : COMMON_UNITS[key] || ''
  206. }
  207. /** 摘要与明细共用的中文字段名(维护者 2026-10-29:一律中文、不带括注)。 */
  208. const SUMMARY_LABELS = {
  209. lengthMeters: '长度',
  210. diameterMillimeters: '管径',
  211. material: '材质',
  212. designCapacity: '设计能力',
  213. currentCapacity: '当前能力',
  214. treatmentProcess: '处理工艺',
  215. designFlow: '设计流量',
  216. designHead: '设计扬程',
  217. storageCapacity: '调蓄容积',
  218. pumpCount: '水泵数量',
  219. powerCapacity: '装机功率',
  220. assetValue: '资产价值',
  221. useLifeYears: '预计使用年限',
  222. riskScore: '风险分值',
  223. riskLevel: '风险等级',
  224. fmodel: '型号',
  225. model: '型号',
  226. specification: '规格',
  227. maintainer: '维护人',
  228. level: '等级',
  229. rectifyDeadline: '整改期限',
  230. rectifyPerson: '整改人',
  231. assessmentTime: '评估时间',
  232. facilityLevel: '设施等级',
  233. manholeDepth: '井深',
  234. manholeShape: '井形',
  235. ownershipUnit: '权属单位',
  236. userType: '用水户类型',
  237. address: '用水地址',
  238. contactPerson: '联系人',
  239. meterNumber: '水表编号',
  240. initialReading: '初始读数',
  241. currentReading: '当前读数',
  242. annualWaterConsumption: '年用水量',
  243. hydrantType: '消火栓类型',
  244. inletPipeDiameter: '进水主管管径',
  245. waterType: '水源类型',
  246. protectionLevel: '保护等级',
  247. waterQualityLevel: '水质等级',
  248. }
  249. /** 同类字段在不同设施里的业务名不同(隐患等级 vs 设施等级),差异只在这里登记。 */
  250. const SUMMARY_LABELS_BY_CATEGORY = {
  251. HAZARD: { level: '隐患等级' },
  252. ENGINEERING_FACILITY: { facilityLevel: '设施等级' },
  253. DRAINAGE_GATE: { facilityLevel: '设施等级' },
  254. DRAINAGE_STORAGE: { facilityLevel: '设施等级' },
  255. // 消火栓的产权单位与窨井的权属单位是同一字段在不同类别下的业务名。
  256. WATER_FIRE_HYDRANT: { ownershipUnit: '产权单位' },
  257. }
  258. function assetSummary(category, attributes, location) {
  259. // 摘要只挑"一眼要看的读数",键与明细同源;单位统一由 METRIC_UNITS 提供。
  260. const byCategory = {
  261. WATER_PLANT: ['currentCapacity', 'designCapacity', 'treatmentProcess'],
  262. WATER_SOURCE: ['waterType', 'protectionLevel', 'waterQualityLevel'],
  263. ENGINEERING_FACILITY: ['facilityLevel', 'designFlow', 'storageCapacity'],
  264. DRAINAGE_GATE: ['facilityLevel', 'designFlow', 'storageCapacity'],
  265. DRAINAGE_STORAGE: ['facilityLevel', 'designFlow', 'storageCapacity'],
  266. WATER_USER: ['currentReading', 'annualWaterConsumption', 'userType'],
  267. WATER_FIRE_HYDRANT: ['hydrantType', 'model', 'inletPipeDiameter'],
  268. PUMP_STATION: ['pumpCount', 'designFlow', 'powerCapacity'],
  269. PIPE_NETWORK: ['lengthMeters', 'diameterMillimeters', 'material'],
  270. MANHOLE: ['manholeDepth', 'manholeShape', 'material', 'ownershipUnit'],
  271. HAZARD: ['level', 'rectifyDeadline', 'rectifyPerson'],
  272. // 风险等级由抬头徽标承担,摘要不再重复同一个词(票面「只出现一次」)。
  273. PROTECTION_TARGET: ['riskScore', 'assessmentTime'],
  274. EMERGENCY_RESOURCE: ['model', 'specification', 'maintainer'],
  275. }
  276. const labels = { ...SUMMARY_LABELS, ...SUMMARY_LABELS_BY_CATEGORY[category] }
  277. const rows = (byCategory[category] || []).map((key) => {
  278. const unit = unitOf(category, key)
  279. const raw = assetFieldValue(key, attributes)
  280. // 只有真有单位时才拼单位;纯文本字段(材质/负责人…)原样。
  281. const value = unit ? withUnitText(raw, unit) : raw
  282. return [labels[key] || SUMMARY_LABELS[key] || key, value]
  283. })
  284. // 状态只在抬头徽标出现;摘要卡不再重复(与预警详情同一口径)。
  285. return summaryItems([...rows, ['位置', location]])
  286. }
  287. function assetPeople(a) { return peopleItems([['负责人', a.principal], ['维护人', a.maintainer], ['整改人', a.rectifyPerson], ['联系电话', a.contactPhone || a.maintainerPhone]]) }
  288. function assetAttachments(a) { return attachmentItems(a.images || a.image) }
  289. function assetDevices(a) {
  290. if (Array.isArray(a.devices)) return a.devices.map((item) => ({
  291. id: item.id || '', code: text(item.code), name: item.name || item.code || '设备名称未提供',
  292. type: item.type || '', location: item.location || '', status: deviceStatusText(item),
  293. }))
  294. return String(a.equipmentIds || a.equipmentId || '').split(',').map((id) => id.trim()).filter(Boolean).map((id) => ({ id, name: '设备名称未提供', code: '', type: '', location: '', status: '状态未发布' }))
  295. }
  296. function deviceStatusText(item) {
  297. if (item.onlineStatus === 0) return '离线'
  298. if (item.alarmStatus === 1) return '报警'
  299. if (item.currentStatus === 1) return '维修'
  300. if (item.currentStatus === 2) return '报废'
  301. if (item.onlineStatus === 1) return '在线'
  302. return '状态未发布'
  303. }
  304. /**
  305. * 设施枚举词表(维护者 2026-10-29 走查逐条点名的口径)。
  306. *
  307. * 后端这些字段是**码值**(status/networkType/networkLevel),直接印数字就是漏码;
  308. * 但认不出的值也不能编一个中文,所以统一走 `codedText()`:命中词表回「中文」,
  309. * 未命中回「码」本身(与 CODE_TEXT 的立场一致)。
  310. */
  311. const FACILITY_STATUS_TEXT = { '0': '正常', '1': '异常' }
  312. const NETWORK_TYPE_TEXT = { '0': '燃气管网', '1': '排水管网', '2': '供水管网' }
  313. const NETWORK_LEVEL_TEXT = { '0': '污水', '1': '雨水' }
  314. /** 排水工程设施类型(0 闸门 / 1 调蓄设施 / 2 泵站):同样是码值,一并直译。 */
  315. const ENGINEERING_FACILITY_TYPE_TEXT = { '0': '闸门', '1': '调蓄设施', '2': '泵站' }
  316. /** 窨井井形(manhole_shape):码值直译,认不出回原码(与上面几条同一纪律)。 */
  317. const MANHOLE_SHAPE_TEXT = { '0': '圆形', '1': '方形', '2': '矩形' }
  318. /** 消火栓类型(字典 water_fire_hydrant_type:0 市政室外 / 1 小区室外 / 2 室内)。 */
  319. const HYDRANT_TYPE_TEXT = { '0': '市政室外消火栓', '1': '小区室外消火栓', '2': '室内消火栓' }
  320. /** 类别中文名:界面上用「中文 + 英文码」,只印英文等于把接口词汇漏上大屏。 */
  321. const FACILITY_CATEGORY_TEXT = {
  322. PIPE_NETWORK: '管网',
  323. WATER_PLANT: '水厂',
  324. PUMP_STATION: '泵站',
  325. WATER_SOURCE: '水源地',
  326. ENGINEERING_FACILITY: '排水工程设施',
  327. DRAINAGE_GATE: '闸门',
  328. DRAINAGE_STORAGE: '调蓄设施',
  329. WATER_USER: '用水户',
  330. WATER_FIRE_HYDRANT: '消火栓',
  331. MANHOLE: '窨井',
  332. EMERGENCY_RESOURCE: '应急资源',
  333. HAZARD: '危险源',
  334. PROTECTION_TARGET: '防护目标',
  335. }
  336. /** 码 → 显示值;命中词表用中文,未登记机器码显示未知;已发布中文保留。 */
  337. function codedText(value, dictionary, withCode = false, unknownWithCode = false) {
  338. const code = value === null || value === undefined ? '' : String(value).trim()
  339. if (!code) return ''
  340. const label = dictionary && Object.hasOwn(dictionary, code) ? dictionary[code] : ''
  341. if (!label) {
  342. const shown = /\p{Script=Han}/u.test(code) && !/\p{Script=Latin}/u.test(code) ? code : '未知'
  343. return unknownWithCode && shown === '未知' ? `未知(${code})` : shown
  344. }
  345. return withCode ? `${label}(${code})` : label
  346. }
  347. /** 类别显示名:一律中文(维护者 2026-10-29:取消英文括注)。 */
  348. export function facilityCategoryText(category) {
  349. return codedText(category, FACILITY_CATEGORY_TEXT)
  350. }
  351. /** 设施状态(0 正常 / 1 异常)→ 中文;未知码保留原值并如实标注,不猜旧字典语义。 */
  352. export function facilityStatusText(status) {
  353. return codedText(status, FACILITY_STATUS_TEXT, false, true)
  354. }
  355. /**
  356. * 设施详情字段表(维护者 2026-10-29 设计规范)。
  357. *
  358. * 三条口径写死在这一处,别的层不再重复判断:
  359. * 1. **命名一律中文**,必要时用括号补英文码/后端字段名(英文只作补充,不作主名);
  360. * 2. **凡有量纲的读数必带单位**;单位来自后端领域注释(m³/d、m³/h、m、mm、m³、kW…),
  361. * 不从前端猜;
  362. * 3. 某些指标只在特定子类型下有效(如管网「二级分类」只对**排水管**有意义),
  363. * 无效时**保留该行并显示「—」**,不是把它删掉 —— 删掉会让读者以为这个设施没这个属性。
  364. *
  365. * 每项形如 { label, key, unit?, format?, always? }:
  366. * · `format` 把码值翻成中文(枚举词表只在这里登记);
  367. * · `always` 表示"无效也占位"(与 compactSections 的缺值剔除相反)。
  368. */
  369. function pipesFields(a) {
  370. const drainage = String(a.networkType ?? '').trim() === '1'
  371. return [
  372. { label: '管网类型', key: 'networkType', format: (v) => codedText(v, NETWORK_TYPE_TEXT) },
  373. // 二级分类=原来的"管网等级":后端 network_level 只用于区分排水管道(污水/雨水)。
  374. // 非排水管这个字段没有业务含义,按要求显示「—」而不是隐藏。
  375. {
  376. label: '二级分类',
  377. key: 'networkLevel',
  378. always: true,
  379. format: (v) => (drainage ? codedText(v, NETWORK_LEVEL_TEXT) : ''),
  380. invalidNote: drainage ? '' : '仅排水管道适用',
  381. },
  382. { label: '长度', key: 'lengthMeters' },
  383. { label: '管径', key: 'diameterMillimeters' },
  384. { label: '材质', key: 'material' },
  385. { label: '管养单位', key: 'managementUnit' },
  386. { label: '建设日期', key: 'buildDate' },
  387. { label: '备注', key: 'remark', wide: true },
  388. ]
  389. }
  390. /**
  391. * 工程设施字段表:旧响应类别保留仅为兼容当前后端载荷,不作为前端类型键或详情请求(票 04)。
  392. * 票 04 的两个新详情类别另用一张表,不继承旧的「设施类型→闸门/调蓄/泵站」折叠码。
  393. */
  394. const ENGINEERING_FACILITY_FIELD_ROWS = [
  395. { label: '设施类型', key: 'facilityType', format: (v) => codedText(v, ENGINEERING_FACILITY_TYPE_TEXT) },
  396. { label: '设施等级', key: 'facilityLevel' },
  397. { label: '管理单位', key: 'managementUnit' },
  398. { label: '建设日期', key: 'buildDate' },
  399. { label: '设计流量', key: 'designFlow' },
  400. { label: '设计扬程', key: 'designHead' },
  401. { label: '调蓄容积', key: 'storageCapacity' },
  402. { label: '关联设备', key: 'equipmentIds', wide: true },
  403. { label: '备注', key: 'remark', wide: true },
  404. ]
  405. /** 票 04:新类别的字段表去掉旧的折叠「设施类型」行,只保留真实工程属性。 */
  406. const DRAINAGE_FACILITY_FIELD_ROWS = ENGINEERING_FACILITY_FIELD_ROWS.slice(1)
  407. const ASSET_FIELD_ROWS = {
  408. PIPE_NETWORK: null, // 见 pipesFields():需要按管网类型决定二级分类是否适用
  409. // 窨井(维护者 2026-11-16):字段与 manhole_base 的列一一对应,不展示不存在的语义。
  410. MANHOLE: [
  411. { label: '井深', key: 'manholeDepth' },
  412. { label: '井形', key: 'manholeShape', format: (v) => codedText(v, MANHOLE_SHAPE_TEXT) },
  413. { label: '材质', key: 'material' },
  414. { label: '权属单位', key: 'ownershipUnit' },
  415. { label: '备注', key: 'remark', wide: true },
  416. ],
  417. // 票 02:水源地字段按后端 water_source_info 实体登记(详情接口已返回这些属性),
  418. // 与「水源类型」区分:waterSourceType 是水厂的取水水源类型,waterType 是水源地自身的水源类型。
  419. WATER_SOURCE: [
  420. { label: '水源类型', key: 'waterType' },
  421. { label: '保护等级', key: 'protectionLevel' },
  422. { label: '水质等级', key: 'waterQualityLevel' },
  423. { label: '水源地类型', key: 'sourceType' },
  424. { label: '所属单位', key: 'unit' },
  425. { label: '详细地址', key: 'address', wide: true },
  426. { label: '保护范围', key: 'protectionScope', wide: true },
  427. { label: '上报时间', key: 'reportTime' },
  428. { label: '备注', key: 'remark', wide: true },
  429. ],
  430. WATER_PLANT: [
  431. { label: '水源类型', key: 'waterSourceType' },
  432. { label: '设计能力', key: 'designCapacity' },
  433. { label: '当前能力', key: 'currentCapacity' },
  434. { label: '处理工艺', key: 'treatmentProcess', wide: true },
  435. { label: '投产日期', key: 'commissionDate' },
  436. { label: '水质标准', key: 'waterQualityStandard' },
  437. { label: '负责人', key: 'principal' },
  438. { label: '联系电话', key: 'contactPhone' },
  439. { label: '备注', key: 'remark', wide: true },
  440. ],
  441. ENGINEERING_FACILITY: ENGINEERING_FACILITY_FIELD_ROWS,
  442. DRAINAGE_GATE: DRAINAGE_FACILITY_FIELD_ROWS,
  443. DRAINAGE_STORAGE: DRAINAGE_FACILITY_FIELD_ROWS,
  444. // 票 05:用水户字段按后端 water_user_info 实体登记,不借用水厂/泵站/工程设施词表。
  445. WATER_USER: [
  446. { label: '用水户类型', key: 'userType' },
  447. { label: '用水地址', key: 'address', wide: true },
  448. { label: '联系人', key: 'contactPerson' },
  449. { label: '联系电话', key: 'contactPhone' },
  450. { label: '水表编号', key: 'meterNumber' },
  451. { label: '初始读数', key: 'initialReading' },
  452. { label: '当前读数', key: 'currentReading' },
  453. { label: '年用水量', key: 'annualWaterConsumption' },
  454. { label: '备注', key: 'remark', wide: true },
  455. ],
  456. // 票 06:消火栓字段按后端 water_fire_hydrant_info 实体登记;类型用字典词表,不发明字段。
  457. WATER_FIRE_HYDRANT: [
  458. { label: '消火栓类型', key: 'hydrantType', format: (v) => codedText(v, HYDRANT_TYPE_TEXT) },
  459. { label: '型号', key: 'model' },
  460. { label: '进水主管管径', key: 'inletPipeDiameter' },
  461. { label: '出水口规格', key: 'outletSpec' },
  462. { label: '产权单位', key: 'ownershipUnit' },
  463. { label: '管护单位', key: 'maintenanceUnit' },
  464. { label: '责任人', key: 'principal' },
  465. { label: '联系电话', key: 'contactPhone' },
  466. { label: '位置描述', key: 'location', wide: true },
  467. { label: '备注', key: 'remark', wide: true },
  468. ],
  469. PUMP_STATION: [
  470. { label: '泵站类型', key: 'stationType', format: (v) => pumpStationTypeText(v) },
  471. { label: '水泵数量', key: 'pumpCount' },
  472. { label: '设计流量', key: 'designFlow' },
  473. { label: '设计扬程', key: 'designHead' },
  474. { label: '装机功率', key: 'powerCapacity' },
  475. { label: '投产日期', key: 'commissionDate' },
  476. { label: '负责人', key: 'principal' },
  477. { label: '联系电话', key: 'contactPhone' },
  478. { label: '备注', key: 'remark', wide: true },
  479. ],
  480. EMERGENCY_RESOURCE: [
  481. { label: '设备类型', key: 'equipmentTypeId' },
  482. { label: '型号', key: 'model' },
  483. { label: '规格', key: 'specification', wide: true },
  484. { label: '制造商', key: 'manufacturer' },
  485. { label: '资产价值', key: 'assetValue' },
  486. { label: '预计使用年限', key: 'useLifeYears' },
  487. { label: '安装时间', key: 'installTime' },
  488. { label: '维护人', key: 'maintainer' },
  489. { label: '维护电话', key: 'maintainerPhone' },
  490. { label: '权属单位', key: 'ownershipUnit' },
  491. { label: '设备图片', key: 'image' },
  492. { label: '备注', key: 'remark', wide: true },
  493. ],
  494. // 隐患类型/等级/来源是业务库字典码(0/1/2 不能直接上屏);
  495. // 三个关联对象是后端下发的业务引用(票 06),不再有 equipmentId/networkId/workOrderId。
  496. // 隐患图片不进明细:它以附件区(缩略图 + 放大)出现在业务详情末尾。
  497. HAZARD: [
  498. { label: '隐患类型', key: 'hazardType', dict: DICT_TYPES.hazardType },
  499. { label: '隐患等级', key: 'level', dict: DICT_TYPES.hazardLevel },
  500. { label: '来源', key: 'source', dict: DICT_TYPES.hazardSource },
  501. { label: '隐患描述', key: 'description', wide: true },
  502. { label: '关联管网', key: 'network' },
  503. { label: '关联设备', key: 'equipment' },
  504. { label: '关联工单', key: 'workOrder' },
  505. { label: '报告单位', key: 'reportUnit' },
  506. { label: '报告时间', key: 'reportTime' },
  507. { label: '整改方案', key: 'rectifyPlan', wide: true },
  508. { label: '整改期限', key: 'rectifyDeadline' },
  509. { label: '整改人', key: 'rectifyPerson' },
  510. { label: '整改反馈', key: 'rectifyFeedback', wide: true },
  511. { label: '备注', key: 'remark', wide: true },
  512. ],
  513. // 风险等级与风险颜色不再进明细:已由抬头那一个「风险等级」徽标承担(规格 §5)。
  514. // 风险因素改成键值网格,不再把一整串 JSON 打在页面上。
  515. PROTECTION_TARGET: [
  516. { label: '关联管网', key: 'network' },
  517. { label: '风险分值', key: 'riskScore' },
  518. { label: '评估模型', key: 'assessmentModel' },
  519. { label: '评估时间', key: 'assessmentTime' },
  520. { label: '风险因素', key: 'riskFactors', wide: true, pairs: true },
  521. { label: '危险源', key: 'hazardSources', wide: true },
  522. { label: '备注', key: 'remark', wide: true },
  523. ],
  524. }
  525. /** 读数 + 单位(认不出的值留给 field() 变占位符,不拼半截 "— m")。 */
  526. function withUnitText(value, unit) {
  527. if (value === null || value === undefined || String(value).trim() === '') return ''
  528. return unit ? `${value} ${unit}` : String(value)
  529. }
  530. function undefinedEnumText(raw) {
  531. const value = text(raw)
  532. if (!value || /\p{Script=Han}/u.test(value) && !/\p{Script=Latin}/u.test(value)) return value
  533. return /^[+-]?\d+(?:\.\d+)?$/.test(value) ? `未定义(原值:${value})` : '未知'
  534. }
  535. /**
  536. * 风险等级:业务库 risk_level 字典是唯一权威(0 重大 / 1 较大 / 2 一般 / 3 低)。
  537. *
  538. * 字典没取到时回**原码**,不再写「未定义(原值:N)」——那是把「字典还没到」
  539. * 说成「后端给了个没定义的枚举」。high/medium/low 是风险评估服务的历史发布形状,
  540. * 保留映射(它不是数字码,字典里没有对应行);已发布中文原样透传。
  541. */
  542. const RISK_LEVEL_LEGACY_TEXT = { high: '高风险', medium: '中风险', low: '低风险' }
  543. function riskLevelText(raw) {
  544. const value = text(raw)
  545. if (!value) return ''
  546. return dictLabel(DICT_TYPES.riskLevel, value) || RISK_LEVEL_LEGACY_TEXT[value] || value
  547. }
  548. /** 风险颜色码 → 中文(红/橙/黄/蓝);字典没取到就回原码。 */
  549. function riskColorText(raw) {
  550. const value = text(raw)
  551. if (!value) return ''
  552. return dictLabel(DICT_TYPES.riskColor, value) || value
  553. }
  554. /** 风险颜色码 → 语义色键(0 红 / 1 橙 / 2 黄 / 3 蓝);认不出回中性。 */
  555. const RISK_TONE_BY_CODE = { 0: 'risk-1', 1: 'risk-2', 2: 'risk-3', 3: 'risk-4' }
  556. function riskTone(value) {
  557. return RISK_TONE_BY_CODE[text(value)] || 'neutral'
  558. }
  559. /**
  560. * 风险因素 → 键值对(规格 §2「风险因素从字符串改为键值组结构」)。
  561. *
  562. * 后端既可能下发对象,也可能下发 JSON 字符串;解析失败(非法 JSON、纯文本)回 null,
  563. * 由调用方原样展示 —— 不吞掉内容,也不假装解析成功。
  564. */
  565. function riskFactorPairs(value) {
  566. if (value === null || value === undefined || value === '') return null
  567. let source = value
  568. if (typeof source === 'string') {
  569. try {
  570. source = JSON.parse(source)
  571. } catch {
  572. return null
  573. }
  574. }
  575. if (Array.isArray(source)) {
  576. const pairs = source.map((item, index) => [`${index + 1}`, text(item)]).filter(([, label]) => label)
  577. return pairs.length ? pairs : null
  578. }
  579. if (source && typeof source === 'object') {
  580. const pairs = Object.entries(source).map(([key, item]) => [key, text(item)]).filter(([, label]) => label)
  581. return pairs.length ? pairs : null
  582. }
  583. return null
  584. }
  585. /** 业务库字典 → 中文;字典没取到就回原码(不编「未知」,也不回显英文枚举)。 */
  586. function dictOrCode(type, value) {
  587. const code = text(value)
  588. if (!code) return ''
  589. return dictLabel(type, code) || code
  590. }
  591. /** 关联设备的业务引用(规格 §5):name + code,有 code 才能定位。 */
  592. function equipmentReference(a) {
  593. const equipment = a.equipment
  594. if (!equipment || typeof equipment !== 'object') return null
  595. const code = text(equipment.code)
  596. const name = text(equipment.name)
  597. if (!code && !name) return null
  598. return { label: name && code ? `${name}(${code})` : name || code, code }
  599. }
  600. /**
  601. * 关联工单的引用(规格 §5):后端只下发 code —— `work_order` 表没有名称列,
  602. * 编一个名称等于造假,所以显示的就是工单号本身。
  603. */
  604. function workOrderReference(a) {
  605. const order = a.workOrder
  606. if (!order || typeof order !== 'object') return null
  607. const code = text(order.code)
  608. return code ? { label: code, code } : null
  609. }
  610. /**
  611. * 关联管网的业务引用(规格 §5):只认后端下发的 name + code。
  612. * 只有内部 id 时不渲染 id —— 字段表据此显示「未提供」。
  613. */
  614. function networkReference(a) {
  615. const network = a.network
  616. if (!network || typeof network !== 'object') return null
  617. const code = text(network.code)
  618. const name = text(network.name)
  619. if (!code && !name) return null
  620. return { label: name && code ? `${name}(${code})` : name || code, code }
  621. }
  622. /** 详情里按完整时间戳展示的字段。 */
  623. const ASSET_TIMESTAMP_KEYS = new Set(['reportTime', 'assessmentTime', 'installTime'])
  624. /** 纯日期字段:只到年月日,后端若序列化成当天 00:00:00 也不补时刻。 */
  625. const ASSET_DATE_KEYS = new Set(['buildDate', 'commissionDate', 'rectifyDeadline'])
  626. function formatAssetDate(value) {
  627. const raw = text(value)
  628. return /^\d{4}-\d{2}-\d{2}/.test(raw) ? raw.slice(0, 10) : raw
  629. }
  630. /**
  631. * 资产详情的时刻(维护者 2026-12-01 时间显示规则):粒度看值的实际内容。
  632. * 落在 `00:00:00` 这个占位时刻上的一律只显示日期,不造一个假时刻;
  633. * 其它仍然是 `yyyy-MM-dd HH:mm:ss`。
  634. */
  635. function formatAssetTime(value) {
  636. const full = formatEventTime(value)
  637. return / 00:00:00$/.test(full) ? full.slice(0, 10) : full
  638. }
  639. /** 原始属性 → 展示值的唯一归一化层:摘要与明细共用;行内 format 只做单字段专门词表。 */
  640. function assetFieldValue(key, a) {
  641. if (key === 'equipmentIds' || key === 'equipmentId') {
  642. const codes = Array.isArray(a.devices) ? a.devices.map((item) => text(item.code)).filter(Boolean) : []
  643. return codes.join('、') || '未提供'
  644. }
  645. if (['networkId', 'workOrderId', 'equipmentTypeId'].includes(key)) return '未提供'
  646. if (key === 'riskLevel') return riskLevelText(a[key])
  647. if (key === 'riskColor') return riskColorText(a[key])
  648. if (ASSET_TIMESTAMP_KEYS.has(key)) return formatAssetTime(a[key])
  649. if (ASSET_DATE_KEYS.has(key)) return formatAssetDate(a[key])
  650. return a[key]
  651. }
  652. function assetFields(category, a) {
  653. const rows = category === 'PIPE_NETWORK' ? pipesFields(a) : ASSET_FIELD_ROWS[category] || []
  654. return rows.map((row) => {
  655. // 码值字段:业务库字典是唯一权威,没取到就回原码(不回显 0/1/2 之外的编造词)。
  656. if (row.dict) return field(row.label, dictOrCode(row.dict, a[row.key]), row.wide === true)
  657. // 关联管网:后端下发 name + code 时显示「名称(编码)」并给聚焦入口;否则如实「未提供」。
  658. if (row.key === 'network') {
  659. const ref = networkReference(a)
  660. if (!ref) return field(row.label, '未提供')
  661. return field(row.label, ref.label, false, { action: ref.code ? { kind: 'focus-network', code: ref.code } : null })
  662. }
  663. // 关联设备:显示「名称(编码)」,有编码才能定位。
  664. if (row.key === 'equipment') {
  665. const ref = equipmentReference(a)
  666. if (!ref) return field(row.label, '未提供')
  667. return field(row.label, ref.label, false, { action: ref.code ? { kind: 'locate-equipment', code: ref.code } : null })
  668. }
  669. // 关联工单:显示工单号并可打开卡片。
  670. if (row.key === 'workOrder') {
  671. const ref = workOrderReference(a)
  672. if (!ref) return field(row.label, '未提供')
  673. return field(row.label, ref.label, false, { action: { kind: 'open-work-order', code: ref.code } })
  674. }
  675. // 风险因素:能解析成键值就出网格;非法 JSON / 纯文本原样展示。
  676. if (row.pairs) {
  677. const pairs = riskFactorPairs(a[row.key])
  678. return pairs ? field(row.label, '', row.wide === true, { pairs }) : field(row.label, a[row.key], row.wide === true)
  679. }
  680. // 单位一律由 `unitOf(category, key)` 给:同一字段名在不同设施里量纲可能不同。
  681. const raw = row.format ? row.format(a[row.key]) : withUnitText(assetFieldValue(row.key, a), unitOf(category, row.key))
  682. // always 行(如非排水管的二级分类)保留占位;其余缺值由 compactSections 剔除。
  683. const item = field(row.label, raw, row.wide === true)
  684. if (row.always) {
  685. item.always = true
  686. if (row.invalidNote && item.value === PLACEHOLDER) item.note = row.invalidNote
  687. }
  688. return item
  689. })
  690. }
  691. function coordinatesText(value) {
  692. if (!value || typeof value !== 'object') return ''
  693. const start = [value.longitude, value.latitude].filter((item) => item !== null && item !== undefined).join(', ')
  694. const end = [value.endLongitude, value.endLatitude].filter((item) => item !== null && item !== undefined).join(', ')
  695. return [start, end].filter(Boolean).join(' → ')
  696. }
  697. /**
  698. * 事件等级 → 色键 + 文字。
  699. *
  700. * **三种输入形状都要认**(维护者 2026-10-29 走查:「等级明明能拿到却标成未知」):
  701. * · 后端原始事件行:`level: 1`(数字);
  702. * · 列表行视图 `eventRowView`:`level: { tone, label }`(已翻译过的对象);
  703. * · 移动端预警/报警详情:`warningLevel / alarmLevel`(数字或等级名)。
  704. * 详情面板首屏先用列表行 prefill、随后被远端覆盖,两条路都要能读出同一个等级 ——
  705. * 早先只认数字,prefill 的等级对象就被判成"等级未知"。
  706. */
  707. /** 「二级预警」「3级」「四级」→ 1..4;认不出回 null(不猜等级)。 */
  708. function numericLevelOf(value) {
  709. const text = value === null || value === undefined ? '' : String(value).trim()
  710. if (!text) return null
  711. const arabic = /([1-4])\s*级/.exec(text)
  712. if (arabic) return Number(arabic[1])
  713. const cn = /([一二三四])\s*级/.exec(text)
  714. if (cn) return { 一: 1, 二: 2, 三: 3, 四: 4 }[cn[1]]
  715. return null
  716. }
  717. function eventLevelFrom(source) {
  718. const raw = source || {}
  719. // 已经翻译过的对象:原样沿用(这正是列表与详情一致的结构性保证)。
  720. const tagged = raw.level
  721. if (tagged && typeof tagged === 'object' && tagged.label) {
  722. return { tone: tagged.tone || DEFAULT_TONE, label: tagged.label }
  723. }
  724. // 移动端字段名与等级名(如 "二级预警")走桶解析;认不出回「等级未知」。
  725. const direct = raw.level ?? raw.warningLevel ?? raw.alarmLevel
  726. if (typeof direct === 'number') return eventLevelTag(direct)
  727. // 中文等级名(后端会下发「二级预警」「三级报警」这类人话)→ 阿拉伯数字。
  728. const numeric = numericLevelOf(direct)
  729. if (numeric !== null) return eventLevelTag(numeric)
  730. const fromBucket = eventLevelFromBucket(raw.levelCode ?? raw.levelColor ?? direct, direct)
  731. return eventLevelTag(fromBucket)
  732. }
  733. /** BusinessCockpitEventAdapter.alarmStatus:0→UNHANDLED,1→HANDLED;核验态不参与。 */
  734. function mobileAlarmStatus(value) {
  735. return typeof value === 'number' ? value === 0 ? 'UNHANDLED' : value === 1 ? 'HANDLED' : 'UNKNOWN' : value
  736. }
  737. function normalizeEvent(identity, source) {
  738. const envelope = source && source.basicInfo ? source : {}
  739. const basic = envelope.basicInfo && typeof envelope.basicInfo === 'object' ? envelope.basicInfo : source
  740. source = { ...basic,
  741. disposalHistory: envelope.disposalHistory || basic.disposalHistory,
  742. attachmentList: envelope.attachmentList || basic.attachmentList,
  743. alarmList: envelope.alarmList || basic.alarmList,
  744. relations: envelope.relations || basic.relations,
  745. gisLocation: envelope.gisLocation || basic.gisLocation,
  746. }
  747. const family = String(identity.family || source.family || source.eventFamily || (source.alarmId || source.alarmNo ? 'ALARM' : source.warningId || source.warningNo ? 'WARNING' : '')).toUpperCase()
  748. const level = eventLevelFrom(source)
  749. const rawStatus = source.status || source.state || mobileAlarmStatus(source.alarmStatus) || source.statusName || source.stateName || source.statusText
  750. const status = eventStatusText(rawStatus, family)
  751. // 状态色走状态词表(待接收/已接收黄、处置中蓝、已处置紫、已解除绿),不再借用等级色。
  752. const statusTone = statusDisplayTone(family, rawStatus)
  753. const name = eventNameText(source.name || source.warningName || source.alarmName || source.eventName || source.deviceName || source.title) || '事件名称未提供'
  754. // 列表 prefill 的 code 是旧内部请求键,只有 codeText 才是业务码;缺码不回退身份。
  755. const listCode = source.codeText === '编码未提供' ? '' : source.codeText
  756. const displayCode = text(source.codeText !== undefined ? listCode : source.code || source.eventCode || source.warningNo || source.alarmNo)
  757. // 报警族的处置记录/附件在不同后端版本字段不一,这里做兼容收集(预警族字段不变)。
  758. const auditRecords = collectAuditRecords(source)
  759. const attachments = collectAttachmentItems(source)
  760. const relations = Array.isArray(source.relations) ? source.relations : eventRelations(family, source)
  761. return {
  762. ...identity,
  763. name,
  764. displayCode,
  765. title: name,
  766. kindLabel: family === 'ALARM' ? '报警' : family === 'WARNING' ? '预警' : '事件',
  767. family,
  768. statusText: status,
  769. tone: statusTone || 'neutral',
  770. // 抬头直接显示等级(与卡片同一张词表、同一套色),不再只写在字段里。
  771. levelLabel: level.label,
  772. levelTone: level.tone,
  773. raw: source,
  774. // 等级已移到状态徽标右侧;摘要卡不再重复(保留当前值 / 发生时间)。
  775. summary: summaryItems([['当前值', withUnit(source.value ?? source.actualValue, source.unit || source.warningUnit)], ['发生时间', formatEventTime(source.eventTime || source.createTime)]]),
  776. tabs: family === 'WARNING'
  777. ? [tab('overview', '预警信息'), tab('records', '处置记录'), tab('relations', '关联信息'), tab('attachments', '附件')]
  778. : [tab('overview', '报警信息'), tab('relations', '关联信息'), tab('records', '处置记录'), tab('attachments', '附件')],
  779. relatedAlarms: Array.isArray(source.alarmList) ? source.alarmList.map(relatedAlarm) : [],
  780. stage: eventStage(family, rawStatus, auditRecords),
  781. // 报警的「相关人员」即使后端暂未回填姓名也要有指标位;预警沿用原口径。
  782. people: family === 'ALARM'
  783. ? alarmPeople(source, auditRecords)
  784. : peopleItems([['发布人', source.publisherName], ['处置人', source.handlerName], ['核验人', source.reviewerName]]),
  785. devices: deviceItems(source),
  786. relations,
  787. attachments,
  788. records: recordItems(auditRecords),
  789. sections: compactSections([
  790. // 等级只出现在摘要卡片那一处(带色),这里不再重复一遍纯文字等级。
  791. // 状态在抬头与摘要卡各有一次,这里不再重复(否则事件编码被挤到换行)。
  792. section('事件摘要', [field('事件编码', displayCode || '未提供', true), field('发生时间', formatEventTime(source.eventTime || source.createTime))]),
  793. section('监测读数', [
  794. field('指标', eventTypeText(source.type || source.warningType || source.warningCode, source.typeName || source.warningTypeName)),
  795. // 读数与阈值都带单位(维护者 2026-10-29:数值型指标必须有单位提示)。
  796. field('实际值', withUnit(source.value ?? source.actualValue, source.unit || source.warningUnit)),
  797. field('阈值', threshold(source)),
  798. field('超出幅度', withUnit(source.deviationRatio, '%')),
  799. ]),
  800. section('处置与附件', [
  801. field('处置记录', listCount(auditRecords, '条')),
  802. field('关联报警', listCount(source.alarmList, '条')),
  803. field('附件', listCount(attachments, '项')),
  804. field('督办记录', listCount(source.supervisionList, '条')),
  805. ]),
  806. ]),
  807. }
  808. }
  809. function alarmPeople(source, records) {
  810. const latest = latestOperator(records)
  811. const handler = text(source.receiveUserName || source.handlerName || source.receiverName || latest)
  812. const verifier = text(source.verifyUserName || source.reviewerName)
  813. return [
  814. { role: '处置人', name: handler || '未提供' },
  815. { role: '核验人', name: verifier || '未提供' },
  816. ]
  817. }
  818. function latestOperator(records) {
  819. const list = Array.isArray(records) ? records : records ? [records] : []
  820. const hit = list.find((item) => item && text(item.operatorName || item.operator))
  821. return hit ? text(hit.operatorName || hit.operator) : ''
  822. }
  823. /** 关联信息:只列当前数据真实带出的设备 / 预警 / 报警 / 工单,不猜不补。 */
  824. function eventRelations(family, source) {
  825. const list = []
  826. const device = deviceRelation(source)
  827. if (device) list.push(device)
  828. if (family === 'WARNING' && Array.isArray(source.alarmList)) {
  829. source.alarmList.map(relatedAlarm).forEach((item) => {
  830. const relation = alarmRelation(item)
  831. if (relation) list.push(relation)
  832. })
  833. }
  834. if (family === 'ALARM') {
  835. const warning = warningRelation(source)
  836. if (warning) list.push(warning)
  837. }
  838. const workOrder = workOrderRelation(source)
  839. if (workOrder) list.push(workOrder)
  840. return list
  841. }
  842. function deviceRelation(source) {
  843. const name = text(source.deviceName || source.monitoringPointName)
  844. const code = text(source.deviceCode || source.monitoringPointCode)
  845. if (!name && !code) return null
  846. return {
  847. kind: 'device',
  848. kindLabel: '设备',
  849. code,
  850. name: name || code,
  851. status: '',
  852. meta: [text(source.deviceTypeName), text(source.deviceLocation || source.location || source.address)].filter(Boolean).join(' · '),
  853. locateCode: code,
  854. }
  855. }
  856. function alarmRelation(item) {
  857. const code = text(item && (item.code || item.alarmNo))
  858. const name = text(item && (item.name || item.alarmContent || item.alarmName))
  859. if (!code && !name) return null
  860. return {
  861. kind: 'alarm',
  862. kindLabel: '报警',
  863. code,
  864. name: name || code,
  865. status: text(item && (item.status || item.alarmStatusName)) || '',
  866. meta: '查看报警详情',
  867. detailId: code,
  868. }
  869. }
  870. function warningRelation(source) {
  871. // warning_code 是报警类型;没有真实 warning_no/warning_id 时不冒充关联预警。
  872. const code = text(source.warningNo || source.warningId)
  873. if (!code) return null
  874. const name = text(source.warningName || source.warningTypeName || source.warningContent)
  875. return {
  876. kind: 'warning',
  877. kindLabel: '预警',
  878. code,
  879. name: name || code,
  880. status: eventStatusText(source.warningStatus || source.status, 'WARNING'),
  881. meta: '查看预警详情',
  882. detailId: code,
  883. }
  884. }
  885. function workOrderRelation(source) {
  886. const code = text(source.orderNo || source.workOrderCode || source.workOrderNo)
  887. const name = text(source.orderDesc || source.workOrderDesc || source.orderTitle)
  888. if (!code && !name) return null
  889. return {
  890. kind: 'work-order',
  891. kindLabel: '工单',
  892. code,
  893. name: name || code,
  894. status: text(source.orderStatusName || source.workOrderStateName),
  895. meta: '',
  896. }
  897. }
  898. function normalizeWorkOrder(identity, source) {
  899. const detailSource = source && source.order ? source : { order: source, logs: source.logs || [] }
  900. const raw = { ...(detailSource.order || {}) }
  901. if (raw.stateCode === undefined && raw.orderStatus === undefined && raw.status !== undefined) raw.stateCode = Number(raw.status)
  902. const order = toWorkOrder(raw)
  903. const timelineRaw = detailSource.logs || source.timeline || source.timelineEntries || source.records
  904. let track = null
  905. if (Array.isArray(timelineRaw)) {
  906. track = trackOf(toWorkOrderTimeline({ workOrder: raw, timelineEntries: timelineRaw.map((item) => ({
  907. operationName: item.operationName || item.operationType || item.action,
  908. operationDesc: item.operationDesc || item.remark || item.content,
  909. operatorName: item.operatorName || item.operator || item.createByName,
  910. operatedAt: item.operatedAt || item.operationTime || item.createTime,
  911. stateCode: item.stateCode ?? item.orderStatus,
  912. stateName: item.stateName || item.orderStatusName,
  913. attachImages: item.attachImages,
  914. })) }))
  915. } else if (source.workOrder && Array.isArray(source.timelineEntries)) {
  916. track = trackOf(toWorkOrderTimeline(source))
  917. }
  918. const stateText = order.stateName || workOrderStateName(order.stateCode)
  919. const relations = Array.isArray(source.relations) && source.relations.length
  920. ? source.relations
  921. : [deviceRelation(order)].filter(Boolean)
  922. return {
  923. ...identity,
  924. name: order.description || order.code || '工单名称未提供',
  925. title: order.description || order.code || '工单名称未提供',
  926. displayCode: order.code,
  927. kindLabel: '工单',
  928. statusText: stateText,
  929. tone: workOrderTone(order.stateCode),
  930. // 优先级作为等级徽标放在状态右侧,与报警/预警的等级徽标同一位置。
  931. levelLabel: order.orderLevel === null ? '' : `优先级 ${orderLevelText(order.orderLevel)}`,
  932. levelTone: orderLevelTone(order.orderLevel),
  933. order,
  934. track,
  935. raw: source,
  936. // 抬头已有状态/优先级徽标;顶部指标卡不再重复工单号或优先级(维护者 2026-12-01)。
  937. summary: [],
  938. tabs: [tab('overview', '工单信息'), tab('flow', '处理流程'), tab('relations', '关联信息'), tab('attachments', '附件')],
  939. stage: workOrderStage(order.stateCode),
  940. // 相关人员与「处置内容」里的处置人/核验人重复;工单详情不再单独出这一栏。
  941. people: [],
  942. // 设备信息统一在「关联信息」页签,概览不再重复一份。
  943. devices: order.deviceCode || order.deviceName ? [{ name: order.deviceName || order.deviceCode, code: order.deviceCode, type: order.deviceTypeName, location: order.deviceLocation }] : [],
  944. relations,
  945. // 附件页签保留完整清单;处理流程页签另外按维修前/后分组展示。
  946. attachments: attachmentItems([
  947. ...order.maintenanceBeforeImages,
  948. ...order.maintenanceAfterImages,
  949. ...timelineAttachments(timelineRaw),
  950. ]),
  951. maintenanceImages: [
  952. { key: 'before', label: '维修前', images: order.maintenanceBeforeImages },
  953. { key: 'after', label: '维修后', images: order.maintenanceAfterImages },
  954. ].filter((group) => group.images.length),
  955. records: recordItems(timelineRaw),
  956. sections: compactSections([
  957. // 工单号在摘要;状态和优先级只由左上角徽标展示。
  958. section('工单摘要', [field('工单号', order.code || '未提供')]),
  959. // 与设备详情同口径:ISO 带时区串统一 yyyy-MM-dd HH:mm:ss(维护者 2026-11-23)。
  960. section('时间信息', [field('创建时间', formatEventTime(order.createTime)), field('计划完成', formatEventTime(order.planFinishTime)), field('实际完成', formatEventTime(order.realFinishTime))]),
  961. section('处置内容', [field('处置人', order.receiveUserName), field('核验人', order.verifyUserName), field('故障描述', order.description, true), field('处置结果', order.repairResult, true)]),
  962. ]),
  963. }
  964. }
  965. /** 工单优先级码值(0 紧急 / 1 一般 / 2 低)→ 中文;认不出回码。 */
  966. function orderLevelText(value) {
  967. const code = value === null || value === undefined ? '' : String(value).trim()
  968. if (!code) return ''
  969. return { '0': '紧急', '1': '一般', '2': '低' }[code] || code
  970. }
  971. /** 工单优先级色:0 紧急红 / 1 一般黄 / 2 低蓝;认不出回中性。 */
  972. function orderLevelTone(value) {
  973. return { '0': 'lv1', '1': 'lv2', '2': 'lv3' }[String(value ?? '').trim()] || 'neutral'
  974. }
  975. function tab(key, label) { return { key, label } }
  976. function relatedAlarm(item) { const code = text(item.code || item.alarmNo || item.alarm_no || item.alarmCode || item.alarmId || item.alarm_id || item.id); const name = item.alarmName || item.alarm_name || item.content || item.alarmContent || item.alarm_content || item.deviceName || item.device_name || item.title || (code ? `报警 ${code}` : '关联报警'); return { id: item.alarmId || item.alarm_id || item.id || '', code, name, status: eventStatusText(mobileAlarmStatus(item.alarmStatus ?? item.alarm_status) || item.status || item.auditStatusName || item.alarmStatusName, 'ALARM') } }
  977. function summaryItems(entries) { return entries.filter(([,value]) => value !== null && value !== undefined && String(value).trim() !== '').map(([label,value,tone]) => ({ label, value: String(value), tone: tone || '' })) }
  978. function peopleItems(entries) { return entries.filter(([,name]) => name).map(([role,name]) => ({ role, name: String(name) })) }
  979. function deviceItems(source) {
  980. const name = source.deviceName || source.monitoringPointName || ''
  981. const code = source.deviceCode || source.monitoringPointCode || ''
  982. return name || code ? [{ name: name || code, code, location: source.location || source.address || '' }] : []
  983. }
  984. function attachmentItems(value) {
  985. const list = Array.isArray(value) ? value : value ? String(value).split(',') : []
  986. return list.flatMap((item) => {
  987. if (!item) return []
  988. if (typeof item === 'object') return [{ name: item.attachmentName || item.fileName || item.name || '附件', url: item.attachmentUrl || item.url || '', type: item.attachmentType || item.type || '' }]
  989. const url = String(item).trim(); return url ? [{ name: url.split('/').pop() || '附件', url, type: '' }] : []
  990. })
  991. }
  992. function recordItems(value) {
  993. return (Array.isArray(value) ? value : []).map((item) => ({
  994. title: item.operationName || item.operationType || item.action || item.disposalTypeName || item.disposalStatus || '处置记录',
  995. time: formatEventTime(item.operatedAt || item.operationTime || item.createTime || item.create_time || item.disposalTime || ''),
  996. operator: item.operatorName || item.operator || item.createByName || item.disposal_user_name || '',
  997. description: item.operationDesc || item.remark || item.content || item.disposal_content || item.disposalContent || '',
  998. }))
  999. }
  1000. /** 处置记录来源兼容:预警 disposalHistory/logs;报警可能来自 audit 列表、工单时间线或最近操作。 */
  1001. function collectAuditRecords(source) {
  1002. const list = []
  1003. const push = (value) => {
  1004. if (Array.isArray(value)) list.push(...value.filter(Boolean))
  1005. else if (value && typeof value === 'object') list.push(value)
  1006. }
  1007. push(source.disposalHistory)
  1008. push(source.logs)
  1009. push(source.timelineEntries)
  1010. push(source.auditList)
  1011. push(source.auditRecords)
  1012. push(source.handleRecords)
  1013. push(source.records)
  1014. const order = source.workOrderDetail
  1015. if (order && typeof order === 'object') { push(order.timelineEntries); push(order.logs) }
  1016. if (!list.length && (source.latestOperation || source.latestOperationTime)) {
  1017. list.push({ operationName: source.latestOperation || '处置记录', operatedAt: source.latestOperationTime })
  1018. }
  1019. return list
  1020. }
  1021. /** 附件来源兼容:预警 attachmentList;报警可能来自 attachList/attachments/equipmentImage 或关联工单维修图片。 */
  1022. function collectAttachmentItems(source) {
  1023. const raw = []
  1024. const push = (value) => {
  1025. if (Array.isArray(value)) raw.push(...value)
  1026. else if (typeof value === 'string' && value.trim()) raw.push(value)
  1027. }
  1028. push(source.attachmentList)
  1029. push(source.attachList)
  1030. push(source.attachments)
  1031. push(source.equipmentImage)
  1032. const order = source.workOrderDetail
  1033. if (order && typeof order === 'object') { push(order.maintenanceBeforeImages); push(order.maintenanceAfterImages); push(order.attachmentList) }
  1034. return attachmentItems(raw)
  1035. }
  1036. function eventStage(family, status, records) {
  1037. const labels = family === 'ALARM' ? ['产生', '确认', '处置', '关闭'] : ['发布', '接收', '处置', '核验', '解除']
  1038. // status 既可能是后端机器码(CLOSED),也可能是已本地化的中文(已解除);两者都要落到正确阶段。
  1039. const normalized = String(status || '').toUpperCase()
  1040. const terminal = /RESOLV|CLEAR|CLOSE|解除|关闭/.test(normalized)
  1041. const processing = /PROCESS|HANDL|处置中|已处置|处置/.test(normalized) && !/UNHANDL/.test(normalized)
  1042. const received = /RECEIV|CONFIRM|接收/.test(normalized)
  1043. let active = terminal ? labels.length - 1
  1044. : processing ? Math.min(2, labels.length - 1)
  1045. : received ? 1 : 0
  1046. // 记录只代表「至少推进到处置」,不能把已是终态(解除/关闭)的流程往回拉。
  1047. if (!terminal && Array.isArray(records) && records.length) active = Math.max(active, Math.min(2, labels.length - 1))
  1048. return labels.map((label,index) => ({ label, state: index < active ? 'done' : index === active ? 'active' : 'pending' }))
  1049. }
  1050. function workOrderStage(code) {
  1051. const labels = ['创建','派单','接单','处置','验收','完成']
  1052. const n = Number(code); const active = n === 6 ? 3 : n === 7 ? 0 : Number.isInteger(n) ? Math.max(0, Math.min(n, 5)) : 0
  1053. return labels.map((label,index) => ({ label, state: index < active ? 'done' : index === active ? 'active' : 'pending' }))
  1054. }
  1055. // 维修过程图片:后端既有 attachList 也有新暴露的 attachImages,两条都收进附件清单。
  1056. function timelineAttachments(records) { return (Array.isArray(records) ? records : []).flatMap((item) => item.attachList || item.attachments || item.attachImages || []) }
  1057. /**
  1058. * 缺值剔除:always 行例外 —— 业务上"这个设施没有该属性"时要显式显示占位符
  1059. * (维护者 2026-10-29:非排水管的二级分类显示「—」,不是把整行藏掉)。
  1060. */
  1061. function compactSections(sections) {
  1062. return sections
  1063. // 键值网格行(风险因素)没有单值文本,但它本身有内容,不能按占位符剔掉。
  1064. .map((group) => ({ ...group, fields: group.fields.filter((item) => item.always || item.pairs || item.value !== PLACEHOLDER) }))
  1065. .filter((group) => group.fields.length)
  1066. }
  1067. function section(title, fields) { return { title, fields } }
  1068. function field(label, value, wide = false, extra = {}) { return { label, value: display(value), wide, always: false, note: '', ...extra } }
  1069. function display(value) { return value === null || value === undefined || String(value).trim() === '' ? PLACEHOLDER : String(value) }
  1070. function text(value) { return value === null || value === undefined ? '' : String(value).trim() }
  1071. /**
  1072. * 读数 + 单位。三条纪律(维护者 2026-10-29):
  1073. * · 没值就整句不出(不拼半截 "— μS/cm");
  1074. * · **有值但后端没给单位**时如实标注「单位未发布」,不假装无单位是个读数;
  1075. * · 有单位则一律追加 —— 数值型指标不允许裸数字上屏。
  1076. */
  1077. function withUnit(value, unit) {
  1078. const hasValue = value !== null && value !== undefined && String(value).trim() !== ''
  1079. if (!hasValue) return ''
  1080. return unit ? `${value} ${unit}` : `${value}(单位未发布)`
  1081. }
  1082. function threshold(source) {
  1083. const min = source.thresholdMinValue ?? source.minValue
  1084. const max = source.thresholdMaxValue ?? source.maxValue
  1085. if (min === undefined && max === undefined) return ''
  1086. return withUnit(min !== undefined && max !== undefined ? `${min} ~ ${max}` : min !== undefined ? `≥ ${min}` : `≤ ${max}`, source.unit)
  1087. }
  1088. function positive(value, fallback) { const n = Number(value); return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback }
  1089. function nonNegative(value, fallback) { const n = Number(value); return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback }
  1090. function listCount(value, unit) { return Array.isArray(value) ? `${value.length} ${unit}` : '' }
  1091. function matchesId(row, id) { return !!row && [row.id, row.code, row.workOrderCode, row.warningNo, row.alarmId, row.facilityCode, row.resourceId].some((value) => String(value ?? '').trim() === id) }
  1092. function workOrderTone(code) { if (code === 5) return 'lv4'; if (code === 7) return 'lv1'; if (code === 6) return 'lv2'; return 'lv3' }