yeg
2026-09-06 f2384cd6229df223707ed48c15bce8f1483e35cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
<script setup lang="ts">
import { toTestDisplayValue } from '@/utils/testDataUnits'
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import CompareReportHistoryDialog from '@/components/CompareReportHistoryDialog.vue'
import { getUserInfo } from '@/api/auth'
import type { CompareMetricKey, CompareTestSelection } from '@/stores/compareReports'
import type { PersistedTestRecord } from '@/api/tests'
import { compareSelectionKey, createCompareReport, editCompareReport, getCompareReport, getCompareSources, previewCompareReport, refreshCompareSource,
  type CompareCandidate, type CompareItem, type CompareSelection, type SavedCompareReport } from '@/api/compareReports'
import { compareMetricDefinitions as metricDefinitions, type CompareMetricDefinition } from '@/utils/compareReportPrint'
 
use([CanvasRenderer, LineChart, GridComponent, LegendComponent, TooltipComponent])
 
interface FieldTemplate {
  key: string
  name: string
  fields: string[]
}
 
const route = useRoute()
const router = useRouter()
const editingId = computed(() => {
  const value = Number(route.params.id)
  return Number.isFinite(value) && value > 0 ? value : null
})
const editingRecord = ref<SavedCompareReport | null>(null)
const readonly = computed(() => Boolean(editingId.value) && (route.query.mode !== 'edit' || !canEdit.value || Boolean(loadError.value)))
const canCreate = ref(false)
const canEdit = ref(false)
const canQuery = ref(false)
const historyVisible = ref(false)
const changeSummary = ref('')
const loadError = ref('')
const previewLoading = ref(false)
const previewError = ref('')
const reportLoading = ref(false)
const saving = ref(false)
const reportName = ref('')
const experimentName = ref('')
const description = ref('')
const batteryGroup = ref('')
type SelectedTest = CompareTestSelection & { selection: CompareSelection }
const selectedTests = ref<SelectedTest[]>([])
const candidates = ref<CompareCandidate[]>([])
const candidateTests = computed(() => [...new Map(candidates.value.map(item => [item.selection.testId, toSelectedTest(item)])).values()])
const sourceItems = ref<CompareItem[]>([])
const candidatesLoading = ref(false)
const candidatesError = ref('')
const testDialogVisible = ref(false)
const templateDialogVisible = ref(false)
const selectedTemplateKey = ref('cycle')
const selectedCandidateId = ref<number | null>(null)
const selectedBatteryNo = ref('')
const selectedCycle = ref<number | null>(null)
const selectedProcess = ref('')
const templateMode = ref<'battery' | 'special'>('battery')
const batteryFields = ref(['额定容量', '电流', '内阻'])
const specialFields = ref(['温升'])
const detailFieldValues = reactive<Record<string, Record<string, string>>>({})
const presetBatteryTemplateLabels: Record<string, string[]> = {
  '标准容量样品': ['额定容量', '电流', '内阻'],
  '标准循环样品': ['额定容量', '循环温度', '内阻'],
  '低温性能样品': ['目标温度', '静置时间', '环境备注'],
}
const batteryTemplateSelections = reactive<Record<string, number[]>>({})
const selectedBatteryTemplateName = ref('标准容量样品')
const selectedBatteryTemplateFieldIds = ref<number[]>([])
 
const specialTemplateSelections = reactive<Record<string, string[]>>({})
 
const fieldTemplates = computed<FieldTemplate[]>(() => [
  { key: 'cycle', name: '循环寿命模板', fields: ['容量保持率', '能量效率', '循环次数', '内阻变化'] },
  { key: 'thermal', name: '热特性模板', fields: ['最高温度', '温差', '温升速率'] },
  ...Object.entries(specialTemplateSelections).map(([name, fields]) => ({ key: `saved:${name}`, name, fields })),
])
 
const metricVisible = reactive<Record<CompareMetricKey, boolean>>({
  voltage: true,
  current: true,
  positiveVoltage: true,
  negativeVoltage: true,
  temperature: true,
})
const seriesColors = ref(['#3978f6', '#7d42d8', '#f08a3e'])
 
const visibleMetrics = computed(() => metricDefinitions.filter(metric => metricVisible[metric.key]))
const selectedTemplate = computed(() => fieldTemplates.value.find(item => item.key === selectedTemplateKey.value) || fieldTemplates.value[0])
const batteryTemplateNames = computed(() => [
  '自定义',
  '标准容量样品',
  '标准循环样品',
  '低温性能样品',
  ...Object.keys(batteryTemplateSelections).filter(name => !['自定义', '标准容量样品', '标准循环样品', '低温性能样品'].includes(name)),
])
const batteryTemplateFieldOptions = computed(() => [...new Map(sourceItems.value.flatMap(item => item.businessFields)
  .map(field => [field.fieldDefinitionId, { id: field.fieldDefinitionId, name: field.fieldName, type: field.fieldType, status: '启用' }])).values()])
const enabledBatteryTemplateFields = computed(() => batteryTemplateFieldOptions.value.filter(field => field.status === '启用'))
const detailFields = computed(() => [...batteryFields.value, ...specialFields.value])
const selectedCandidate = computed(() => candidateTests.value.find(item => item.id === selectedCandidateId.value) || null)
const detailTests = computed(() => selectedTests.value)
const chartSeries = computed(() => detailTests.value)
const testCandidates = computed(() => candidates.value.filter(item => item.selection.testId === selectedCandidateId.value))
const batteryChoices = computed(() => [...new Set(testCandidates.value.map(item => item.batteryNo))])
const cycleChoices = computed(() => [...new Set(testCandidates.value.filter(item => item.batteryNo === selectedBatteryNo.value).map(item => item.selection.cycleNo))].sort((a, b) => a - b))
const processChoices = computed(() => testCandidates.value.filter(item => item.batteryNo === selectedBatteryNo.value && item.selection.cycleNo === selectedCycle.value).map(item => item.process))
 
function toSelectedTest(item: CompareCandidate): SelectedTest {
  return { ...item, id: item.selection.testId, cycle: item.selection.cycleNo }
}
 
async function loadCandidates() {
  candidatesLoading.value = true
  candidatesError.value = ''
  try {
    candidates.value = await getCompareSources()
  } catch (error) {
    candidatesError.value = error instanceof Error ? error.message : '真实测试来源加载失败'
  } finally {
    candidatesLoading.value = false
  }
}
 
function metricValues(key: CompareMetricKey): Array<Array<[number, number | null]>> {
  const field: Record<CompareMetricKey, keyof PersistedTestRecord> = { voltage: 'voltage', current: 'current', positiveVoltage: 'positivePotential', negativeVoltage: 'negativePotential', temperature: 'temperature' }
  // 各来源设备时间按比对项零点转为相对秒,测量仅在展示时换算毫单位,保留缺失值。
  return sourceItems.value.map(item => item.records.flatMap(row => {
    const time = key === 'voltage' || key === 'current' ? row.deviceTime : row.collectorDeviceTime
    if (time == null || item.zeroTime == null) return []
    const value = row[field[key]]
    return [[(Number(time) - item.zeroTime) / 1000, value == null ? null : toTestDisplayValue(key, Number(value))] as [number, number | null]]
  }).sort((left, right) => left[0] - right[0]))
}
 
function detailKey(item: SelectedTest) {
  return compareSelectionKey(item.selection)
}
 
function ensureDetailFieldValues(field: string) {
  if (!detailFieldValues[field]) detailFieldValues[field] = {}
  detailTests.value.forEach(item => {
    const key = detailKey(item)
    // 未填写才读取当前预览或保存快照的业务值,显式清空不被后续预览覆盖。
    if (detailFieldValues[field][key] === undefined) {
      const source = sourceItems.value.find(value => compareSelectionKey(value.source.selection) === key)
      detailFieldValues[field][key] = source?.businessFields.find(value => value.fieldName === field)?.fieldValue ?? ''
    }
  })
}
 
function loadEditingReport() {
  const record = editingRecord.value
  if (!record) return
 
  reportName.value = record.name
  experimentName.value = record.experimentName || ''
  description.value = record.description || ''
  sourceItems.value = record.items
  selectedTests.value = record.items.map(item => toSelectedTest(item.source))
  metricDefinitions.forEach(metric => { metricVisible[metric.key] = record.settings.metrics.includes(metric.key) })
  seriesColors.value = [...record.settings.seriesColors]
  batteryFields.value = [...record.settings.batteryTemplateFields]
  specialFields.value = [...record.settings.specialFields]
  Object.keys(detailFieldValues).forEach(field => delete detailFieldValues[field])
  Object.entries(record.settings.detailFieldValues).forEach(([field, values]) => {
    detailFieldValues[field] = { ...values }
  })
  selectedBatteryTemplateName.value = '自定义'
  selectedBatteryTemplateFieldIds.value = enabledBatteryTemplateFields.value
    .filter(field => batteryFields.value.includes(field.name))
    .map(field => field.id)
  detailFields.value.forEach(ensureDetailFieldValues)
}
 
function updateSeriesColor(index: number, color: string | null) {
  if (color) seriesColors.value[index] = color
}
 
detailFields.value.forEach(ensureDetailFieldValues)
// 搜索跳转和浏览器后退会复用详情组件,旧请求的结果不能覆盖新报表。
watch(() => [editingId.value, route.query.mode, route.query.version] as const, async ([id, mode, version], _previous, onCleanup) => {
  let cancelled = false
  onCleanup(() => { cancelled = true })
  editingRecord.value = null
  selectedTests.value = []
  sourceItems.value = []
  reportName.value = ''
  description.value = ''
  experimentName.value = ''
  batteryFields.value = ['额定容量', '电流', '内阻']
  specialFields.value = ['温升']
  seriesColors.value = ['#3978f6', '#7d42d8', '#f08a3e']
  metricDefinitions.forEach(metric => { metricVisible[metric.key] = true })
  Object.keys(detailFieldValues).forEach(field => delete detailFieldValues[field])
  loadError.value = ''
  detailFields.value.forEach(ensureDetailFieldValues)
  previewError.value = ''
  canCreate.value = false
  canEdit.value = false
  canQuery.value = false
  historyVisible.value = false
  changeSummary.value = ''
  reportLoading.value = true
  try {
    const info = await getUserInfo()
    if (cancelled) return
    canEdit.value = Boolean(info.permissions?.some(item => item === '*:*:*' || item === 'system:compare-report:edit'))
    canQuery.value = Boolean(info.permissions?.some(item => item === '*:*:*' || item === 'system:compare-report:query'))
    if (id) {
      if (mode === 'edit' && (!canEdit.value || version !== undefined)) throw new Error('历史版本只读或无编辑权限')
      // 编辑权限包含读取最新编辑基准,取消或保存后仍可预览;历史查看单独要求查看权限。
      const editingAccess = mode === 'edit' || (!canQuery.value && canEdit.value && version === undefined)
      const record = await getCompareReport(id, version === undefined ? undefined : Number(version), editingAccess)
      if (cancelled) return
      editingRecord.value = record
      loadEditingReport()
    } else {
      canCreate.value = Boolean(info.permissions?.some(item => item === '*:*:*' || item === 'system:compare-report:add'))
      if (!canCreate.value) throw new Error('无新增对比报表权限')
      await loadCandidates()
    }
  } catch (error) { if (!cancelled) loadError.value = error instanceof Error ? error.message : '报表加载失败' }
  finally { if (!cancelled) reportLoading.value = false }
}, { immediate: true })
 
async function refreshPreview() {
  const selections = selectedTests.value.map(item => item.selection)
  previewLoading.value = true
  previewError.value = ''
  sourceItems.value = []
  try {
    const items = await previewCompareReport(selections)
    if (editingId.value) return
    sourceItems.value = items
    detailFields.value.forEach(ensureDetailFieldValues)
  } catch (error) { previewError.value = error instanceof Error ? error.message : '曲线预览失败' }
  finally { previewLoading.value = false }
}
 
function openAddTest() {
  selectedCandidateId.value = null
  selectedBatteryNo.value = ''
  selectedCycle.value = null
  selectedProcess.value = ''
  testDialogVisible.value = true
}
 
function syncDialogDefaults() {
  if (!selectedCandidate.value) return
  selectedBatteryNo.value = selectedCandidate.value.batteryNo
  selectedCycle.value = selectedCandidate.value.cycle
  selectedProcess.value = selectedCandidate.value.process
}
 
async function addSelectedTest() {
  if (previewLoading.value || saving.value) return
  const candidate = testCandidates.value.find(item => item.batteryNo === selectedBatteryNo.value && item.selection.cycleNo === selectedCycle.value && item.process === selectedProcess.value)
  if (!candidate) {
    ElMessage.warning('请选择要加入对比的测试')
    return
  }
  if (!selectedBatteryNo.value || !selectedCycle.value || !selectedProcess.value) {
    ElMessage.warning('请完整选择电池、循环和工步')
    return
  }
  if (selectedTests.value.some(item => detailKey(item) === compareSelectionKey(candidate.selection))) {
    ElMessage.warning('相同测试、电池和工步循环已加入对比信息')
    return
  }
  selectedTests.value.push(toSelectedTest(candidate))
  if (!seriesColors.value[selectedTests.value.length - 1]) seriesColors.value.push('#109854')
  testDialogVisible.value = false
  await refreshPreview()
}
 
async function removeTest(itemToRemove: SelectedTest) {
  if (previewLoading.value || saving.value) return
  if (selectedTests.value.length === 1) {
    ElMessage.warning('至少保留一条对比测试')
    return
  }
  const index = selectedTests.value.indexOf(itemToRemove)
  if (index >= 0) { selectedTests.value.splice(index, 1); seriesColors.value.splice(index, 1) }
  await refreshPreview()
}
 
function addCustomField() {
  ElMessageBox.prompt('请输入要添加的字段名称', '添加项', {
    confirmButtonText: '添加',
    cancelButtonText: '取消',
    inputPlaceholder: '例如:库仑效率',
    inputValidator: value => value.trim() ? true : '请输入字段名称',
  }).then(({ value }) => {
    const name = value.trim()
    if (detailFields.value.includes(name)) {
      ElMessage.warning('该字段已经存在')
      return
    }
    specialFields.value.push(name)
    ensureDetailFieldValues(name)
    ElMessage.success(`已添加字段“${name}”`)
  }).catch(() => {
    // 用户取消添加。
  })
}
 
function removeCustomField(field: string) {
  if (batteryFields.value.includes(field)) {
    ElMessage.warning('电池组模板字段请在电池组字段模板中调整')
    return
  }
  specialFields.value = specialFields.value.filter(item => item !== field)
  delete detailFieldValues[field]
}
 
function resolveBatteryTemplateFieldIds(name: string) {
  const savedIds = batteryTemplateSelections[name]
  if (savedIds) return savedIds.filter(id => enabledBatteryTemplateFields.value.some(field => field.id === id))
  const labels = presetBatteryTemplateLabels[name] || []
  return enabledBatteryTemplateFields.value.filter(field => labels.includes(field.name)).map(field => field.id)
}
 
function loadBatteryTemplate(name: string) {
  selectedBatteryTemplateFieldIds.value = resolveBatteryTemplateFieldIds(name)
}
 
function switchBatteryTemplate(name: string) {
  loadBatteryTemplate(name)
  applyBatteryTemplateFields()
}
 
function applyBatteryTemplateFields() {
  batteryFields.value = selectedBatteryTemplateFieldIds.value
    .map(id => enabledBatteryTemplateFields.value.find(field => field.id === id)?.name)
    .filter((name): name is string => Boolean(name))
  specialFields.value = specialFields.value.filter(field => !batteryFields.value.includes(field))
  detailFields.value.forEach(ensureDetailFieldValues)
}
 
function openFieldTemplate(mode: 'battery' | 'special') {
  templateMode.value = mode
  if (mode === 'battery') {
    if (!batteryTemplateNames.value.includes(selectedBatteryTemplateName.value)) selectedBatteryTemplateName.value = '自定义'
    if (selectedBatteryTemplateName.value !== '自定义') loadBatteryTemplate(selectedBatteryTemplateName.value)
  } else {
    selectedTemplateKey.value = 'cycle'
  }
  templateDialogVisible.value = true
}
 
function applyFieldTemplate() {
  if (templateMode.value === 'battery') {
    applyBatteryTemplateFields()
  } else {
    const nextFields = selectedTemplate.value.fields
    specialFields.value = nextFields.filter(field => !batteryFields.value.includes(field))
    detailFields.value.forEach(ensureDetailFieldValues)
  }
  templateDialogVisible.value = false
  ElMessage.success(`${templateMode.value === 'battery' ? '电池组字段' : '特殊字段'}模板已应用`)
}
 
function chartOption(metric: CompareMetricDefinition) {
    const names = chartSeries.value.map(item => `${item.name} · ${item.batteryNo} · 循环${item.cycle} · ${item.process}`)
    const colors = seriesColors.value
    const visibleSeries = metricValues(metric.key)
    const visibleValues = visibleSeries.flat().map(point => point[1]).filter((value): value is number => value !== null)
    const dataMin = Math.min(0, ...visibleValues)
    const dataMax = Math.max(0, ...visibleValues)
    const range = Math.max(dataMax - dataMin, 1)
  const axisMax = Math.max(metric.unit === '℃' ? Math.ceil(dataMax / 10) * 10 : Math.ceil(dataMax * 10) / 10, 1)
  const createYAxis = (position: 'left' | 'right') => ({
    type: 'value',
    name: metric.unit,
    position,
    min: dataMin - range * 0.05,
    max: axisMax,
    nameTextStyle: { color: '#8795a3', fontSize: 10 },
    axisLine: { show: true, lineStyle: { color: '#cbd8e4' } },
    axisTick: { show: true, lineStyle: { color: '#cbd8e4' } },
    splitLine: { show: position === 'left', lineStyle: { color: '#e8eef4' } },
    axisLabel: { color: '#8795a3', fontSize: 10 },
  })
  return {
    animation: false,
    color: colors,
      grid: { top: 40, right: 46, bottom: 42, left: 46 },
    tooltip: { trigger: 'axis' },
    legend: { show: false },
      xAxis: { type: 'value', min: 0, name: '相对时间 / s', nameLocation: 'middle', nameGap: 28, axisLine: { lineStyle: { color: '#cbd8e4' } }, axisLabel: { color: '#8795a3', fontSize: 10 }, nameTextStyle: { color: '#26333f', fontSize: 11, fontWeight: 600 } },
    yAxis: [createYAxis('left'), createYAxis('right')],
    series: names.map((name, index) => ({ name, type: 'line', smooth: false, connectNulls: false, showSymbol: true, symbolSize: 5, lineStyle: { width: 2 }, data: visibleSeries[index] || [] })),
  }
}
 
async function saveReport() {
  if (saving.value || reportLoading.value || loadError.value || readonly.value || !(editingId.value ? canEdit.value : canCreate.value)) return
  if (!reportName.value.trim()) {
    ElMessage.warning('请输入报告名称')
    return
  }
  if (selectedTests.value.length < 2) {
    ElMessage.warning('请至少添加两条对比测试')
    return
  }
  if (editingId.value && !changeSummary.value.trim()) {
    ElMessage.warning('请输入修改说明')
    return
  }
  saving.value = true
  try {
    const content = {
      name: reportName.value.trim(), description: description.value, experimentName: experimentName.value,
      settings: {
        metrics: visibleMetrics.value.map(item => item.key), seriesColors: seriesColors.value.slice(0, selectedTests.value.length),
        batteryTemplateFields: [...batteryFields.value], specialFields: [...specialFields.value],
        detailFieldValues: Object.fromEntries(detailFields.value.map(field => [field,
          Object.fromEntries(selectedTests.value.map(item => [detailKey(item), detailFieldValues[field]?.[detailKey(item)] || ''])),
        ])),
      },
    }
    if (editingId.value && editingRecord.value) {
      await editCompareReport(editingId.value, { ...content, baseVersionNo: editingRecord.value.versionNo, changeSummary: changeSummary.value.trim() })
    } else {
      await createCompareReport({ ...content, selections: selectedTests.value.map(item => item.selection) })
    }
    ElMessage.success('对比报表已保存')
    await router.push(editingId.value ? { path: `/report-compare/${editingId.value}/edit`, query: { mode: 'view' } } : '/report-compare')
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '保存失败,请重试')
  } finally {
    saving.value = false
  }
}
 
async function generateFromLatestSource() {
  if (saving.value || !editingRecord.value || !editingId.value) return
  const baseRecord = editingRecord.value
  let reason: string
  try {
    const result = await ElMessageBox.prompt('将重新读取当前来源并生成新版本,保留已有人工表格值。', '按最新来源生成版本', {
      inputPlaceholder: '请输入更新来源说明', inputValidator: value => value?.trim() && value.trim().length <= 480 ? true : '请填写不超过480字的说明',
      confirmButtonText: '生成新版本', cancelButtonText: '取消',
    })
    reason = result.value.trim()
  } catch { return }
  if (editingRecord.value !== baseRecord) return
  saving.value = true
  try {
    const record = await refreshCompareSource(baseRecord.id, baseRecord.versionNo, reason)
    if (editingRecord.value !== baseRecord) return
    editingRecord.value = record
    loadEditingReport()
    ElMessage.success(`已生成版本 ${record.versionNo}`)
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '更新来源失败')
  } finally { saving.value = false }
}
</script>
 
<template>
  <div class="compare-form-page" :class="{ 'is-readonly': readonly }">
    <el-alert v-if="loadError" :title="loadError" type="error" :closable="false" show-icon />
    <div v-if="reportLoading">正在加载报表</div>
    <el-alert v-if="previewError" :title="previewError" type="error" :closable="false" show-icon />
    <div class="page-tools"><button class="back-button" type="button" @click="router.push('/report-compare')"><el-icon><ArrowLeft /></el-icon>返回对比报表</button><span>{{ readonly ? 'VIEW COMPARISON REPORT' : editingId ? 'EDIT COMPARISON REPORT' : 'NEW COMPARISON REPORT' }}</span></div>
 
    <section class="report-name-panel">
      <label><span>报表名称</span><el-input v-model="reportName" :readonly="readonly" maxlength="100" clearable placeholder="请输入报表名称" /></label>
      <label><span>说明</span><el-input v-model="description" :readonly="readonly" maxlength="2000" type="textarea" placeholder="请输入说明" /></label>
      <label v-if="editingId && !readonly"><span>修改说明</span><el-input v-model="changeSummary" maxlength="500" placeholder="请输入修改说明" /></label>
      <span v-if="editingRecord">版本 {{ editingRecord.versionNo }} · {{ editingRecord.operatorName }} · {{ new Date(editingRecord.versionCreatedAt).toLocaleString() }} · {{ editingRecord.changeSummary }}</span>
    </section>
 
    <section class="compare-info-panel">
      <header class="panel-heading"><div><strong>对比信息</strong><el-icon><ArrowUp /></el-icon></div></header>
      <div class="compare-table-wrap">
        <table class="compare-table">
          <thead><tr><th>测试名称</th><th>测试类型</th><th>电池号</th><th>工步</th><th>循环</th><th v-if="!editingId">操作</th></tr></thead>
          <tbody>
            <tr v-for="(item, index) in selectedTests" :key="`${item.id}-${item.batteryGroup || batteryGroup}-${item.batteryNo}-${index}`"><td>{{ item.name }}</td><td>{{ item.type }}</td><td>{{ item.batteryNo }}</td><td>{{ item.process }}</td><td>{{ item.cycle }}</td><td v-if="!editingId"><button class="delete-link" type="button" @click="removeTest(item)">删除</button></td></tr>
            <tr v-if="!selectedTests.length"><td :colspan="readonly ? 5 : 6" class="empty-cell">暂无对比测试</td></tr>
          </tbody>
        </table>
      </div>
      <button v-if="!editingId && canCreate" class="primary-button compact-button" type="button" :disabled="previewLoading || saving" @click="openAddTest"><el-icon><Plus /></el-icon>添加比较</button>
    </section>
 
    <section class="detail-panel">
      <header class="panel-heading"><div><strong>测试详情</strong><el-icon><ArrowUp /></el-icon></div></header>
      <div class="detail-meta">
        <label><span>实验</span><el-input v-model="experimentName" :readonly="readonly" maxlength="500" /></label>
      </div>
      <div class="field-table-wrap">
        <table class="field-table" :style="{ minWidth: `${Math.max(900, detailTests.length * 220 + 214)}px` }">
          <thead><tr><th>字段</th><th v-for="(item, index) in detailTests" :key="detailKey(item)">对比项 {{ index + 1 }}</th><th v-if="!readonly">操作</th></tr></thead>
          <tbody>
            <tr class="detail-meta-row"><td>测试</td><td v-for="item in detailTests" :key="detailKey(item)">{{ item.name }}</td><td v-if="!readonly">-</td></tr>
            <tr class="detail-meta-row"><td>电池组</td><td v-for="item in detailTests" :key="detailKey(item)">{{ item.batteryGroup || batteryGroup }}</td><td v-if="!readonly">-</td></tr>
            <tr class="sample-row"><td>电池号</td><td v-for="item in detailTests" :key="detailKey(item)">{{ item.batteryNo }}</td><td v-if="!readonly">-</td></tr>
            <tr v-for="field in detailFields" :key="field"><td>{{ field }}</td><td v-for="item in detailTests" :key="detailKey(item)"><el-input v-model="detailFieldValues[field][detailKey(item)]" :readonly="readonly" size="small" placeholder="请输入" /></td><td v-if="!readonly"><button v-if="specialFields.includes(field)" class="delete-link" type="button" @click="removeCustomField(field)">删除</button><span v-else class="field-lock">-</span></td></tr>
            <tr v-if="!detailFields.length"><td :colspan="detailTests.length + (readonly ? 1 : 2)" class="empty-cell">暂无字段</td></tr>
          </tbody>
        </table>
      </div>
      <div v-if="!readonly" class="detail-actions"><button class="primary-button" type="button" @click="addCustomField"><el-icon><Plus /></el-icon>添加项</button><button class="secondary-button" type="button" @click="openFieldTemplate('battery')">电池组字段</button><button class="secondary-button" type="button" @click="openFieldTemplate('special')">选择特殊字段</button></div>
    </section>
 
    <section class="metrics-panel">
      <div v-if="!readonly" class="metric-switches"><label v-for="metric in metricDefinitions" :key="metric.key"><span>{{ metric.title }}</span><el-switch v-model="metricVisible[metric.key]" inline-prompt active-text="显" inactive-text="隐" /></label></div>
      <div v-if="chartSeries.length" class="chart-legend-bar"><strong>对比图例</strong><div v-for="(item, index) in chartSeries" :key="detailKey(item)" class="chart-legend-item"><el-color-picker v-if="!readonly" class="legend-color-picker" :model-value="seriesColors[index]" :show-alpha="false" popper-class="legend-color-popper" :aria-label="`修改${item.name}颜色`" @change="updateSeriesColor(index, $event)" /><i v-else class="series-swatch" :style="{ background: seriesColors[index] }" /><span>{{ item.name }} · {{ item.batteryNo }} · 循环{{ item.cycle }} · {{ item.process }}</span></div></div>
      <!-- 报表切换和比对项移除时完整替换配置,避免图表库将颜色数组缩短误判为组件合并。 -->
      <div class="charts-grid"><article v-for="metric in visibleMetrics" :key="metric.key" class="chart-card"><header><strong>{{ metric.title }}</strong></header><VChart class="metric-chart" :option="chartOption(metric)" :update-options="{ notMerge: true }" autoresize /></article></div>
    </section>
 
    <footer class="form-actions">
      <button v-if="readonly && canQuery && editingRecord" class="secondary-button" type="button" :disabled="reportLoading || saving" @click="historyVisible = true"><el-icon><Clock /></el-icon>历史版本</button>
      <button v-if="readonly && editingRecord && route.query.version !== undefined" class="secondary-button" type="button" @click="router.push({ query: { mode: 'view' } })">查看最新版本</button>
      <button v-if="readonly && canEdit && editingRecord && route.query.version === undefined" class="secondary-button" type="button" :disabled="reportLoading || saving || !!loadError" @click="generateFromLatestSource"><el-icon><Refresh /></el-icon>按最新来源生成版本</button>
      <button v-if="readonly && canEdit && editingRecord && route.query.version === undefined" class="secondary-button" type="button" :disabled="reportLoading || saving || !!loadError" @click="router.push({ query: { mode: 'edit' } })"><el-icon><Edit /></el-icon>编辑报表</button>
      <button v-if="readonly" class="primary-button" type="button" @click="router.push('/report-compare')">返回列表</button>
      <button v-else-if="editingId" class="secondary-button" type="button" :disabled="saving" @click="router.push({ query: { mode: 'view' } })">取消编辑</button>
      <button v-if="!readonly && (canCreate || canEdit)" class="primary-button save-button" type="button" :disabled="saving || reportLoading || !!loadError || previewLoading || !!previewError" @click="saveReport"><el-icon><Check /></el-icon>{{ saving ? '保存中' : editingId ? '保存新版本' : '保存报表' }}</button>
    </footer>
 
    <CompareReportHistoryDialog v-model="historyVisible" :report-id="editingId" />
 
    <el-dialog v-model="testDialogVisible" class="test-dialog" title="添加对比" width="540px" align-center destroy-on-close>
      <div class="compare-select-form">
        <label><span>选择测试</span><el-select v-model="selectedCandidateId" filterable clearable :loading="candidatesLoading" placeholder="输入测试名称或ID搜索" @change="syncDialogDefaults"><el-option v-for="item in candidateTests" :key="item.id" :label="`${item.name}(${item.id})`" :value="item.id" /></el-select></label>
        <label><span>选择电池</span><el-select v-model="selectedBatteryNo" placeholder="请选择" :disabled="!selectedCandidateId" @change="selectedCycle = cycleChoices[0] ?? null; selectedProcess = processChoices[0] || ''"><el-option v-for="item in batteryChoices" :key="item" :label="item" :value="item" /></el-select></label>
        <label><span>选择循环</span><el-select v-model="selectedCycle" placeholder="请选择" :disabled="!selectedCandidateId" @change="selectedProcess = processChoices[0] || ''"><el-option v-for="item in cycleChoices" :key="item" :label="`${item}`" :value="item" /></el-select></label>
        <label><span>选择工步</span><div class="control-stack"><el-select v-model="selectedProcess" placeholder="请选择" :disabled="!selectedCandidateId"><el-option v-for="item in processChoices" :key="item" :label="item" :value="item" /></el-select></div></label>
        <p v-if="candidatesError" class="select-error">{{ candidatesError }}</p><p v-else-if="!candidatesLoading && !candidateTests.length" class="select-empty">暂无检测完成且有已保存数据的测试</p>
      </div>
      <template #footer><div class="dialog-footer-left"><button class="primary-button" type="button" @click="addSelectedTest"><el-icon><Check /></el-icon>添加</button></div></template>
    </el-dialog>
 
    <el-dialog v-model="templateDialogVisible" class="template-dialog" :title="templateMode === 'battery' ? '选择电池组字段模板' : '选择特殊字段模板'" :width="templateMode === 'battery' ? '720px' : '560px'" align-center>
      <div v-if="templateMode === 'battery'" class="battery-template-editor">
        <label class="battery-template-select"><span>选择模板</span><el-select v-model="selectedBatteryTemplateName" @change="switchBatteryTemplate"><el-option v-for="name in batteryTemplateNames" :key="name" :label="name" :value="name" /></el-select></label>
        <el-checkbox-group v-if="batteryTemplateFieldOptions.length" v-model="selectedBatteryTemplateFieldIds" class="battery-template-fields" @change="applyBatteryTemplateFields">
          <el-checkbox v-for="field in batteryTemplateFieldOptions" :key="field.id" :value="field.id" :disabled="field.status === '禁用'" :title="`${field.name}(${field.type},${field.status})`">{{ field.name }}</el-checkbox>
        </el-checkbox-group>
        <div v-else class="template-empty">暂无字段,请先到电池组字段管理中添加字段</div>
      </div>
      <el-radio-group v-else v-model="selectedTemplateKey" class="template-options"><el-radio v-for="item in fieldTemplates" :key="item.key" :value="item.key" border>{{ item.name }}({{ item.fields.join('、') }})</el-radio></el-radio-group>
      <template #footer><div v-if="templateMode === 'battery'" class="battery-template-actions"><button class="primary-button" type="button" @click="applyFieldTemplate"><el-icon><Check /></el-icon>确认</button></div><div v-else><button class="secondary-button" type="button" @click="templateDialogVisible = false">取消</button><button class="primary-button" type="button" @click="applyFieldTemplate">应用字段</button></div></template>
    </el-dialog>
  </div>
</template>
 
<style scoped>
.compare-form-page { width: 100%; padding-bottom: 80px; }
.compare-form-page.is-readonly :deep(.el-input), .compare-form-page.is-readonly :deep(.el-textarea) { pointer-events: none; }
.compare-form-page.is-readonly :deep(.el-input__wrapper), .compare-form-page.is-readonly :deep(.el-textarea__inner) { background: #f3f6f8; box-shadow: 0 0 0 1px #d8e1e9 inset; }
.page-tools { height: 34px; display: flex; align-items: center; justify-content: space-between; }
.page-tools > span { color: #7f8d99; font-size: 10px; font-weight: 600; }
.back-button { display: inline-flex; align-items: center; gap: 6px; border: 0; color: #52606d; background: transparent; font-size: 13px; cursor: pointer; }
.back-button:hover { color: var(--blue); }
.primary-button, .secondary-button { height: 34px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 0 13px; border: 1px solid transparent; border-radius: 3px; font-size: 13px; font-weight: 500; cursor: pointer; white-space: nowrap; }
.primary-button { color: #fff; background: var(--blue); border-color: var(--blue); }
.primary-button:hover { background: #176fcb; border-color: #176fcb; }
.primary-button:disabled { opacity: .55; cursor: wait; }
.secondary-button { color: #52606d; background: #fff; border-color: var(--line-strong); }
.secondary-button:hover { color: var(--blue); border-color: #9dc8f5; }
.report-name-panel, .compare-info-panel, .detail-panel, .metrics-panel { background: #fff; border: 1px solid #d8e1e9; }
.report-name-panel { padding: 18px 22px; margin-bottom: 16px; }
.report-name-panel label + label { margin-top: 12px; }
.report-name-panel > span { display: block; margin-top: 12px; overflow-wrap: anywhere; }
.series-swatch { flex: 0 0 12px; width: 12px; height: 12px; display: inline-block; }
.report-name-panel label { display: grid; grid-template-columns: 72px minmax(260px, 420px); align-items: center; gap: 12px; }
.report-name-panel label > span, .detail-meta label > span { color: #52606d; font-size: 12px; font-weight: 500; }
.report-name-panel :deep(.el-input__wrapper), .detail-meta :deep(.el-input__wrapper), .detail-meta :deep(.el-select__wrapper), .field-table :deep(.el-input__wrapper), .field-table :deep(.el-select__wrapper) { min-height: 34px; border-radius: 3px; box-shadow: 0 0 0 1px #d8e1e9 inset; background: #f8fafc; }
.panel-heading { min-height: 48px; display: flex; align-items: center; justify-content: space-between; padding: 0 24px; border-bottom: 1px solid var(--line); }
.panel-heading > div { display: flex; align-items: center; gap: 9px; color: #26333f; font-size: 13px; }
.panel-heading > div::before { content: ''; width: 3px; height: 16px; background: #2b78a3; }
.compare-info-panel, .detail-panel { margin-bottom: 16px; padding-bottom: 18px; }
.compare-table-wrap, .field-table-wrap { overflow-x: auto; padding: 18px 24px 0; }
.compare-table, .field-table { width: 100%; min-width: 820px; table-layout: fixed; border-collapse: collapse; color: #52606d; font-size: 13px; }
.compare-table th, .compare-table td, .field-table th, .field-table td { height: 42px; padding: 0 12px; border: 1px solid #cbd8e4; text-align: center; white-space: nowrap; }
.compare-table th, .field-table th { color: #fff; background: #3c6497; font-size: 12px; font-weight: 600; }
.compare-table th:nth-child(1) { width: 22%; } .compare-table th:nth-child(2) { width: 17%; } .compare-table th:nth-child(3) { width: 18%; } .compare-table th:nth-child(4) { width: 17%; } .compare-table th:nth-child(5) { width: 14%; } .compare-table th:last-child { width: 12%; }
.compare-table tbody tr:hover, .field-table tbody tr:hover { background: #f7fbff; }
.delete-link { border: 0; color: #d15b5b; background: transparent; font-size: 12px; cursor: pointer; }
.delete-link:hover { text-decoration: underline; }
.compact-button { margin: 16px 24px 0; }
.detail-meta { display: grid; grid-template-columns: minmax(280px, 520px); gap: 22px; padding: 18px 24px 0; }
.detail-meta label { display: grid; grid-template-columns: 48px minmax(0, 1fr); align-items: center; gap: 10px; }
.field-table { min-width: 900px; }
.field-table th:first-child, .field-table td:first-child { width: 140px; text-align: left; }
.field-table th:last-child, .field-table td:last-child { width: 74px; }
.field-table .sample-row td { background: #fbfdff; }
.field-table .detail-meta-row td { background: #fbfdff; color: #26333f; }
.field-table .detail-meta-row td:not(:first-child) { font-weight: 500; }
.field-table :deep(.el-select), .field-table :deep(.el-input) { width: 100%; }
.detail-actions { display: flex; flex-wrap: wrap; gap: 10px; padding: 16px 24px 0; }
.metrics-panel { padding: 0 24px 24px; }
.metric-switches { display: flex; flex-wrap: wrap; align-items: center; gap: 20px 28px; min-height: 58px; border-bottom: 1px solid var(--line); }
.metric-switches label { display: inline-flex; align-items: center; gap: 7px; color: #52606d; font-size: 12px; }
.metric-switches :deep(.el-switch) { --el-switch-on-color: #3978f6; }
.chart-legend-bar { min-height: 52px; display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; border-bottom: 1px solid var(--line); }
.chart-legend-bar > strong { color: #26333f; font-size: 12px; font-weight: 600; }
.chart-legend-item { display: inline-flex; align-items: center; gap: 7px; min-width: 0; color: #52606d; font-size: 12px; }
.chart-legend-item span { max-width: 360px; overflow-wrap: anywhere; }
.legend-color-picker { width: 18px; height: 18px; display: inline-flex; align-items: center; justify-content: center; }
.legend-color-picker :deep(.el-color-picker__trigger) { width: 14px !important; height: 14px !important; padding: 0 !important; border: 0 !important; border-radius: 2px; background: transparent !important; box-shadow: none !important; overflow: hidden; }
.legend-color-picker :deep(.el-color-picker__color) { width: 14px; height: 14px; border: 0; border-radius: 2px; box-shadow: 0 0 0 1px rgba(36, 54, 71, .18); }
.legend-color-picker :deep(.el-color-picker__color-inner) { border-radius: 2px; }
.legend-color-picker :deep(.el-color-picker__icon), .legend-color-picker :deep(.el-color-picker__empty), .legend-color-picker :deep(.el-color-picker__trigger svg), .legend-color-picker :deep(.el-color-picker__trigger .el-icon) { display: none !important; }
.legend-color-picker :deep(.el-color-picker__trigger:hover) { box-shadow: 0 0 0 2px rgba(43, 120, 163, .24) !important; }
:global(.legend-color-popper.el-popper) { padding: 0 !important; border: 1px solid #b9c9d8 !important; border-radius: 4px !important; box-shadow: 0 10px 24px rgba(25, 48, 69, .18) !important; overflow: hidden; }
:global(.legend-color-popper .el-color-picker-panel) { border: 0 !important; box-shadow: none !important; }
.charts-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; padding-top: 18px; }
.chart-card { min-width: 0; border: 1px solid #edf1f5; background: #fff; }
.chart-card header { height: 38px; display: flex; align-items: center; gap: 18px; padding: 0 14px; color: #52606d; font-size: 11px; }
.chart-card header strong { margin-right: auto; color: #26333f; font-size: 13px; }
.metric-chart { width: 100%; height: 210px; }
.form-actions { position: sticky; bottom: 0; z-index: 20; min-height: 62px; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; margin-top: 16px; padding: 10px 16px; background: rgba(234, 240, 246, .96); border-top: 1px solid #cbd9e5; }
.form-actions .primary-button, .form-actions .secondary-button { min-width: 110px; }
.save-button { min-width: 110px; }
.compare-form-page :deep(.el-dialog) { max-width: calc(100vw - 28px); border-radius: 4px; }
.compare-form-page :deep(.el-dialog__header) { margin: 0; padding: 17px 20px; border-bottom: 1px solid var(--line); }
.compare-form-page :deep(.el-dialog__body) { padding: 20px; }
.compare-form-page :deep(.el-dialog__footer) { padding: 14px 20px; border-top: 1px solid var(--line); }
.compare-select-form { display: grid; gap: 14px; padding: 2px 16px 6px; }
.compare-select-form label { display: grid; grid-template-columns: 72px minmax(0, 1fr); align-items: start; gap: 12px; }
.compare-select-form label > span { padding-top: 9px; color: #52606d; font-size: 12px; }
.compare-select-form :deep(.el-select), .compare-select-form :deep(.el-input) { width: 100%; }
.compare-select-form :deep(.el-input__wrapper), .compare-select-form :deep(.el-select__wrapper) { min-height: 34px; border-radius: 3px; box-shadow: 0 0 0 1px #d8e1e9 inset; background: #f8fafc; }
.control-stack { display: grid; gap: 8px; }
.select-hint { color: #8a97a3; font-size: 11px; line-height: 1.4; }
.dialog-footer-left { display: flex; justify-content: flex-start; }
.template-options { display: grid; gap: 12px; }
.template-options :deep(.el-radio) { width: 100%; height: auto; margin: 0; padding: 12px; white-space: normal; }
.battery-template-editor { min-height: 340px; padding: 4px 22px 18px; }
.battery-template-select { width: min(390px, 100%); display: grid; grid-template-columns: 88px minmax(0, 1fr); align-items: center; gap: 12px; margin: 0 auto 28px; }
.battery-template-select > span { color: #52606d; font-size: 12px; font-weight: 600; }
.battery-template-select :deep(.el-select) { width: 100%; }
.battery-template-fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px 28px; }
.battery-template-fields :deep(.el-checkbox) { min-width: 0; margin: 0; overflow: hidden; }
.battery-template-fields :deep(.el-checkbox__label) { min-width: 0; overflow: hidden; color: #52606d; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
.template-empty { padding: 56px 18px; color: #8795a3; text-align: center; border: 1px dashed #ccd9e5; }
.battery-template-actions, .template-dialog :deep(.el-dialog__footer) > div { display: flex; align-items: center; justify-content: center; gap: 12px; }
.battery-template-actions button { min-width: 96px; }
@media (max-width: 900px) { .charts-grid { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 680px) {
  .report-name-panel { padding: 14px 12px; }
  .report-name-panel label, .detail-meta { grid-template-columns: minmax(0, 1fr); gap: 7px; }
  .panel-heading, .metrics-panel { padding-left: 12px; padding-right: 12px; }
  .compare-table-wrap, .field-table-wrap { padding-left: 12px; padding-right: 12px; }
  .compact-button { margin-left: 12px; }
  .detail-actions { padding-left: 12px; padding-right: 12px; }
  .metric-switches { gap: 14px; }
  .chart-legend-bar { align-items: flex-start; flex-direction: column; gap: 10px; padding: 12px 0; }
  .form-actions { justify-content: stretch; padding: 12px; }
  .form-actions button { flex: 1; }
  .battery-template-editor { padding: 0; }
  .battery-template-select { grid-template-columns: minmax(0, 1fr); gap: 7px; }
  .battery-template-fields { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 12px; }
  .battery-template-actions { flex-wrap: wrap; }
}
</style>