EnergyReportDialog.vue
35.5 KB
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
<template>
<el-dialog
:model-value="visible"
@update:model-value="$emit('update:visible', $event)"
title=""
width="calc(100vw - 40px)"
:style="{ maxWidth: '1400px' }"
top="3vh"
destroy-on-close
class="ereport-dialog"
>
<template #header>
<div class="dialog-header">
<span class="title-text">{{ device?.name || dtuSn }} 查询方式:</span>
<el-radio-group v-model="queryMode" size="small" @change="fetchData">
<el-radio-button value="day">日查询</el-radio-button>
</el-radio-group>
<el-date-picker v-model="selectedDate" type="date" placeholder="" size="small"
style="width:160px;margin-left:8px;margin-right: 8px;" value-format="YYYY-MM-DD" @change="fetchData" />
<el-button type="primary" size="small" @click="fetchData">查询</el-button>
<div style="flex:1"></div>
</div>
</template>
<div class="report-body" v-loading="loading">
<!-- 设备运行状态图 -->
<div class="chart-section">
<div class="section-title">
设备运行状态图:
<span class="legend-item"><i class="dot g"></i>运行</span>
<span class="legend-item"><i class="dot r"></i>停机</span>
<span class="legend-item"><i class="dot y"></i>待机</span>
<span class="legend-item"><i class="dot gy"></i>离线</span>
</div>
<div class="timeline-canvas-wrap" ref="timelineWrapRef"
@mouseenter="onTimelineMouseEnter" @mouseleave="onTimelineMouseLeave"
@wheel.prevent="onTimelineWheel">
<canvas ref="timelineCanvasRef"></canvas>
<div v-if="timelineHover.show" class="tl-tooltip" :class="{ 'tt-below': timelineHover.ttBelow }"
:style="{ left: timelineHover.x + 'px', top: timelineHover.y + 'px' }">
<div class="tt-row"><span class="tt-label">开始时间</span><span class="tt-val">{{ ttData.startTime }}</span></div>
<div class="tt-row"><span class="tt-label">结束时间</span><span class="tt-val">{{ ttData.endTime }}</span></div>
<div class="tt-row"><span class="tt-label">状态</span><span class="tt-val" :class="'status-' + ttData.runStatus"><i :class="['dot', statusDotClass(ttData.runStatus)]"></i>{{ statusLabel(ttData.runStatus) }}</span></div>
<div class="tt-row"><span class="tt-label">持续时长</span><span class="tt-val">{{ ttData.duration }}</span></div>
</div>
</div>
</div>
<!-- 设备用电量 -->
<div class="chart-section">
<div class="section-title">设备用电量:</div>
<div class="bar-canvas-wrap" @mousemove="onBarMouseMove" @mouseleave="onBarMouseLeave">
<canvas ref="barCanvasRef"></canvas>
<div v-if="barHover.show" class="bar-tooltip" :style="{ left: barHover.x + 'px', top: barHover.y + 'px' }">
<div class="btt-row"><span class="btt-label">时段</span><span class="btt-val">{{ barTtData.hour }}时</span></div>
<div class="btt-row"><span class="btt-label">用电量</span><span class="btt-val btt-highlight">{{ barTtData.value }} kw.h</span></div>
</div>
</div>
</div>
<!-- 底部:明细表格 + 饼图 -->
<div class="bottom-row">
<div class="detail-panel">
<div class="section-title">设备运行状态明细</div>
<div class="detail-table-wrap">
<table class="detail-table">
<thead>
<tr><th>开始时间</th><th>状态</th><th>运行时长</th></tr>
</thead>
<tbody>
<tr v-for="(item, idx) in apiData.oeeData.list" :key="idx">
<td>{{ item.startTime ? item.startTime.slice(0, 19) : '' }}</td>
<td><i :class="['dot', statusDotClass(item.runStatus)]"></i>{{ statusLabel(item.runStatus) }}</td>
<td>{{ formatDuration(item.duration) }}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="pie-panel">
<div class="pie-canvas-wrap">
<canvas ref="pieCanvasRef" @mousemove="onPieMouseMove" @mouseleave="onPieMouseLeave"></canvas>
<div v-if="pieHover.show" class="pie-tooltip" :style="{ left: pieHover.x + 'px', top: pieHover.y + 'px' }">
<div class="ptt-row"><span class="ptt-label">状态</span><span class="ptt-val" :style="{ color: STATUS_COLORS[pieTtData.status] }"><i :class="['dot', statusDotClass(pieTtData.status)]"></i>{{ statusLabel(pieTtData.status) }}</span></div>
<div class="ptt-row"><span class="ptt-label">占比</span><span class="ptt-val ptt-highlight">{{ pieTtData.percent }}%</span></div>
</div>
</div>
<div class="stats-area">
<div class="stat-row"><span class="stat-label">总时长:</span><span class="stat-val">{{ totalDurationFormatted }}</span></div>
<div class="stat-row"><span class="stat-label">总用电量:</span><span class="stat-val">{{ totalKwh }}kw.h</span></div>
</div>
</div>
</div>
</div>
</el-dialog>
</template>
<script setup>
import { ref, reactive, computed, watch, nextTick, onBeforeUnmount, inject } from 'vue'
const props = defineProps({ visible: Boolean, device: Object })
const emit = defineEmits(['update:visible'])
const loading = ref(false)
const queryMode = ref('day')
const selectedDate = ref(new Date().toISOString().slice(0, 10))
const unitSelect = ref('single')
const dtuSn = computed(() => props.device?._raw?.dtuSn || props.device?.name || '')
// 从全局获取corpCode
const corpCode = inject('corpCode')
import { getApiUrl } from '../config/api.js'
function withCorpCode(url) {
const fullUrl = getApiUrl(url)
if (!corpCode.value) return fullUrl
const sep = fullUrl.includes('?') ? '&' : '?'
return `${fullUrl}${sep}corpCode=${encodeURIComponent(corpCode.value)}`
}
// API 数据
const apiData = reactive({
oeeData: { list: [], statusStats: [], totalDurationSeconds: 0, totalDurationFormatted: '' },
kwhData: { list: [], totalKwh: 0 },
date: ''
})
const totalDurationFormatted = computed(() => apiData.oeeData.totalDurationFormatted || '0秒')
const totalKwh = computed(() => apiData.kwhData.totalKwh ?? 0)
function formatDuration(seconds) {
if (!seconds && seconds !== 0) return '0秒'
seconds = Number(seconds)
if (seconds <= 0) return '0秒'
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
const s = seconds % 60
let str = ''
if (h > 0) str += h + '时'
if (m > 0) str += m + '分'
if (s > 0 || !str) str += s + '秒'
return str
}
const STATUS_MAP = { 0: '离线', 1: '停机', 2: '运行', 3: '待机' }
function statusLabel(s) { return STATUS_MAP[s] || '未知' }
function statusDotClass(s) { return { 0: 'gy', 1: 'r', 2: 'g', 3: 'y' }[s] || 'gy' }
const STATUS_COLORS = {
0: '#909399',
1: '#e74c3c',
2: '#67c23a',
3: '#c5d94e'
}
const STATUS_COLORS_HOVER = {
0: '#7a7d82',
1: '#d63a3a',
2: '#4cae4c',
3: '#b8cc38'
}
// Canvas refs
const timelineCanvasRef = ref(null)
const timelineWrapRef = ref(null)
const barCanvasRef = ref(null)
const pieCanvasRef = ref(null)
let resizeObserver = null
let canvasRAF = null
// ==================== 饼图 Hover 交互 ====================
const pieHover = reactive({ show: false, x: 0, y: 0, index: -1 })
const pieTtData = computed(() => {
if (!pieHover.show || pieHover.index < 0) return { status: '-', percent: '-' }
const stats = apiData.oeeData.statusStats || []
const item = stats[pieHover.index]
if (!item) return { status: '-', percent: '-' }
return { status: item.status, percent: (item.percent || 0).toFixed(2) }
})
// 扇区角度范围缓存(用于碰撞检测)
let pieAngleRanges = []
function onPieMouseMove(e) {
const canvas = pieCanvasRef.value
if (!canvas) return
const rect = canvas.getBoundingClientRect()
const mx = e.clientX - rect.left
const my = e.clientY - rect.top
// 转换为 canvas 内部坐标(考虑 dpr 缩放)
const scaleX = canvas.width / rect.width
const scaleY = canvas.height / rect.height
const px = mx * scaleX
const py = my * scaleY
let hoveredIdx = -1
// 从后往前检测
for (let i = pieAngleRanges.length - 1; i >= 0; i--) {
const seg = pieAngleRanges[i]
const dx = px - seg.cx
const dy = py - seg.cy
const dist = Math.sqrt(dx * dx + dy * dy)
if (dist > seg.radius) continue
let mouseAngle = Math.atan2(dy, dx)
// 角度范围判断(统一到 [-PI, PI] 后比较)
function inRange(a, sa, ea) {
// 将所有角归一化到 [sa, sa + 2PI) 范围
let na = a - sa
let nea = ea - sa
if (nea < 0) nea += Math.PI * 2
if (na < 0) na += Math.PI * 2
return na >= 0 && na <= nea
}
if (inRange(mouseAngle, seg.startAngle, seg.endAngle)) {
hoveredIdx = i
break
}
}
if (hoveredIdx !== pieHover.index) {
pieHover.index = hoveredIdx
pieHover.show = hoveredIdx >= 0
if (hoveredIdx >= 0) {
const ttW = 120
// 默认在鼠标右侧
let tx = mx + 10
let ty = my - 54
// 右边界检查
if (tx + ttW > rect.width - 4) tx = mx - ttW - 8
// 上边界检查
if (ty < 4) ty = my + 14
pieHover.x = Math.max(4, tx)
pieHover.y = Math.max(4, ty)
}
drawPieChart()
}
}
function onPieMouseLeave() {
pieHover.show = false
pieHover.index = -1
drawPieChart()
}
// ==================== 柱状图 Hover 交互 ====================
const barHover = reactive({ show: false, x: 0, y: 0, index: -1 })
const barTtData = computed(() => {
if (!barHover.show || barHover.index < 0) return { hour: '-', value: '-' }
const list = apiData.kwhData.list || []
const item = list[barHover.index]
if (!item) return { hour: '-', value: '-' }
return { hour: barHover.index + 1, value: item.value ?? 0 }
})
// 柱子碰撞矩形缓存
let barRects = []
function onBarMouseMove(e) {
const canvas = barCanvasRef.value
if (!canvas) return
const rect = canvas.getBoundingClientRect()
const mx = e.clientX - rect.left
const my = e.clientY - rect.top
let hoveredIdx = -1
for (let i = 0; i < barRects.length; i++) {
const br = barRects[i]
if (mx >= br.x && mx <= br.x + br.w && my >= br.y && my <= br.y + br.h) {
hoveredIdx = i
break
}
}
if (hoveredIdx !== barHover.index) {
barHover.index = hoveredIdx
barHover.show = hoveredIdx >= 0
if (hoveredIdx >= 0) {
const br = barRects[hoveredIdx]
// tooltip 定位在柱子上方居中
const ttW = 140
let tx = br.x + br.w / 2 - ttW / 2
tx = Math.max(4, Math.min(tx, rect.width - ttW - 4))
barHover.x = tx
barHover.y = br.y - 70
}
drawBarChart()
}
}
function onBarMouseLeave() {
barHover.show = false
barHover.index = -1
drawBarChart()
}
// ==================== 时间轴 缩放系统 ====================
const TL_H = 104 // 时间轴高度
const zoomLevel = ref(1)
const minZoom = 0.001
const maxZoom = 1
const viewOffsetX = ref(0)
let tlContainerW = 900
// 原始段数据(数据空间坐标,不受缩放影响)
const rawSegments = computed(() => {
const list = apiData.oeeData.list || []
if (!list.length) return []
const baseDate = apiData.date || selectedDate.value
const dayStartMs = new Date(baseDate + ' 00:00:00').getTime()
const daySpanMs = 86400000
const plotLeft = 55
const plotW = tlContainerW - plotLeft - 10
return list.map((item, idx) => {
const st = new Date(item.startTime).getTime()
let et = item.endTime ? new Date(item.endTime).getTime() : st + (item.duration || 0) * 1000
const startX = ((st - dayStartMs) / daySpanMs) * plotW + plotLeft
const endX = ((et - dayStartMs) / daySpanMs) * plotW + plotLeft
const x = Math.max(plotLeft, startX)
const w = Math.max(1, endX - x)
return {
x, w,
index: idx,
runStatus: item.runStatus,
startTime: item.startTime,
endTime: item.endTime,
duration: item.duration,
startTimeText: item.startTime ? item.startTime.slice(0, 19) : '',
endTimeText: item.endTime ? item.endTime.slice(0, 19) : '',
}
})
})
// ==================== 时间轴 Hover 交互 ====================
const timelineHover = reactive({ show: false, x: 0, y: 0, segIndex: -1, ttBelow: false })
const ttData = computed(() => {
if (!timelineHover.show || timelineHover.segIndex < 0) return {}
const list = apiData.oeeData.list || []
const item = list[timelineHover.segIndex]
if (!item) return {}
return {
startTime: item.startTime ? item.startTime.slice(0, 19) : '-',
endTime: item.endTime ? item.endTime.slice(0, 19) : '-',
runStatus: item.runStatus,
duration: formatDuration(item.duration),
}
})
function onTimelineWheel(e) {
const wrap = timelineWrapRef.value
if (!wrap) return
const rect = wrap.getBoundingClientRect()
const mx = e.clientX - rect.left
// 鼠标位置 → 数据空间坐标
const mouseDataX = mx * zoomLevel.value + viewOffsetX.value
// 向上滚动(deltaY < 0)放大,向下(deltaY > 0)缩小
const delta = e.deltaY < 0 ? 0.8 : 1.25
const nextZ = Math.max(minZoom, Math.min(maxZoom, zoomLevel.value * delta))
// 以鼠标位置为中心缩放,调整偏移量
viewOffsetX.value = mouseDataX - mx * nextZ
zoomLevel.value = nextZ
}
function onTimelineMouseEnter() {
const canvas = timelineCanvasRef.value
if (!canvas) return
canvas.addEventListener('mousemove', onTimelineMouseMove)
}
function onTimelineMouseLeave() {
const canvas = timelineCanvasRef.value
if (!canvas) return
canvas.removeEventListener('mousemove', onTimelineMouseMove)
timelineHover.show = false
timelineHover.segIndex = -1
drawTimelineChart()
}
function onTimelineMouseMove(e) {
const wrap = timelineWrapRef.value
if (!wrap) return
const rect = wrap.getBoundingClientRect()
const mx = e.clientX - rect.left
const my = e.clientY - rect.top
const z = zoomLevel.value
const vo = viewOffsetX.value
// 屏幕坐标 → 数据空间坐标
const dataX = mx * z + vo
// 条带区域(与 drawTimelineChart 中一致)
const barY = 24
const barH = 46
let hoveredIdx = -1
// 从后往前遍历(后面的段覆盖前面的)
for (let i = rawSegments.value.length - 1; i >= 0; i--) {
const seg = rawSegments.value[i]
if (dataX >= seg.x && dataX <= seg.x + seg.w && my >= barY && my <= barY + barH) {
hoveredIdx = seg.index
break
}
}
if (hoveredIdx !== timelineHover.segIndex) {
timelineHover.segIndex = hoveredIdx
timelineHover.show = hoveredIdx >= 0
if (hoveredIdx >= 0) {
const seg = rawSegments.value.find(s => s.index === hoveredIdx)
if (seg) {
// 计算该段在屏幕上的位置用于 tooltip 定位
const sx = (seg.x - vo) / z
const sw = seg.w / z
const ttW = 220
let tx = sx + sw / 2 - ttW / 2
tx = Math.max(2, Math.min(tx, rect.width - ttW - 2))
const ttH = 100
const aboveY = barY - ttH - 12
timelineHover.ttBelow = aboveY < 4
timelineHover.x = tx
timelineHover.y = timelineHover.ttBelow ? barY + barH + 12 : aboveY
}
}
drawTimelineChart()
}
}
// 获取数据
async function fetchData() {
if (!dtuSn.value || !selectedDate.value) return
loading.value = true
try {
const res = await fetch(withCorpCode(`/api/energy/detail?dtuSn=${dtuSn.value}&date=${selectedDate.value}`))
const data = await res.json()
if (data.code === 200) {
Object.assign(apiData.oeeData, data.oeeData || { list: [], statusStats: [], totalDurationSeconds: 0, totalDurationFormatted: '' })
Object.assign(apiData.kwhData, data.kwhData || { list: [], totalKwh: 0 })
apiData.date = data.date || selectedDate.value
await nextTick()
zoomLevel.value = 1
viewOffsetX.value = 0
await nextTick()
updateTimelineSize()
drawAllCharts()
}
} catch (err) {
console.error('获取能耗详情失败:', err)
} finally {
loading.value = false
}
}
watch(() => props.visible, async (val) => {
if (val) {
await nextTick()
initCanvasObserver()
fetchData()
} else {
destroyCanvasObserver()
timelineHover.show = false
}
})
// 监听缩放/偏移/数据变化重绘时间轴
watch([zoomLevel, viewOffsetX, () => apiData.oeeData.list], () => {
if (props.visible) {
if (canvasRAF) cancelAnimationFrame(canvasRAF)
canvasRAF = requestAnimationFrame(() => drawTimelineChart())
}
}, { deep: true })
function updateTimelineSize() {
const wrap = timelineWrapRef.value
if (!wrap) return
tlContainerW = wrap.clientWidth - 12 // 减去 padding
}
function initCanvasObserver() {
destroyCanvasObserver()
const dialogBody = document.querySelector('.ereport-dialog .el-dialog__body')
if (!dialogBody) return
resizeObserver = new ResizeObserver(() => {
if (canvasRAF) cancelAnimationFrame(canvasRAF)
canvasRAF = requestAnimationFrame(() => {
updateTimelineSize()
drawAllCharts()
})
})
resizeObserver.observe(dialogBody)
}
function destroyCanvasObserver() {
if (resizeObserver) { resizeObserver.disconnect(); resizeObserver = null }
if (canvasRAF) { cancelAnimationFrame(canvasRAF); canvasRAF = null }
}
onBeforeUnmount(() => destroyCanvasObserver())
// ==================== Canvas 绘制 ====================
function getDpr() { return window.devicePixelRatio || 1 }
function setupCanvas(canvas, w, h) {
const dpr = getDpr()
canvas.width = w * dpr
canvas.height = h * dpr
canvas.style.width = w + 'px'
canvas.style.height = h + 'px'
const ctx = canvas.getContext('2d')
ctx.scale(dpr, dpr)
return ctx
}
function drawAllCharts() {
drawTimelineChart()
drawBarChart()
drawPieChart()
}
// ---------- 1. 设备运行状态图(甘特图)+ 缩放 + hover放大 ----------
function drawTimelineChart() {
const canvas = timelineCanvasRef.value
if (!canvas) return
const wrap = timelineWrapRef.value
const w = wrap ? wrap.clientWidth - 12 : tlContainerW
const h = TL_H
const ctx = setupCanvas(canvas, w, h)
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, w, h)
const list = apiData.oeeData.list || []
if (list.length === 0) {
ctx.fillStyle = '#999'
ctx.font = '13px sans-serif'
ctx.textAlign = 'center'
ctx.fillText('暂无数据', w / 2, h / 2)
return
}
// 布局参数(与 OeeDialog 一致)
const labelLeft = 50 // "时刻" 标签 X
const plotLeft = 55 // 数据区起点
const plotW = w - plotLeft - 10
const barY = 24 // 条带顶部
const barH = 46 // 默认条带高度
const axisY = barY + barH + 8 // 分隔线 Y
const timeLabelY = h - 4 // 时间标签 Y
const z = zoomLevel.value
const vo = viewOffsetX.value
// "时刻" 标签
ctx.fillStyle = '#999'
ctx.font = '12px sans-serif'
ctx.textAlign = 'center'
ctx.fillText('时刻', labelLeft - vo / z, 16)
// ===== 时间轴标签 — 根据缩放级别动态选择步长 =====
const totalSec = 24 * 3600
const visSpanSec = Math.max(60, (w * z / plotW) * totalSec)
let stepSec = 14400 // 默认 4 小时
if (visSpanSec <= 120) stepSec = 30
else if (visSpanSec <= 300) stepSec = 60
else if (visSpanSec <= 600) stepSec = 300
else if (visSpanSec <= 1800) stepSec = 600
else if (visSpanSec <= 3600) stepSec = 900
else if (visSpanSec <= 7200) stepSec = 1800
else if (visSpanSec <= 28800) stepSec = 3600
else stepSec = 7200
ctx.font = '11px sans-serif'
ctx.fillStyle = '#666'
ctx.textAlign = 'center'
const leftSec = ((vo - plotLeft) / plotW) * totalSec
let firstSec = Math.floor(leftSec / stepSec) * stepSec
if (firstSec < 0) firstSec = 0
for (let s = firstSec; s <= totalSec + stepSec * 2; s += stepSec) {
const dataPx = plotLeft + (s / totalSec) * plotW
const screenPx = (dataPx - vo) / z
if (screenPx < -50 || screenPx > w + 50) continue
const hh = Math.floor(s / 3600)
const mm = Math.floor((s % 3600) / 60)
const ss = s % 60
if (stepSec < 60) {
ctx.fillText(`${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')}:${String(ss).padStart(2,'0')}`, screenPx, timeLabelY)
} else {
ctx.fillText(`${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')}`, screenPx, timeLabelY)
}
}
// 分隔线(条带与时间轴之间)
ctx.strokeStyle = '#ddd'
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo((plotLeft - vo) / z, axisY)
ctx.lineTo(((plotLeft + plotW) - vo) / z, axisY)
ctx.stroke()
// ===== 绘制条带 =====
const hoverIdx = timelineHover.segIndex
// 先画非 hover 段
rawSegments.value.forEach((seg) => {
if (seg.index === hoverIdx) return
drawSegment(ctx, seg, z, vo, w, barY, barH, false)
})
// 再画 hover 段(最上层,有放大效果)
if (hoverIdx >= 0) {
const hoverSeg = rawSegments.value.find(s => s.index === hoverIdx)
if (hoverSeg) {
drawSegment(ctx, hoverSeg, z, vo, w, barY, barH, true)
}
}
}
/** 绘制单个色段 */
function drawSegment(ctx, seg, z, vo, canvasW, barY, barH, isHover) {
const sx = (seg.x - vo) / z
const sw = seg.w / z
// 裁剪不可见段
if (sx + sw < -1 || sx > canvasW + 1) return
// hover 放大参数
let finalX = sx
let finalY = barY
let finalW = sw
let finalH = barH
if (isHover) {
finalH = barH + 18 // 高度增加
finalY = barY - 9 // 向上偏移(居中放大)
finalX = sx - 2 // 左右微扩展
finalW = sw + 4
}
ctx.save()
if (isHover) {
ctx.shadowColor = 'rgba(0, 0, 0, 0.35)'
ctx.shadowBlur = 16
ctx.shadowOffsetX = 0
ctx.shadowOffsetY = 4
ctx.strokeStyle = 'rgba(255,255,255,0.7)'
ctx.lineWidth = 2
}
ctx.fillStyle = isHover
? (STATUS_COLORS_HOVER[seg.runStatus] || STATUS_COLORS[seg.runStatus])
: (STATUS_COLORS[seg.runStatus] || '#ccc')
// hover 段用圆角,非 hover 用直角(与 OEE 一致风格)
if (isHover) {
ctx.beginPath()
ctx.roundRect(finalX, finalY, finalW, finalH, 5)
ctx.fill()
ctx.stroke()
} else {
ctx.globalAlpha = 0.9
ctx.fillRect(finalX, finalY, finalW, finalH)
}
ctx.restore()
}
// ---------- 2. 设备用电量柱状图 + hover ----------
function drawBarChart() {
const canvas = barCanvasRef.value
if (!canvas) return
const wrap = canvas.parentElement
const w = wrap.clientWidth
const h = 184
const ctx = setupCanvas(canvas, w, h)
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, w, h)
const kwhList = apiData.kwhData.list || []
// 清空碰撞矩形
barRects = []
if (kwhList.length === 0) {
ctx.fillStyle = '#999'
ctx.font = '13px sans-serif'
ctx.textAlign = 'center'
ctx.fillText('暂无数据', w / 2, h / 2)
return
}
const padLeft = 36
const padRight = 16
const padTop = 20
const padBottom = 32
const chartW = w - padLeft - padRight
const chartH = h - padTop - padBottom
const maxVal = Math.max(...kwhList.map(d => d.value || 0), 70)
const niceMax = Math.ceil(maxVal / 10) * 10
// 网格线 + Y轴标签
ctx.strokeStyle = '#eee'
ctx.lineWidth = 0.5
ctx.fillStyle = '#999'
ctx.font = '11px sans-serif'
ctx.textAlign = 'right'
for (let v = 0; v <= niceMax; v += 10) {
const y = padTop + chartH - (v / niceMax) * chartH
ctx.beginPath()
ctx.moveTo(padLeft, y)
ctx.lineTo(w - padRight, y)
ctx.stroke()
ctx.fillText(String(v), padLeft - 6, y + 4)
}
// X 轴线
ctx.strokeStyle = '#ddd'
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(padLeft, padTop + chartH)
ctx.lineTo(w - padRight, padTop + chartH)
ctx.stroke()
// 柱子参数
const barCount = kwhList.length
const totalGapRatio = 0.3
let barW_px = Math.max(4, (chartW / barCount) * (1 - totalGapRatio))
const gap = (chartW / barCount) * totalGapRatio
const hoverIdx = barHover.index
kwhList.forEach((item, i) => {
const val = item.value || 0
const x = padLeft + (i * (chartW / barCount)) + gap / 2
const barH_px = (val / niceMax) * chartH
const y = padTop + chartH - barH_px
// 存储碰撞矩形(默认尺寸)
barRects.push({ x, y, w: barW_px, h: barH_px })
// 判断是否 hover
const isHover = (i === hoverIdx)
if (isHover) {
// hover 柱:加宽、加深色、阴影、圆角
const hw = barW_px + 6
const hx = x - 3
ctx.save()
ctx.shadowColor = 'rgba(51, 126, 204, 0.4)'
ctx.shadowBlur = 14
ctx.shadowOffsetY = 3
ctx.fillStyle = '#2060a8'
ctx.beginPath()
ctx.roundRect(hx, y, hw, barH_px, 3)
ctx.fill()
ctx.restore()
// 数值标签加粗加大
ctx.fillStyle = '#2060a8'
ctx.font = 'bold 13px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(String(val), x + barW_px / 2, y - 7)
// X 轴标签高亮
ctx.fillStyle = '#2060a8'
ctx.font = 'bold 11px sans-serif'
ctx.fillText(String(i + 1), x + barW_px / 2, padTop + chartH + 16)
} else {
// 默认柱
ctx.fillStyle = '#337ecc'
ctx.globalAlpha = isHover ? 1 : 0.85
ctx.fillRect(x, y, barW_px, barH_px)
ctx.globalAlpha = 1
// 数值标签
if (val > 0) {
ctx.fillStyle = '#555'
ctx.font = '9px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(String(val), x + barW_px / 2, y - 4)
}
// X 轴标签
ctx.fillStyle = '#666'
ctx.font = '10px sans-serif'
ctx.textAlign = 'center'
ctx.fillText(String(i + 1), x + barW_px / 2, padTop + chartH + 16)
}
})
}
// ---------- 3. 实心饼图 + hover + 外部标签 ----------
function drawPieChart() {
const canvas = pieCanvasRef.value
if (!canvas) return
const wrap = canvas.parentElement
const w = wrap.clientWidth
const h = 230
const ctx = setupCanvas(canvas, w, h)
ctx.clearRect(0, 0, w, h)
const stats = apiData.oeeData.statusStats || []
pieAngleRanges = []
if (!stats.length || stats.every(s => !s.status && s.status !== 0)) {
ctx.fillStyle = '#999'
ctx.font = '12px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText('暂无数据', w / 2, h / 2)
return
}
const cx = w * 0.4
const cy = h * 0.52
const radius = Math.min(cx, cy) - 24
const MIN_SLICE_DEG = 2 // 0% 的扇区也给最小角度用于展示
// 计算每个扇区的角度(含 0% 最小角度)
const totalPct = stats.reduce((sum, s) => sum + (s.percent || 0), 0)
const sliceInfos = stats.map((statItem, i) => {
const pct = statItem.percent || 0
const deg = pct > 0 ? (pct / totalPct) * 360 : MIN_SLICE_DEG
return { index: i, status: statItem.status, percent: pct, deg }
})
// 归一化:如果全0则均分;否则按比例缩放非0的
const hasNonZero = sliceInfos.some(si => si.percent > 0)
if (!hasNonZero && sliceInfos.length > 0) {
const eqDeg = 360 / sliceInfos.length
sliceInfos.forEach(si => si.deg = eqDeg)
} else if (hasNonZero) {
const usedByNonZero = sliceInfos.filter(si => si.percent > 0).reduce((s, si) => s + si.deg, 0)
const zeroCount = sliceInfos.filter(si => si.percent === 0).length
const remaining = Math.max(0, 360 - usedByNonZero - zeroCount * MIN_SLICE_DEG)
// 非零的按比例补上剩余空间
sliceInfos.forEach(si => {
if (si.percent > 0) {
si.deg = si.deg + (si.deg / usedByNonZero) * remaining
}
})
}
// 转弧度并累积计算起止角
let startAngle = -Math.PI / 2
sliceInfos.forEach(si => {
si.startAngle = startAngle
si.sliceAngle = (si.deg / 180) * Math.PI
si.endAngle = startAngle + si.sliceAngle
si.midAngle = startAngle + si.sliceAngle / 2
startAngle = si.endAngle
})
// 记录碰撞信息
sliceInfos.forEach(si => {
pieAngleRanges.push({
index: si.index,
status: si.status,
cx, cy,
radius,
innerR: 0,
startAngle: si.startAngle,
endAngle: si.endAngle
})
})
// 第一遍:画扇区(hover的最后画)
sliceInfos.forEach(si => {
const isHover = (si.index === pieHover.index)
if (!isHover) {
ctx.beginPath()
ctx.moveTo(cx, cy)
ctx.arc(cx, cy, radius, si.startAngle, si.endAngle)
ctx.closePath()
ctx.fillStyle = STATUS_COLORS[si.status] || '#ccc'
ctx.globalAlpha = 0.85
ctx.fill()
ctx.globalAlpha = 1
}
})
// 第二遍:画 hover 扇区(放大+阴影)
if (pieHover.index >= 0) {
const si = sliceInfos.find(s => s.index === pieHover.index)
if (si && si.percent >= 0) {
const { startAngle: sa, endAngle: ea, midAngle: ma } = si
const expandR = radius + 5
const offsetDist = 6
const ox = cx + Math.cos(ma) * offsetDist
const oy = cy + Math.sin(ma) * offsetDist
ctx.save()
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
ctx.shadowBlur = 12
ctx.shadowOffsetY = 3
ctx.beginPath()
ctx.moveTo(ox, oy)
ctx.arc(ox, oy, expandR, sa, ea)
ctx.closePath()
ctx.fillStyle = STATUS_COLORS_HOVER[si.status] || STATUS_COLORS[si.status] || '#ccc'
ctx.fill()
ctx.restore()
}
}
// 第三遍:引导线 + 标签
sliceInfos.forEach(si => {
const isHover = (si.index === pieHover.index)
const { midAngle, status: s, percent: pct } = si
const lineStartX = cx + Math.cos(midAngle) * radius
const lineStartY = cy + Math.sin(midAngle) * radius
const elbowLen = 14
const elbowX = cx + Math.cos(midAngle) * (radius + elbowLen)
const elbowY = cy + Math.sin(midAngle) * (radius + elbowLen)
const textDir = midAngle > Math.PI / 2 && midAngle <= Math.PI * 1.5 ? -1 : 1
const textLen = 36
const lineEndX = elbowX + textDir * textLen
const lineEndY = elbowY
ctx.strokeStyle = isHover ? '#666' : '#aaa'
ctx.lineWidth = isHover ? 1.2 : 0.8
ctx.beginPath()
ctx.moveTo(lineStartX, lineStartY)
ctx.lineTo(elbowX, elbowY)
ctx.lineTo(lineEndX, lineEndY)
ctx.stroke()
const labelText = `${statusLabel(s)}${pct.toFixed(pct % 1 === 0 ? 0 : 2)}%`
const tx = lineEndX + textDir * 4
const ty = lineEndY + (isHover ? -2 : 4)
ctx.fillStyle = isHover ? '#333' : '#555'
ctx.font = `${isHover ? 'bold ' : ''}11px sans-serif`
ctx.textAlign = textDir > 0 ? 'left' : 'right'
ctx.textBaseline = 'middle'
ctx.fillText(labelText, tx, ty)
})
}
</script>
<style scoped>
.ereport-dialog :deep(.el-dialog) {
max-height: 94vh;
display: flex;
flex-direction: column;
}
.ereport-dialog :deep(.el-dialog__header) {
padding: 10px 18px;
border-bottom: 1px solid #e8e8e8;
margin: 0;
flex-shrink: 0;
}
.ereport-dialog :deep(.el-dialog__body) {
overflow: hidden;
flex: 1;
}
.dialog-header {
display: flex;
align-items: center;
}
.title-text {
font-size: 14px;
font-weight: bold;
color: #333;
margin-right: 8px;
}
.report-body {
padding: 10px 14px;
display: flex;
flex-direction: column;
gap: 10px;
}
.chart-section {
background: #fff;
border: 1px solid #e8e8e8;
border-radius: 4px;
padding: 10px 14px;
}
.section-title {
font-size: 13px;
font-weight: bold;
color: #333;
margin-bottom: 5px;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 3px;
font-size: 11px;
font-weight: normal;
color: #666;
}
/* 时间轴容器 */
.timeline-canvas-wrap {
position: relative;
background: #fff;
border: 1px solid #e0e0e0;
border-radius: 3px;
padding: 5px;
min-height: 122px;
cursor: default;
}
.timeline-canvas-wrap canvas {
display: block;
width: 100%;
}
.canvas-wrap {
width: 100%;
overflow: hidden;
}
/* 柱状图容器 */
.bar-canvas-wrap {
position: relative;
width: 100%;
}
.bar-canvas-wrap canvas {
display: block;
width: 100%;
}
.canvas-wrap canvas {
display: block;
width: 100%;
}
.bottom-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
/* 明细面板 */
.detail-panel {
background: #fff;
border: 1px solid #e8e8e8;
border-radius: 4px;
padding: 10px 14px;
}
.detail-table-wrap {
max-height: 253px;
overflow-y: auto;
}
.detail-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.detail-table th {
background: #fafafa;
padding: 7px 12px;
text-align: left;
font-weight: bold;
color: #333;
border-bottom: 1px solid #eee;
}
.detail-table td {
padding: 5px 12px;
border-bottom: 1px solid #f5f5f5;
color: #555;
}
.detail-table tbody tr:hover { background: #f9f9f9; }
/* 饼图面板 */
.pie-panel {
background: #fff;
border: 1px solid #e8e8e8;
border-radius: 4px;
padding: 8px 12px;
display: flex;
align-items: center;
}
.pie-canvas-wrap {
flex: 1;
min-width: 0;
position: relative;
}
.pie-canvas-wrap canvas {
display: block;
width: 100%;
}
.stats-area {
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 10px;
margin-left: -15px;
}
.stat-row {
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-label { font-size: 12px; color: #888; }
.stat-val { font-size: 17px; font-weight: bold; color: #333; }
/* 图例圆点 */
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
flex-shrink: 0;
}
.dot.g { background: #67c23a; }
.dot.r { background: #e74c3c; }
.dot.y { background: #c5d94e; }
.dot.gy { background: #909399; }
/* ========== Tooltip 样式 ========== */
.tl-tooltip {
position: absolute;
background: rgba(32, 40, 55, 0.95);
border-radius: 6px;
padding: 10px 16px;
min-width: 210px;
z-index: 200;
pointer-events: none;
box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
.tl-tooltip::after {
content: '';
position: absolute;
bottom: -7px;
left: 50%;
transform: translateX(-50%);
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid rgba(32, 40, 55, 0.95);
}
.tl-tooltip.tt-below::after {
top: -7px;
bottom: auto;
border-top: none;
border-bottom: 7px solid rgba(32, 40, 55, 0.95);
}
.tt-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
line-height: 1.9;
font-size: 12px;
}
.tt-label { color: #aab2c0; flex-shrink: 0; }
.tt-val {
color: #eef1f7;
font-weight: 500;
display: flex;
align-items: center;
gap: 4px;
}
.tt-val.status-2 .dot { background: #67c23a; }
.tt-val.status-3 .dot { background: #c5d94e; }
.tt-val.status-1 .dot { background: #e74c3c; }
.tt-val.status-0 .dot { background: #909399; }
/* ========== 柱状图 Tooltip ========== */
.bar-tooltip {
position: absolute;
background: rgba(32, 40, 55, 0.95);
border-radius: 6px;
padding: 10px 16px;
min-width: 130px;
z-index: 200;
pointer-events: none;
box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
.bar-tooltip::after {
content: '';
position: absolute;
bottom: -7px;
left: 50%;
transform: translateX(-50%);
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid rgba(32, 40, 55, 0.95);
}
.btt-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
line-height: 1.9;
font-size: 12px;
}
.btt-label { color: #aab2c0; flex-shrink: 0; }
.btt-val { color: #eef1f7; font-weight: 500; }
.btt-highlight { color: #66b1ff; font-weight: bold; }
/* ========== 饼图 Tooltip ========== */
.pie-tooltip {
position: absolute;
background: rgba(32, 40, 55, 0.95);
border-radius: 6px;
padding: 8px 14px;
min-width: 120px;
z-index: 200;
pointer-events: none;
box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}
.pie-tooltip::after {
content: '';
position: absolute;
bottom: -7px;
left: 18px;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid rgba(32, 40, 55, 0.95);
}
.ptt-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
line-height: 1.9;
font-size: 12px;
}
.ptt-label { color: #aab2c0; flex-shrink: 0; }
.ptt-val { color: #eef1f7; font-weight: 500; display: flex; align-items: center; gap: 4px; }
.ptt-highlight { font-weight: bold; }
</style>