entityDetail.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /**
  2. * 统一实体详情领域边界(issue 65)。
  3. *
  4. * 列表只传 { kind, id };本模块负责身份校验、不同后端载荷的正规化和紧凑详情视图。
  5. * point/device 沿用既有详情链,不在此重复实现。
  6. */
  7. import { eventLevelFromBucket, eventLevelTag, eventStatusText, eventTypeText, eventNameText } from './eventList.js'
  8. import { DEFAULT_TONE } from './statusTones.js'
  9. import { toWorkOrder, toWorkOrderTimeline, workOrderStateName } from './workOrder.js'
  10. import { trackOf } from './workOrderTimeline.js'
  11. import { facilityStatusTone } from './facilityStatus.js'
  12. import { pumpStationTypeText } from './facilityTypeDict.js'
  13. export { facilityStatusTone } from './facilityStatus.js'
  14. export const ENTITY_DETAIL_KIND = Object.freeze({
  15. FACILITY: 'facility',
  16. EMERGENCY: 'emergency',
  17. EVENT: 'event',
  18. WORK_ORDER: 'work-order',
  19. })
  20. const KINDS = Object.freeze(Object.values(ENTITY_DETAIL_KIND))
  21. const PLACEHOLDER = '—'
  22. export function entityIdentity(input, fallbackKind = '') {
  23. const source = input && typeof input === 'object' ? input : {}
  24. const kind = String(source.kind || source.identityKind || fallbackKind || '').trim()
  25. const id = String(source.id ?? source.code ?? source.identityCode ?? '').trim()
  26. const category = String(source.category || source.identityCategory || '').trim().toUpperCase()
  27. const family = String(source.family || source.eventFamily || source.identityFamily || '').trim().toUpperCase()
  28. return { kind: KINDS.includes(kind) ? kind : '', id, category, family, valid: KINDS.includes(kind) && !!id }
  29. }
  30. export function sameEntity(left, right) {
  31. const a = entityIdentity(left)
  32. const b = entityIdentity(right)
  33. return a.valid && b.valid && a.kind === b.kind && a.id === b.id && a.category === b.category && a.family === b.family
  34. }
  35. /** AjaxResult / page / list 三种常见外形收成同一份有效载荷。 */
  36. export function unwrapEntityPayload(raw) {
  37. let value = raw
  38. if (value && typeof value === 'object' && typeof value.code === 'number') {
  39. if (value.code !== 200) return null
  40. value = value.data
  41. }
  42. if (value && typeof value === 'object' && value.data !== undefined && !Array.isArray(value.data)) {
  43. const keys = Object.keys(value)
  44. if (keys.every((key) => ['data', 'msg', 'message', 'success', 'timestamp'].includes(key))) value = value.data
  45. }
  46. return value
  47. }
  48. export function normalizePage(raw) {
  49. const payload = unwrapEntityPayload(raw)
  50. if (Array.isArray(payload)) return { rows: payload, page: 1, pageSize: payload.length, total: payload.length, totalPages: 1 }
  51. const source = payload && typeof payload === 'object' ? payload : {}
  52. const rows = [source.rows, source.records, source.list, source.items, source.content].find(Array.isArray) || []
  53. const paging = source.pagination && typeof source.pagination === 'object' ? source.pagination : source
  54. const page = positive(paging.page ?? paging.current ?? paging.pageNum, 1)
  55. const pageSize = positive(paging.pageSize ?? paging.size ?? paging.limit, rows.length)
  56. const total = nonNegative(paging.total, rows.length)
  57. const totalPages = positive(paging.totalPages ?? paging.pages, pageSize ? Math.ceil(total / pageSize) : 1)
  58. return { rows, page, pageSize, total, totalPages }
  59. }
  60. export function normalizeEntityDetail(identityInput, raw, prefill = null) {
  61. const identity = entityIdentity(identityInput)
  62. if (!identity.valid) return null
  63. const payload = unwrapEntityPayload(raw)
  64. const page = normalizePage(payload)
  65. let source = payload
  66. if (Array.isArray(payload)) source = payload.find((row) => matchesId(row, identity.id)) || null
  67. else if (payload && typeof payload === 'object' && page.rows.length) source = page.rows.find((row) => matchesId(row, identity.id)) || null
  68. const seed = prefill && typeof prefill === 'object' ? prefill : {}
  69. const publishedCodeKey = identity.kind === ENTITY_DETAIL_KIND.EVENT && source && source.codeText === undefined
  70. ? ['code', 'eventCode', 'warningNo', 'alarmNo'].find((key) => Object.hasOwn(source, key)) : ''
  71. const publishedCode = publishedCodeKey ? text(source[publishedCodeKey]) : undefined
  72. source = source && typeof source === 'object' ? { ...seed, ...source } : { ...seed }
  73. if (publishedCode !== undefined) source.codeText = publishedCode
  74. if (identity.kind === ENTITY_DETAIL_KIND.WORK_ORDER) return normalizeWorkOrder(identity, source)
  75. if (identity.kind === ENTITY_DETAIL_KIND.EVENT) return normalizeEvent(identity, source)
  76. return normalizeAsset(identity, source)
  77. }
  78. export function prefilledEntityDetail(identity, prefill) {
  79. return normalizeEntityDetail(identity, {}, prefill)
  80. }
  81. export function entityDetailView(detail) {
  82. const current = detail || {}
  83. return {
  84. title: current.title || current.name || '实体详情',
  85. // 副标题仅用业务编号;缺码不回退主键。
  86. subtitle: current.subtitle || [current.kindLabel, current.displayCode || '编码未提供'].filter(Boolean).join(' · '),
  87. tone: current.tone || 'neutral',
  88. status: current.statusText || '',
  89. // 等级与状态各有自己的语义色:等级沿用卡片那张四级词表,不与状态色混用。
  90. levelLabel: current.levelLabel || '',
  91. levelTone: current.levelTone || '',
  92. // 类别是身份而不是普通字段:抬头要能一眼看出是什么对象。
  93. categoryText: current.categoryText || '',
  94. summary: Array.isArray(current.summary) ? current.summary : [],
  95. tabs: Array.isArray(current.tabs) ? current.tabs : [],
  96. relatedAlarms: Array.isArray(current.relatedAlarms) ? current.relatedAlarms : [],
  97. stage: Array.isArray(current.stage) ? current.stage : [],
  98. sections: Array.isArray(current.sections) ? current.sections : [],
  99. people: Array.isArray(current.people) ? current.people : [],
  100. devices: Array.isArray(current.devices) ? current.devices : [],
  101. sectionMap: current.sectionMap && typeof current.sectionMap === 'object' ? current.sectionMap : {},
  102. attachments: Array.isArray(current.attachments) ? current.attachments : [],
  103. records: Array.isArray(current.records) ? current.records : [],
  104. track: current.track || null,
  105. }
  106. }
  107. function normalizeAsset(identity, source) {
  108. const emergency = identity.kind === ENTITY_DETAIL_KIND.EMERGENCY
  109. const category = text(source.category || identity.category).toUpperCase()
  110. const attributes = source.attributes && typeof source.attributes === 'object' ? source.attributes : {}
  111. const displayCode = text(source.code)
  112. const name = text(source.name || source.facilityName || source.resourceName || source.title) || (emergency ? '应急对象名称未提供' : '设施名称未提供')
  113. // 状态是码值时翻成中文(设施:0 正常 / 1 异常;后端若直接给人话则原样用)。
  114. const statusRaw = source.status ?? source.state ?? source.statusName ?? source.stateName
  115. const status = (category === 'PROTECTION_TARGET' ? riskLevelText(statusRaw) : emergency ? undefinedEnumText(statusRaw) : facilityStatusText(statusRaw)) || '状态未发布'
  116. const location = text(source.address || source.location || source.position)
  117. const fields = assetFields(category, attributes)
  118. return {
  119. ...identity, category, name, title: name, displayCode,
  120. kindLabel: emergency ? '应急对象' : '设施', statusText: status, tone: emergency ? 'neutral' : facilityStatusTone(source.status), raw: source,
  121. categoryText: facilityCategoryText(category),
  122. coordinates: source.coordinates || null,
  123. summary: assetSummary(category, attributes, status, location),
  124. tabs: [tab('overview', '基本信息'), tab('business', '业务详情'), tab('related', '关联信息')],
  125. people: assetPeople(attributes),
  126. devices: assetDevices(attributes),
  127. attachments: assetAttachments(attributes),
  128. sections: compactSections([
  129. section('基本信息', [field('设施编码', displayCode || '未提供'), field('设施类别', facilityCategoryText(category)), field('运行状态', status), field('数据更新时间', source.updatedAt)]),
  130. section('位置与归属', [field('位置描述', location, true), field('所属片区', source.districtName), field('坐标', coordinatesText(source.coordinates), true)]),
  131. section('业务详情', fields),
  132. ]),
  133. }
  134. }
  135. /**
  136. * 数值型指标的**单位登记**(维护者 2026-10-29「所有数值都要带单位」)。
  137. *
  138. * 只在这里写一次,摘要网格与业务明细都从这里取 —— 两处各写一份单位必然漂移
  139. * (已经踩过:摘要写「长度(米)」、明细写「长度」+ 单位,同一份数据两种长相)。
  140. * 单位来自后端领域注释,不由前端猜。
  141. */
  142. const COMMON_UNITS = {
  143. lengthMeters: '米',
  144. diameterMillimeters: '毫米',
  145. designCapacity: '万m³/d',
  146. currentCapacity: '万m³/d',
  147. designHead: 'm',
  148. storageCapacity: 'm³',
  149. pumpCount: '台',
  150. powerCapacity: 'kW',
  151. assetValue: '元',
  152. useLifeYears: '年',
  153. riskScore: '分',
  154. }
  155. /**
  156. * 同一字段名在不同设施里量纲不同:泵站设计流量是 m³/h,排水工程设施设计流量是 m³/s。
  157. * 所以单位必须**按类别**登记,"一个键一个单位"会张冠李戴。
  158. */
  159. const UNIT_BY_CATEGORY = {
  160. PIPE_NETWORK: {},
  161. WATER_PLANT: {},
  162. PUMP_STATION: { designFlow: 'm³/h' },
  163. ENGINEERING_FACILITY: { designFlow: 'm³/s' },
  164. MANHOLE: { manholeDepth: 'm' },
  165. EMERGENCY_RESOURCE: {},
  166. HAZARD: {},
  167. PROTECTION_TARGET: {},
  168. }
  169. /** 字段在该设施类别下的单位;没登记返回空串(纯文本字段)。 */
  170. function unitOf(category, key) {
  171. const scoped = UNIT_BY_CATEGORY[category] || {}
  172. return scoped[key] !== undefined ? scoped[key] : COMMON_UNITS[key] || ''
  173. }
  174. /** 摘要与明细共用的中文字段名(维护者 2026-10-29:一律中文、不带括注)。 */
  175. const SUMMARY_LABELS = {
  176. lengthMeters: '长度',
  177. diameterMillimeters: '管径',
  178. material: '材质',
  179. designCapacity: '设计能力',
  180. currentCapacity: '当前能力',
  181. treatmentProcess: '处理工艺',
  182. designFlow: '设计流量',
  183. designHead: '设计扬程',
  184. storageCapacity: '调蓄容积',
  185. pumpCount: '水泵数量',
  186. powerCapacity: '装机功率',
  187. assetValue: '资产价值',
  188. useLifeYears: '预计使用年限',
  189. riskScore: '风险分值',
  190. riskLevel: '风险等级',
  191. fmodel: '型号',
  192. model: '型号',
  193. specification: '规格',
  194. maintainer: '维护人',
  195. level: '等级',
  196. rectifyDeadline: '整改期限',
  197. rectifyPerson: '整改人',
  198. assessmentTime: '评估时间',
  199. facilityLevel: '设施等级',
  200. manholeDepth: '井深',
  201. manholeShape: '井形',
  202. ownershipUnit: '权属单位',
  203. }
  204. /** 同类字段在不同设施里的业务名不同(隐患等级 vs 设施等级),差异只在这里登记。 */
  205. const SUMMARY_LABELS_BY_CATEGORY = {
  206. HAZARD: { level: '隐患等级' },
  207. ENGINEERING_FACILITY: { facilityLevel: '设施等级' },
  208. }
  209. function assetSummary(category, a, status, location) {
  210. // 摘要只挑"一眼要看的读数",键与明细同源;单位统一由 METRIC_UNITS 提供。
  211. const byCategory = {
  212. WATER_PLANT: ['currentCapacity', 'designCapacity', 'treatmentProcess'],
  213. ENGINEERING_FACILITY: ['facilityLevel', 'designFlow', 'storageCapacity'],
  214. PUMP_STATION: ['pumpCount', 'designFlow', 'powerCapacity'],
  215. PIPE_NETWORK: ['lengthMeters', 'diameterMillimeters', 'material'],
  216. MANHOLE: ['manholeDepth', 'manholeShape', 'material', 'ownershipUnit'],
  217. HAZARD: ['level', 'rectifyDeadline', 'rectifyPerson'],
  218. PROTECTION_TARGET: ['riskLevel', 'riskScore', 'assessmentTime'],
  219. EMERGENCY_RESOURCE: ['model', 'specification', 'maintainer'],
  220. }
  221. const labels = { ...SUMMARY_LABELS, ...SUMMARY_LABELS_BY_CATEGORY[category] }
  222. const rows = (byCategory[category] || []).map((key) => {
  223. const unit = unitOf(category, key)
  224. const raw = assetFieldValue(key, a)
  225. // 只有真有单位时才拼单位;纯文本字段(材质/负责人…)原样。
  226. const value = unit ? withUnitText(raw, unit) : raw
  227. return [labels[key] || SUMMARY_LABELS[key] || key, value]
  228. })
  229. return summaryItems([['状态', status], ...rows, ['位置', location]])
  230. }
  231. function assetPeople(a) { return peopleItems([['负责人', a.principal], ['维护人', a.maintainer], ['整改人', a.rectifyPerson], ['联系电话', a.contactPhone || a.maintainerPhone]]) }
  232. function assetAttachments(a) { return attachmentItems(a.images || a.image) }
  233. function assetDevices(a) {
  234. if (Array.isArray(a.devices)) return a.devices.map((item) => ({
  235. id: item.id || '', code: text(item.code), name: item.name || item.code || '设备名称未提供',
  236. type: item.type || '', location: item.location || '', status: deviceStatusText(item),
  237. }))
  238. return String(a.equipmentIds || a.equipmentId || '').split(',').map((id) => id.trim()).filter(Boolean).map((id) => ({ id, name: '设备名称未提供', code: '', type: '', location: '', status: '状态未发布' }))
  239. }
  240. function deviceStatusText(item) {
  241. if (item.onlineStatus === 0) return '离线'
  242. if (item.alarmStatus === 1) return '报警'
  243. if (item.currentStatus === 1) return '维修'
  244. if (item.currentStatus === 2) return '报废'
  245. if (item.onlineStatus === 1) return '在线'
  246. return '状态未发布'
  247. }
  248. /**
  249. * 设施枚举词表(维护者 2026-10-29 走查逐条点名的口径)。
  250. *
  251. * 后端这些字段是**码值**(status/networkType/networkLevel),直接印数字就是漏码;
  252. * 但认不出的值也不能编一个中文,所以统一走 `codedText()`:命中词表回「中文」,
  253. * 未命中回「码」本身(与 CODE_TEXT 的立场一致)。
  254. */
  255. const FACILITY_STATUS_TEXT = { '0': '正常', '1': '异常' }
  256. const NETWORK_TYPE_TEXT = { '0': '燃气管网', '1': '排水管网', '2': '供水管网' }
  257. const NETWORK_LEVEL_TEXT = { '0': '污水', '1': '雨水' }
  258. /** 排水工程设施类型(0 闸门 / 1 调蓄设施 / 2 泵站):同样是码值,一并直译。 */
  259. const ENGINEERING_FACILITY_TYPE_TEXT = { '0': '闸门', '1': '调蓄设施', '2': '泵站' }
  260. /** 窨井井形(manhole_shape):码值直译,认不出回原码(与上面几条同一纪律)。 */
  261. const MANHOLE_SHAPE_TEXT = { '0': '圆形', '1': '方形', '2': '矩形' }
  262. /** 类别中文名:界面上用「中文 + 英文码」,只印英文等于把接口词汇漏上大屏。 */
  263. const FACILITY_CATEGORY_TEXT = {
  264. PIPE_NETWORK: '管网',
  265. WATER_PLANT: '水厂',
  266. PUMP_STATION: '泵站',
  267. ENGINEERING_FACILITY: '排水工程设施',
  268. MANHOLE: '窨井',
  269. EMERGENCY_RESOURCE: '应急资源',
  270. HAZARD: '危险源',
  271. PROTECTION_TARGET: '防护目标',
  272. }
  273. /** 码 → 显示值;命中词表用中文,未登记机器码显示未知;已发布中文保留。 */
  274. function codedText(value, dictionary, withCode = false, unknownWithCode = false) {
  275. const code = value === null || value === undefined ? '' : String(value).trim()
  276. if (!code) return ''
  277. const label = dictionary && Object.hasOwn(dictionary, code) ? dictionary[code] : ''
  278. if (!label) {
  279. const shown = /\p{Script=Han}/u.test(code) && !/\p{Script=Latin}/u.test(code) ? code : '未知'
  280. return unknownWithCode && shown === '未知' ? `未知(${code})` : shown
  281. }
  282. return withCode ? `${label}(${code})` : label
  283. }
  284. /** 类别显示名:一律中文(维护者 2026-10-29:取消英文括注)。 */
  285. export function facilityCategoryText(category) {
  286. return codedText(category, FACILITY_CATEGORY_TEXT)
  287. }
  288. /** 设施状态(0 正常 / 1 异常)→ 中文;未知码保留原值并如实标注,不猜旧字典语义。 */
  289. export function facilityStatusText(status) {
  290. return codedText(status, FACILITY_STATUS_TEXT, false, true)
  291. }
  292. /**
  293. * 设施详情字段表(维护者 2026-10-29 设计规范)。
  294. *
  295. * 三条口径写死在这一处,别的层不再重复判断:
  296. * 1. **命名一律中文**,必要时用括号补英文码/后端字段名(英文只作补充,不作主名);
  297. * 2. **凡有量纲的读数必带单位**;单位来自后端领域注释(m³/d、m³/h、m、mm、m³、kW…),
  298. * 不从前端猜;
  299. * 3. 某些指标只在特定子类型下有效(如管网「二级分类」只对**排水管**有意义),
  300. * 无效时**保留该行并显示「—」**,不是把它删掉 —— 删掉会让读者以为这个设施没这个属性。
  301. *
  302. * 每项形如 { label, key, unit?, format?, always? }:
  303. * · `format` 把码值翻成中文(枚举词表只在这里登记);
  304. * · `always` 表示"无效也占位"(与 compactSections 的缺值剔除相反)。
  305. */
  306. function pipesFields(a) {
  307. const drainage = String(a.networkType ?? '').trim() === '1'
  308. return [
  309. { label: '管网类型', key: 'networkType', format: (v) => codedText(v, NETWORK_TYPE_TEXT) },
  310. // 二级分类=原来的"管网等级":后端 network_level 只用于区分排水管道(污水/雨水)。
  311. // 非排水管这个字段没有业务含义,按要求显示「—」而不是隐藏。
  312. {
  313. label: '二级分类',
  314. key: 'networkLevel',
  315. always: true,
  316. format: (v) => (drainage ? codedText(v, NETWORK_LEVEL_TEXT) : ''),
  317. invalidNote: drainage ? '' : '仅排水管道适用',
  318. },
  319. { label: '长度', key: 'lengthMeters' },
  320. { label: '管径', key: 'diameterMillimeters' },
  321. { label: '材质', key: 'material' },
  322. { label: '管养单位', key: 'managementUnit' },
  323. { label: '建设日期', key: 'buildDate' },
  324. { label: '备注', key: 'remark', wide: true },
  325. ]
  326. }
  327. const ASSET_FIELD_ROWS = {
  328. PIPE_NETWORK: null, // 见 pipesFields():需要按管网类型决定二级分类是否适用
  329. // 窨井(维护者 2026-11-16):字段与 manhole_base 的列一一对应,不展示不存在的语义。
  330. MANHOLE: [
  331. { label: '井深', key: 'manholeDepth' },
  332. { label: '井形', key: 'manholeShape', format: (v) => codedText(v, MANHOLE_SHAPE_TEXT) },
  333. { label: '材质', key: 'material' },
  334. { label: '权属单位', key: 'ownershipUnit' },
  335. { label: '备注', key: 'remark', wide: true },
  336. ],
  337. WATER_PLANT: [
  338. { label: '水源类型', key: 'waterSourceType' },
  339. { label: '设计能力', key: 'designCapacity' },
  340. { label: '当前能力', key: 'currentCapacity' },
  341. { label: '处理工艺', key: 'treatmentProcess', wide: true },
  342. { label: '投产日期', key: 'commissionDate' },
  343. { label: '水质标准', key: 'waterQualityStandard' },
  344. { label: '负责人', key: 'principal' },
  345. { label: '联系电话', key: 'contactPhone' },
  346. { label: '备注', key: 'remark', wide: true },
  347. ],
  348. ENGINEERING_FACILITY: [
  349. { label: '设施类型', key: 'facilityType', format: (v) => codedText(v, ENGINEERING_FACILITY_TYPE_TEXT) },
  350. { label: '设施等级', key: 'facilityLevel' },
  351. { label: '管理单位', key: 'managementUnit' },
  352. { label: '建设日期', key: 'buildDate' },
  353. { label: '设计流量', key: 'designFlow' },
  354. { label: '设计扬程', key: 'designHead' },
  355. { label: '调蓄容积', key: 'storageCapacity' },
  356. { label: '关联设备', key: 'equipmentIds', wide: true },
  357. { label: '备注', key: 'remark', wide: true },
  358. ],
  359. PUMP_STATION: [
  360. { label: '泵站类型', key: 'stationType', format: (v) => pumpStationTypeText(v) },
  361. { label: '水泵数量', key: 'pumpCount' },
  362. { label: '设计流量', key: 'designFlow' },
  363. { label: '设计扬程', key: 'designHead' },
  364. { label: '装机功率', key: 'powerCapacity' },
  365. { label: '投产日期', key: 'commissionDate' },
  366. { label: '负责人', key: 'principal' },
  367. { label: '联系电话', key: 'contactPhone' },
  368. { label: '备注', key: 'remark', wide: true },
  369. ],
  370. EMERGENCY_RESOURCE: [
  371. { label: '设备类型', key: 'equipmentTypeId' },
  372. { label: '型号', key: 'model' },
  373. { label: '规格', key: 'specification', wide: true },
  374. { label: '制造商', key: 'manufacturer' },
  375. { label: '资产价值', key: 'assetValue' },
  376. { label: '预计使用年限', key: 'useLifeYears' },
  377. { label: '安装时间', key: 'installTime' },
  378. { label: '维护人', key: 'maintainer' },
  379. { label: '维护电话', key: 'maintainerPhone' },
  380. { label: '权属单位', key: 'ownershipUnit' },
  381. { label: '设备图片', key: 'image' },
  382. { label: '备注', key: 'remark', wide: true },
  383. ],
  384. HAZARD: [
  385. { label: '隐患类型', key: 'hazardType' },
  386. { label: '隐患等级', key: 'level' },
  387. { label: '来源', key: 'source' },
  388. { label: '隐患描述', key: 'description', wide: true },
  389. { label: '关联管网', key: 'networkId' },
  390. { label: '关联设备', key: 'equipmentId' },
  391. { label: '关联工单', key: 'workOrderId' },
  392. { label: '报告单位', key: 'reportUnit' },
  393. { label: '报告时间', key: 'reportTime' },
  394. { label: '整改方案', key: 'rectifyPlan', wide: true },
  395. { label: '整改期限', key: 'rectifyDeadline' },
  396. { label: '整改人', key: 'rectifyPerson' },
  397. { label: '整改反馈', key: 'rectifyFeedback', wide: true },
  398. { label: '隐患图片', key: 'images', wide: true },
  399. { label: '备注', key: 'remark', wide: true },
  400. ],
  401. PROTECTION_TARGET: [
  402. { label: '关联管网', key: 'networkId' },
  403. { label: '风险等级', key: 'riskLevel' },
  404. { label: '风险分值', key: 'riskScore' },
  405. { label: '风险颜色', key: 'riskColor' },
  406. { label: '评估模型', key: 'assessmentModel' },
  407. { label: '评估时间', key: 'assessmentTime' },
  408. { label: '风险因素', key: 'riskFactors', wide: true },
  409. { label: '危险源', key: 'hazardSources', wide: true },
  410. { label: '备注', key: 'remark', wide: true },
  411. ],
  412. }
  413. /** 读数 + 单位(认不出的值留给 field() 变占位符,不拼半截 "— m")。 */
  414. function withUnitText(value, unit) {
  415. if (value === null || value === undefined || String(value).trim() === '') return ''
  416. return unit ? `${value} ${unit}` : String(value)
  417. }
  418. function undefinedEnumText(raw) {
  419. const value = text(raw)
  420. if (!value || /\p{Script=Han}/u.test(value) && !/\p{Script=Latin}/u.test(value)) return value
  421. return /^[+-]?\d+(?:\.\d+)?$/.test(value) ? `未定义(原值:${value})` : '未知'
  422. }
  423. /** RiskAssessmentServiceImpl 发布 high/medium/low;历史数字码无定义,不套易积水点字典。 */
  424. function riskLevelText(raw) {
  425. const value = text(raw)
  426. const names = { high: '高风险', medium: '中风险', low: '低风险' }
  427. return Object.hasOwn(names, value) ? names[value] : undefinedEnumText(raw)
  428. }
  429. function assetFieldValue(key, a) {
  430. if (key === 'equipmentIds' || key === 'equipmentId') {
  431. const codes = Array.isArray(a.devices) ? a.devices.map((item) => text(item.code)).filter(Boolean) : []
  432. return codes.join('、') || '未提供'
  433. }
  434. if (['networkId', 'workOrderId', 'equipmentTypeId'].includes(key)) return '未提供'
  435. if (key === 'riskLevel') return riskLevelText(a[key])
  436. if (key === 'riskColor') return undefinedEnumText(a[key])
  437. return a[key]
  438. }
  439. function assetFields(category, a) {
  440. const rows = category === 'PIPE_NETWORK' ? pipesFields(a) : ASSET_FIELD_ROWS[category] || []
  441. return rows.map((row) => {
  442. // 单位一律由 `unitOf(category, key)` 给:同一字段名在不同设施里量纲可能不同。
  443. const raw = row.format ? row.format(a[row.key]) : withUnitText(assetFieldValue(row.key, a), unitOf(category, row.key))
  444. // always 行(如非排水管的二级分类)保留占位;其余缺值由 compactSections 剔除。
  445. const item = field(row.label, raw, row.wide === true)
  446. if (row.always) {
  447. item.always = true
  448. if (row.invalidNote && item.value === PLACEHOLDER) item.note = row.invalidNote
  449. }
  450. return item
  451. })
  452. }
  453. function coordinatesText(value) {
  454. if (!value || typeof value !== 'object') return ''
  455. const start = [value.longitude, value.latitude].filter((item) => item !== null && item !== undefined).join(', ')
  456. const end = [value.endLongitude, value.endLatitude].filter((item) => item !== null && item !== undefined).join(', ')
  457. return [start, end].filter(Boolean).join(' → ')
  458. }
  459. /**
  460. * 事件等级 → 色键 + 文字。
  461. *
  462. * **三种输入形状都要认**(维护者 2026-10-29 走查:「等级明明能拿到却标成未知」):
  463. * · 后端原始事件行:`level: 1`(数字);
  464. * · 列表行视图 `eventRowView`:`level: { tone, label }`(已翻译过的对象);
  465. * · 移动端预警/报警详情:`warningLevel / alarmLevel`(数字或等级名)。
  466. * 详情面板首屏先用列表行 prefill、随后被远端覆盖,两条路都要能读出同一个等级 ——
  467. * 早先只认数字,prefill 的等级对象就被判成"等级未知"。
  468. */
  469. /** 「二级预警」「3级」「四级」→ 1..4;认不出回 null(不猜等级)。 */
  470. function numericLevelOf(value) {
  471. const text = value === null || value === undefined ? '' : String(value).trim()
  472. if (!text) return null
  473. const arabic = /([1-4])\s*级/.exec(text)
  474. if (arabic) return Number(arabic[1])
  475. const cn = /([一二三四])\s*级/.exec(text)
  476. if (cn) return { 一: 1, 二: 2, 三: 3, 四: 4 }[cn[1]]
  477. return null
  478. }
  479. function eventLevelFrom(source) {
  480. const raw = source || {}
  481. // 已经翻译过的对象:原样沿用(这正是列表与详情一致的结构性保证)。
  482. const tagged = raw.level
  483. if (tagged && typeof tagged === 'object' && tagged.label) {
  484. return { tone: tagged.tone || DEFAULT_TONE, label: tagged.label }
  485. }
  486. // 移动端字段名与等级名(如 "二级预警")走桶解析;认不出回「等级未知」。
  487. const direct = raw.level ?? raw.warningLevel ?? raw.alarmLevel
  488. if (typeof direct === 'number') return eventLevelTag(direct)
  489. // 中文等级名(后端会下发「二级预警」「三级报警」这类人话)→ 阿拉伯数字。
  490. const numeric = numericLevelOf(direct)
  491. if (numeric !== null) return eventLevelTag(numeric)
  492. const fromBucket = eventLevelFromBucket(raw.levelCode ?? raw.levelColor ?? direct, direct)
  493. return eventLevelTag(fromBucket)
  494. }
  495. /** BusinessCockpitEventAdapter.alarmStatus:0→UNHANDLED,1→HANDLED;核验态不参与。 */
  496. function mobileAlarmStatus(value) {
  497. return typeof value === 'number' ? value === 0 ? 'UNHANDLED' : value === 1 ? 'HANDLED' : 'UNKNOWN' : value
  498. }
  499. function normalizeEvent(identity, source) {
  500. const envelope = source && source.basicInfo ? source : {}
  501. const basic = envelope.basicInfo && typeof envelope.basicInfo === 'object' ? envelope.basicInfo : source
  502. source = { ...basic,
  503. disposalHistory: envelope.disposalHistory || basic.disposalHistory,
  504. attachmentList: envelope.attachmentList || basic.attachmentList,
  505. alarmList: envelope.alarmList || basic.alarmList,
  506. gisLocation: envelope.gisLocation || basic.gisLocation,
  507. }
  508. const family = String(identity.family || source.family || source.eventFamily || (source.alarmId || source.alarmNo ? 'ALARM' : source.warningId || source.warningNo ? 'WARNING' : '')).toUpperCase()
  509. const level = eventLevelFrom(source)
  510. const status = eventStatusText(source.status || source.state || mobileAlarmStatus(source.alarmStatus) || source.statusName || source.stateName || source.statusText, family)
  511. const name = eventNameText(source.name || source.warningName || source.alarmName || source.eventName || source.deviceName || source.title) || '事件名称未提供'
  512. // 列表 prefill 的 code 是旧内部请求键,只有 codeText 才是业务码;缺码不回退身份。
  513. const listCode = source.codeText === '编码未提供' ? '' : source.codeText
  514. const displayCode = text(source.codeText !== undefined ? listCode : source.code || source.eventCode || source.warningNo || source.alarmNo)
  515. return {
  516. ...identity,
  517. name,
  518. displayCode,
  519. title: name,
  520. kindLabel: family === 'ALARM' ? '报警' : family === 'WARNING' ? '预警' : '事件',
  521. family,
  522. statusText: status,
  523. tone: level.tone || 'neutral',
  524. // 抬头直接显示等级(与卡片同一张词表、同一套色),不再只写在字段里。
  525. levelLabel: level.label,
  526. levelTone: level.tone,
  527. raw: source,
  528. // 等级带语义色(与卡片同一张词表),是摘要里唯一的等级呈现位置。
  529. summary: summaryItems([['等级', level.label, level.tone], ['状态', status], ['当前值', withUnit(source.value ?? source.actualValue, source.unit || source.warningUnit)], ['发生时间', source.eventTime || source.createTime]]),
  530. tabs: family === 'WARNING'
  531. ? [tab('overview', '预警信息'), tab('records', '处置记录'), tab('alarms', '关联报警'), tab('attachments', '附件')]
  532. : [tab('overview', '报警信息'), tab('devices', '设备信息'), tab('records', '处置记录'), tab('attachments', '附件')],
  533. relatedAlarms: Array.isArray(source.alarmList) ? source.alarmList.map(relatedAlarm) : [],
  534. stage: eventStage(family, status, source.disposalHistory),
  535. people: peopleItems([['发布人', source.publisherName || source.publisher], ['处置人', source.handlerName || source.handler], ['核验人', source.reviewerName || source.reviewer]]),
  536. devices: deviceItems(source),
  537. attachments: attachmentItems(source.attachmentList),
  538. records: recordItems(source.disposalHistory || source.logs),
  539. sections: compactSections([
  540. // 等级只出现在摘要卡片那一处(带色),这里不再重复一遍纯文字等级。
  541. section('事件摘要', [field('事件编码', displayCode || '未提供'), field('状态', status), field('发生时间', source.eventTime || source.createTime)]),
  542. section('监测读数', [
  543. field('指标', eventTypeText(source.type || source.warningType || source.warningCode, source.typeName || source.warningTypeName)),
  544. // 读数与阈值都带单位(维护者 2026-10-29:数值型指标必须有单位提示)。
  545. field('实际值', withUnit(source.value ?? source.actualValue, source.unit || source.warningUnit)),
  546. field('阈值', threshold(source)),
  547. field('超出幅度', withUnit(source.deviationRatio, '%')),
  548. ]),
  549. section('关联信息', [field('设备', source.deviceName || source.deviceCode), field('监测点', source.monitoringPointName || source.monitoringPointCode), field('工单', source.workOrderCode || source.orderNo), field('位置', source.location || source.address || locationText(source.gisLocation), true)]),
  550. section('处置与附件', [
  551. field('处置记录', listCount(source.disposalHistory, '条')),
  552. field('关联报警', listCount(source.alarmList, '条')),
  553. field('附件', listCount(source.attachmentList, '项')),
  554. field('督办记录', listCount(source.supervisionList, '条')),
  555. ]),
  556. ]),
  557. }
  558. }
  559. function normalizeWorkOrder(identity, source) {
  560. const detailSource = source && source.order ? source : { order: source, logs: source.logs || [] }
  561. const raw = { ...(detailSource.order || {}) }
  562. if (raw.stateCode === undefined && raw.orderStatus === undefined && raw.status !== undefined) raw.stateCode = Number(raw.status)
  563. const order = toWorkOrder(raw)
  564. const timelineRaw = detailSource.logs || source.timeline || source.timelineEntries || source.records
  565. let track = null
  566. if (Array.isArray(timelineRaw)) {
  567. track = trackOf(toWorkOrderTimeline({ workOrder: raw, timelineEntries: timelineRaw.map((item) => ({
  568. operationName: item.operationName || item.operationType || item.action,
  569. operationDesc: item.operationDesc || item.remark || item.content,
  570. operatorName: item.operatorName || item.operator || item.createByName,
  571. operatedAt: item.operatedAt || item.operationTime || item.createTime,
  572. stateCode: item.stateCode ?? item.orderStatus,
  573. stateName: item.stateName || item.orderStatusName,
  574. })) }))
  575. } else if (source.workOrder && Array.isArray(source.timelineEntries)) {
  576. track = trackOf(toWorkOrderTimeline(source))
  577. }
  578. const stateText = order.stateName || workOrderStateName(order.stateCode)
  579. return {
  580. ...identity,
  581. name: order.code || '工单名称未提供',
  582. title: order.orderTypeName || order.code || '工单名称未提供',
  583. displayCode: order.code,
  584. kindLabel: '工单',
  585. statusText: stateText,
  586. tone: workOrderTone(order.stateCode),
  587. order,
  588. track,
  589. raw: source,
  590. summary: summaryItems([['工单号', order.code], ['状态', stateText], ['优先级', orderLevelText(order.orderLevel)], ['计划完成', order.planFinishTime]]),
  591. tabs: [tab('overview', '工单信息'), tab('flow', '处理流程'), tab('devices', '设备信息'), tab('attachments', '附件')],
  592. stage: workOrderStage(order.stateCode),
  593. people: peopleItems([['处置人', order.receiveUserName], ['核验人', order.verifyUserName]]),
  594. devices: order.deviceCode || order.deviceName ? [{ name: order.deviceName || order.deviceCode, code: order.deviceCode, type: order.deviceTypeName, location: order.deviceLocation }] : [],
  595. attachments: attachmentItems([raw.maintenanceBeforeImg, raw.maintenanceAfterImg, ...timelineAttachments(timelineRaw)]),
  596. records: recordItems(timelineRaw),
  597. sections: compactSections([
  598. section('工单摘要', [field('工单号', order.code || '未提供'), field('类型', order.orderTypeName), field('优先级', orderLevelText(order.orderLevel)), field('状态', stateText)]),
  599. section('时间信息', [field('创建时间', order.createTime), field('计划完成', order.planFinishTime), field('实际完成', order.realFinishTime)]),
  600. section('设备信息', [field('设备', order.deviceName || order.deviceCode), field('设备类型', order.deviceTypeName), field('安装位置', order.deviceLocation, true)]),
  601. section('处置内容', [field('处置人', order.receiveUserName), field('核验人', order.verifyUserName), field('故障描述', order.description, true), field('处置结果', order.repairResult, true)]),
  602. ]),
  603. }
  604. }
  605. /** 工单优先级码值(0 紧急 / 1 一般 / 2 低)→ 中文;认不出回码。 */
  606. function orderLevelText(value) {
  607. const code = value === null || value === undefined ? '' : String(value).trim()
  608. if (!code) return ''
  609. return { '0': '紧急', '1': '一般', '2': '低' }[code] || code
  610. }
  611. function tab(key, label) { return { key, label } }
  612. function relatedAlarm(item) { return { id: item.alarmId || item.id || '', code: text(item.code || item.alarmNo || item.alarmCode), name: item.alarmName || item.content || item.deviceName || '关联报警', status: eventStatusText(mobileAlarmStatus(item.alarmStatus) || item.status || item.auditStatusName, 'ALARM') } }
  613. function summaryItems(entries) { return entries.filter(([,value]) => value !== null && value !== undefined && String(value).trim() !== '').map(([label,value,tone]) => ({ label, value: String(value), tone: tone || '' })) }
  614. function peopleItems(entries) { return entries.filter(([,name]) => name).map(([role,name]) => ({ role, name: String(name) })) }
  615. function deviceItems(source) {
  616. const name = source.deviceName || source.monitoringPointName || ''
  617. const code = source.deviceCode || source.monitoringPointCode || ''
  618. return name || code ? [{ name: name || code, code, location: source.location || source.address || '' }] : []
  619. }
  620. function attachmentItems(value) {
  621. const list = Array.isArray(value) ? value : value ? String(value).split(',') : []
  622. return list.flatMap((item) => {
  623. if (!item) return []
  624. if (typeof item === 'object') return [{ name: item.attachmentName || item.fileName || item.name || '附件', url: item.attachmentUrl || item.url || '', type: item.attachmentType || item.type || '' }]
  625. const url = String(item).trim(); return url ? [{ name: url.split('/').pop() || '附件', url, type: '' }] : []
  626. })
  627. }
  628. function recordItems(value) {
  629. return (Array.isArray(value) ? value : []).map((item) => ({
  630. title: item.operationName || item.operationType || item.action || item.disposalStatus || '处置记录',
  631. time: item.operatedAt || item.operationTime || item.createTime || item.disposalTime || '',
  632. operator: item.operatorName || item.operator || item.createByName || item.disposalUser || '',
  633. description: item.operationDesc || item.remark || item.content || item.disposalContent || '',
  634. }))
  635. }
  636. function eventStage(family, status, records) {
  637. const labels = family === 'ALARM' ? ['产生', '确认', '处置', '关闭'] : ['发布', '接收', '处置', '核验', '解除']
  638. const normalized = String(status || '').toUpperCase()
  639. let active = normalized.includes('RESOLV') || normalized.includes('CLEAR') || normalized.includes('CLOSE') ? labels.length - 1
  640. : normalized.includes('PROCESS') || normalized.includes('HANDL') ? Math.min(2, labels.length - 1)
  641. : normalized.includes('RECEIV') || normalized.includes('CONFIRM') ? 1 : 0
  642. if (Array.isArray(records) && records.length) active = Math.max(active, Math.min(2, labels.length - 1))
  643. return labels.map((label,index) => ({ label, state: index < active ? 'done' : index === active ? 'active' : 'pending' }))
  644. }
  645. function workOrderStage(code) {
  646. const labels = ['创建','派单','接单','处置','验收','完成']
  647. const n = Number(code); const active = n === 6 ? 3 : n === 7 ? 0 : Number.isInteger(n) ? Math.max(0, Math.min(n, 5)) : 0
  648. return labels.map((label,index) => ({ label, state: index < active ? 'done' : index === active ? 'active' : 'pending' }))
  649. }
  650. function timelineAttachments(records) { return (Array.isArray(records) ? records : []).flatMap((item) => item.attachList || item.attachments || []) }
  651. /**
  652. * 缺值剔除:always 行例外 —— 业务上"这个设施没有该属性"时要显式显示占位符
  653. * (维护者 2026-10-29:非排水管的二级分类显示「—」,不是把整行藏掉)。
  654. */
  655. function compactSections(sections) {
  656. return sections
  657. .map((group) => ({ ...group, fields: group.fields.filter((item) => item.always || item.value !== PLACEHOLDER) }))
  658. .filter((group) => group.fields.length)
  659. }
  660. function section(title, fields) { return { title, fields } }
  661. function field(label, value, wide = false) { return { label, value: display(value), wide, always: false, note: '' } }
  662. function display(value) { return value === null || value === undefined || String(value).trim() === '' ? PLACEHOLDER : String(value) }
  663. function text(value) { return value === null || value === undefined ? '' : String(value).trim() }
  664. /**
  665. * 读数 + 单位。三条纪律(维护者 2026-10-29):
  666. * · 没值就整句不出(不拼半截 "— μS/cm");
  667. * · **有值但后端没给单位**时如实标注「单位未发布」,不假装无单位是个读数;
  668. * · 有单位则一律追加 —— 数值型指标不允许裸数字上屏。
  669. */
  670. function withUnit(value, unit) {
  671. const hasValue = value !== null && value !== undefined && String(value).trim() !== ''
  672. if (!hasValue) return ''
  673. return unit ? `${value} ${unit}` : `${value}(单位未发布)`
  674. }
  675. function threshold(source) {
  676. const min = source.thresholdMinValue ?? source.minValue
  677. const max = source.thresholdMaxValue ?? source.maxValue
  678. if (min === undefined && max === undefined) return ''
  679. return withUnit(min !== undefined && max !== undefined ? `${min} ~ ${max}` : min !== undefined ? `≥ ${min}` : `≤ ${max}`, source.unit)
  680. }
  681. function positive(value, fallback) { const n = Number(value); return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback }
  682. function nonNegative(value, fallback) { const n = Number(value); return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback }
  683. function listCount(value, unit) { return Array.isArray(value) ? `${value.length} ${unit}` : '' }
  684. function locationText(value) {
  685. if (!value || typeof value !== 'object') return ''
  686. return value.location || value.address || [value.longitude, value.latitude].filter((item) => item !== undefined && item !== null).join(', ')
  687. }
  688. 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) }
  689. function workOrderTone(code) { if (code === 5) return 'lv4'; if (code === 7) return 'lv1'; if (code === 6) return 'lv2'; return 'lv3' }