File size: 85,210 Bytes
aec7019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1199a79
 
aec7019
 
 
 
 
 
 
 
 
 
 
 
 
1199a79
aec7019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1199a79
 
 
 
 
 
 
 
 
 
 
 
 
 
aec7019
1199a79
aec7019
 
 
 
 
 
 
 
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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>提升泵站 AI 节能优化 · 展示台</title>
<!--
  单文件 HTML 展示页(碧帝 Biditech 泵站 AI 节能优化)
  - 数据来源:Node-RED(node-red-contrib-opcua 独立采集)经 WebSocket/REST 发布。
  - 不依赖力控原生 OPC 能力;本页可直接嵌入力控 FWebView / iframe 显示。
  - 无 Node-RED 时自动降级到内置仿真数据,界面独立可跑。
  数据源集中在下方 CONFIG,改这里即可对接现场。
-->
<!-- ECharts 本地内置(离线工控机可用);如需改用 CDN 把下一行换成 jsDelivr 链接即可 -->
<script src="./echarts.min.js"></script>
<style>
  :root {
    --bg: #0b1a2b;
    --sidebar: #0d2136;
    --panel: #10273f;
    --panel-2: #14314e;
    --line: #1d3f60;
    --text: #e8f0f8;
    --text-dim: #8fa8c0;
    --accent: #2ea8ff;
    --green: #22c58b;
    --amber: #f6c343;
    --red: #ff5c5c;
    --chart-h: 100%;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  html, body { height: 100%; }
  body {
    font-family: "Segoe UI", "Microsoft YaHei", system-ui, sans-serif;
    background: var(--bg);
    color: var(--text);
    display: flex;
    height: 100vh;
    overflow: hidden;
  }
  /* ---------- Sidebar ---------- */
  .sidebar {
    width: 210px;
    flex-shrink: 0;
    background: var(--sidebar);
    border-right: 1px solid var(--line);
    display: flex;
    flex-direction: column;
  }
  .brand {
    padding: 18px 18px 14px;
    border-bottom: 1px solid var(--line);
  }
  .brand h1 { font-size: 15px; font-weight: 600; letter-spacing: .5px; }
  .brand span { font-size: 11px; color: var(--text-dim); }
  .nav { list-style: none; padding: 10px 0; flex: 1; overflow-y: auto; }
  .nav li {
    padding: 12px 20px;
    font-size: 13.5px;
    color: var(--text-dim);
    cursor: pointer;
    border-left: 3px solid transparent;
    transition: all .15s;
    display: flex; align-items: center; gap: 10px;
  }
  .nav li:hover { background: var(--panel); color: var(--text); }
  .nav li.active {
    background: var(--panel);
    color: var(--accent);
    border-left-color: var(--accent);
  }
  .nav li .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .7; }
  .sidebar-foot { padding: 12px 18px; font-size: 11px; color: var(--text-dim); border-top: 1px solid var(--line); }
  /* ---------- Main ---------- */
  .main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
  .topbar {
    height: 52px; flex-shrink: 0;
    background: var(--panel);
    border-bottom: 1px solid var(--line);
    display: flex; align-items: center; gap: 14px;
    padding: 0 18px;
  }
  .topbar select, .topbar button {
    background: var(--panel-2); color: var(--text);
    border: 1px solid var(--line); border-radius: 5px;
    padding: 6px 10px; font-size: 13px; cursor: pointer;
  }
  .topbar button:hover { border-color: var(--accent); }
  .topbar .title { font-size: 14px; font-weight: 600; }
  .spacer { flex: 1; }
  .pill {
    display: inline-flex; align-items: center; gap: 7px;
    font-size: 12px; padding: 5px 11px; border-radius: 20px;
    background: var(--panel-2); border: 1px solid var(--line);
  }
  .pill .led { width: 8px; height: 8px; border-radius: 50%; background: var(--text-dim); }
  .pill.live .led { background: var(--green); box-shadow: 0 0 8px var(--green); }
  .pill.sim .led { background: var(--amber); box-shadow: 0 0 8px var(--amber); }
  .pill.off .led { background: var(--red); }
  .clock { font-size: 12px; color: var(--text-dim); font-variant-numeric: tabular-nums; }
  .content { flex: 1; padding: 16px; overflow: auto; min-height: 0; }
  .view { display: none; height: 100%; }
  .view.active { display: block; }
  .chart-wrap {
    background: var(--panel); border: 1px solid var(--line);
    border-radius: 8px; height: 100%; padding: 8px;
  }
  .chart { width: 100%; height: 100%; }
  /* two-column layout for single-pump view */
  .split { display: flex; gap: 14px; height: 100%; }
  .side-panel {
    width: 240px; flex-shrink: 0;
    background: var(--panel); border: 1px solid var(--line);
    border-radius: 8px; padding: 12px; overflow-y: auto;
  }
  .side-panel h3 { font-size: 13px; margin-bottom: 10px; color: var(--accent); font-weight: 600; }
  .kv {
    display: flex; justify-content: space-between; align-items: baseline;
    padding: 8px 6px; border-bottom: 1px dashed var(--line); font-size: 13px;
  }
  .kv .k { color: var(--text-dim); }
  .kv .v { font-weight: 600; font-variant-numeric: tabular-nums; }
  .kv .v small { color: var(--text-dim); font-weight: 400; margin-left: 3px; }
  /* overview cards */
  .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; }
  .card {
    background: var(--panel); border: 1px solid var(--line);
    border-radius: 8px; padding: 14px;
  }
  .card .card-h { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
  .card .card-h .name { font-size: 14px; font-weight: 600; }
  .badge { font-size: 11px; padding: 3px 9px; border-radius: 12px; }
  .badge.run { background: rgba(34,197,139,.18); color: var(--green); }
  .badge.stop { background: rgba(143,168,192,.18); color: var(--text-dim); }
  .badge.fault { background: rgba(255,92,92,.18); color: var(--red); }
  .metric-row { display: flex; justify-content: space-between; padding: 5px 0; font-size: 13px; }
  .metric-row .lab { color: var(--text-dim); }
  .metric-row .val { font-variant-numeric: tabular-nums; font-weight: 600; }
  .kpi-strip { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px,1fr)); gap: 14px; margin-bottom: 14px; }
  .kpi {
    background: linear-gradient(135deg, var(--panel-2), var(--panel));
    border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px;
  }
  .kpi .kpi-l { font-size: 12px; color: var(--text-dim); }
  .kpi .kpi-v { font-size: 24px; font-weight: 700; margin-top: 4px; font-variant-numeric: tabular-nums; }
  .kpi .kpi-v small { font-size: 12px; color: var(--text-dim); font-weight: 400; }
  .overview-scroll { height: 100%; overflow-y: auto; padding-right: 4px; }
  /* AI 建议页 */
  .toolbar-row { display: flex; align-items: center; gap: 14px; margin-bottom: 16px; flex-wrap: wrap; }
  .toolbar-row button {
    background: var(--panel-2); color: var(--text); border: 1px solid var(--line);
    border-radius: 5px; padding: 8px 16px; font-size: 13px; cursor: pointer;
  }
  .toolbar-row button:hover:not(:disabled) { border-color: var(--accent); }
  .toolbar-row button:disabled { opacity: .45; cursor: not-allowed; }
  .btn-primary { background: var(--accent) !important; border-color: var(--accent) !important; color: #04263f !important; font-weight: 600; }
  #confirmBtn:not(:disabled) { background: rgba(34,197,139,.18) !important; border-color: var(--green) !important; color: var(--green) !important; }
  .chk { font-size: 13px; color: var(--text-dim); display: flex; align-items: center; gap: 5px; cursor: pointer; }
  .compare-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 14px; }
  .cmp-card { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px; }
  .cmp-card.changed { border-color: var(--amber); }
  .cmp-card .cmp-h { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
  .cmp-card .cmp-h .name { font-weight: 600; }
  .cmp-row { display: flex; align-items: center; gap: 10px; padding: 6px 0; font-size: 13px; }
  .cmp-row .from { color: var(--text-dim); }
  .cmp-row .arrow { color: var(--accent); }
  .cmp-row .to { font-weight: 600; }
  .tag { font-size: 11px; padding: 2px 8px; border-radius: 10px; }
  .tag.start { background: rgba(34,197,139,.18); color: var(--green); }
  .tag.stop { background: rgba(255,92,92,.18); color: var(--red); }
  .tag.keep { background: rgba(143,168,192,.18); color: var(--text-dim); }
  .tag.adjust { background: rgba(246,195,67,.18); color: var(--amber); }
  .kpi.hl .kpi-v { color: var(--green); }
  /* 模式切换 + 安全 */
  .mode-seg { display: inline-flex; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
  .mode-seg .seg { background: var(--panel-2); color: var(--text-dim); border: none; padding: 8px 14px; font-size: 13px; cursor: pointer; }
  .mode-seg .seg.active { background: var(--accent); color: #04263f; font-weight: 600; }
  .mode-seg .seg.active.auto { background: var(--green); }
  .btn-danger { background: rgba(255,92,92,.14) !important; border-color: var(--red) !important; color: var(--red) !important; }
  .btn-danger:hover { background: rgba(255,92,92,.25) !important; }
  .safety-bar { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 12px; }
  .sf { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; padding: 5px 11px; border-radius: 6px; background: var(--panel); border: 1px solid var(--line); }
  .sf .led { width: 8px; height: 8px; border-radius: 50%; background: var(--text-dim); }
  .sf.ok .led { background: var(--green); box-shadow: 0 0 6px var(--green); }
  .sf.warn .led { background: var(--amber); box-shadow: 0 0 6px var(--amber); }
  .sf.bad .led { background: var(--red); box-shadow: 0 0 6px var(--red); }
  .interv-list { background: rgba(246,195,67,.08); border: 1px solid rgba(246,195,67,.3); border-radius: 6px; padding: 8px 12px; margin-bottom: 12px; font-size: 12.5px; }
  .interv-list b { color: var(--amber); }
  .interv-list div { padding: 2px 0; color: var(--text-dim); }
  /* 泵曲线管理 */
  .curve-work { display: flex; gap: 14px; }
  .curve-canvas-wrap { position: relative; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 8px; }
  #curveCanvas { background: #071522; border-radius: 4px; cursor: crosshair; max-width: 100%; }
  .curve-hint { font-size: 11.5px; color: var(--text-dim); padding: 6px 2px 0; }
  .curve-side { flex: 1; min-width: 260px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px; }
  .curve-side h3 { font-size: 13px; color: var(--accent); margin-bottom: 10px; }
  .curve-field { margin-bottom: 10px; }
  .curve-field label { display: block; font-size: 12px; color: var(--text-dim); margin-bottom: 4px; }
  .curve-field textarea, .curve-field input { width: 100%; background: var(--panel-2); color: var(--text); border: 1px solid var(--line); border-radius: 5px; padding: 7px; font-size: 12.5px; font-family: ui-monospace, monospace; resize: vertical; }
  .fit-info { font-size: 12px; color: var(--text-dim); margin-top: 8px; line-height: 1.7; }
  .fit-info b { color: var(--green); }
  /* ---------- 运行总览大屏 ---------- */
  .dash { display: flex; flex-direction: column; gap: 14px; height: 100%; min-height: 0; }
  .dash-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
  .dash-kpi { background: linear-gradient(135deg, var(--panel-2), var(--panel)); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px; position: relative; overflow: hidden; }
  .dash-kpi .l { font-size: 12px; color: var(--text-dim); }
  .dash-kpi .v { font-size: 26px; font-weight: 700; margin-top: 3px; font-variant-numeric: tabular-nums; letter-spacing: .5px; }
  .dash-kpi .v small { font-size: 12px; color: var(--text-dim); font-weight: 400; }
  .dash-kpi.accent .v { color: var(--accent); } .dash-kpi.green .v { color: var(--green); } .dash-kpi.amber .v { color: var(--amber); }
  .dash-mid { display: grid; grid-template-columns: 2fr 1fr; gap: 14px; }
  .dash-bottom { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
  .dash-panel { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 12px; min-width: 0; }
  .panel-h { font-size: 13px; color: var(--accent); font-weight: 600; margin-bottom: 10px; }
  .chart.mini { height: 200px; }
  /* SCADA 工艺组态 */
  .scada-flow { display: flex; align-items: stretch; gap: 6px; min-height: 220px; }
  .scada-well { width: 96px; flex-shrink: 0; display: flex; flex-direction: column; align-items: center; }
  .well-tank { flex: 1; width: 70px; border: 2px solid var(--line); border-top: none; border-radius: 0 0 8px 8px; background: linear-gradient(to top, rgba(46,168,255,.35) 0%, rgba(46,168,255,.35) var(--lvl,50%), transparent var(--lvl,50%)); position: relative; }
  .well-tank .lvl-txt { position: absolute; bottom: 6px; left: 0; right: 0; text-align: center; font-size: 12px; font-weight: 600; }
  .scada-well .cap { font-size: 11px; color: var(--text-dim); margin-top: 6px; }
  .scada-pumps { flex: 1; display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 8px; align-content: start; }
  .pump-node { background: var(--panel-2); border: 1px solid var(--line); border-radius: 8px; padding: 10px; text-align: center; position: relative; transition: border-color .2s; }
  .pump-node.on { border-color: var(--green); box-shadow: 0 0 12px rgba(34,197,139,.25) inset; }
  .pump-node.fault { border-color: var(--red); }
  .pump-node .pid { font-size: 12px; color: var(--text-dim); }
  .pump-node .ring { width: 46px; height: 46px; margin: 6px auto; border-radius: 50%; border: 3px solid var(--line); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; }
  .pump-node.on .ring { border-color: var(--green); color: var(--green); animation: spin 2.6s linear infinite; }
  .pump-node .ring .blade { font-size: 18px; }
  @keyframes spin { to { transform: rotate(360deg); } }
  .pump-node .m { font-size: 11.5px; color: var(--text); padding: 1px 0; font-variant-numeric: tabular-nums; }
  .pump-node .m .u { color: var(--text-dim); }
  .scada-out { width: 74px; flex-shrink: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; border-left: 2px dashed var(--line); }
  .scada-out .big { font-size: 18px; font-weight: 700; color: var(--accent); }
  .scada-out .cap { font-size: 11px; color: var(--text-dim); }
  .combo-line { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px; }
  .combo-chip { font-size: 12px; padding: 4px 10px; border-radius: 14px; background: var(--panel-2); border: 1px solid var(--line); }
  .combo-chip.on { border-color: var(--green); color: var(--green); }
  /* 报警表 */
  .alarm-table { width: 100%; border-collapse: collapse; font-size: 13px; }
  .alarm-table th { text-align: left; color: var(--text-dim); font-weight: 500; padding: 8px 10px; border-bottom: 1px solid var(--line); font-size: 12px; }
  .alarm-table td { padding: 8px 10px; border-bottom: 1px solid rgba(120,150,180,.08); }
  .lv { font-size: 11px; padding: 2px 9px; border-radius: 10px; font-weight: 600; }
  .lv.crit { background: rgba(255,92,92,.18); color: var(--red); }
  .lv.warn { background: rgba(246,195,67,.18); color: var(--amber); }
  .lv.info { background: rgba(46,168,255,.18); color: var(--accent); }
  .st-active { color: var(--red); } .st-cleared { color: var(--text-dim); }
</style>
</head>
<body>
  <aside class="sidebar">
    <div class="brand">
      <h1 id="brandTitle">泵站 AI 节能优化</h1>
      <span id="brandPlant">Biditech · 展示台</span>
    </div>
    <ul class="nav" id="nav">
      <li data-view="dashboard" class="active"><span class="dot"></span>运行总览大屏</li>
      <li data-view="overview"><span class="dot"></span>泵站总览</li>
      <li data-view="hq"><span class="dot"></span>泵组 H-Q 特性曲线</li>
      <li data-view="single"><span class="dot"></span>单泵性能曲线</li>
      <li data-view="eff"><span class="dot"></span>效率性能曲线</li>
      <li data-view="trends"><span class="dot"></span>历史趋势</li>
      <li data-view="alarms"><span class="dot"></span>报警记录</li>
      <li data-view="energy"><span class="dot"></span>能耗分析</li>
      <li data-view="suggest"><span class="dot"></span>AI 优化建议</li>
      <li data-view="curve"><span class="dot"></span>泵曲线管理</li>
    </ul>
    <div class="sidebar-foot" id="brandFoot">数据源:Node-RED / OPC UA<br/>力控 FWebView 嵌入显示</div>
  </aside>

  <div class="main">
    <div class="topbar">
      <span class="title" id="viewTitle">运行总览大屏</span>
      <select id="pumpSelect"><!-- 由 PUMP_ROSTER 动态填充 --></select>
      <button id="refreshBtn">刷新</button>
      <button onclick="location.href='./config.html'">数据接入配置</button>
      <div class="spacer"></div>
      <span class="pill off" id="statusPill"><span class="led"></span><span id="statusText">未连接</span></span>
      <span class="clock" id="clock">--:--:--</span>
    </div>

    <div class="content">
      <!-- View 0: 运行总览大屏 -->
      <section class="view active" id="view-dashboard">
        <div class="dash">
          <div class="dash-kpis" id="dashKpis"></div>
          <div class="dash-mid">
            <div class="dash-panel scada">
              <div class="panel-h">泵站工艺组态 · 实时</div>
              <div class="scada-flow" id="scadaFlow"></div>
            </div>
            <div class="dash-panel">
              <div class="panel-h">开泵组合与 AI 建议</div>
              <div id="dashCombo"></div>
            </div>
          </div>
          <div class="dash-bottom">
            <div class="dash-panel"><div class="panel-h">总流量 / 液位 趋势</div><div class="chart mini" id="chart-dash-flow"></div></div>
            <div class="dash-panel"><div class="panel-h">总功率 / SEC 趋势</div><div class="chart mini" id="chart-dash-power"></div></div>
          </div>
        </div>
      </section>

      <!-- View 1: 泵组 H-Q -->
      <section class="view" id="view-hq">
        <div class="chart-wrap"><div class="chart" id="chart-hq"></div></div>
      </section>

      <!-- View 2: 单泵性能曲线 -->
      <section class="view" id="view-single">
        <div class="split">
          <div class="side-panel" id="singlePanel">
            <h3>实时工况参数</h3>
            <!-- filled by JS -->
          </div>
          <div class="chart-wrap" style="flex:1;"><div class="chart" id="chart-single"></div></div>
        </div>
      </section>

      <!-- View 3: 泵站总览 -->
      <section class="view" id="view-overview">
        <div class="overview-scroll">
          <div class="kpi-strip" id="kpiStrip"></div>
          <div class="grid" id="pumpGrid"></div>
        </div>
      </section>

      <!-- View 4: 效率性能曲线 -->
      <section class="view" id="view-eff">
        <div class="chart-wrap"><div class="chart" id="chart-eff"></div></div>
      </section>

      <!-- View: 历史趋势 -->
      <section class="view" id="view-trends">
        <div class="overview-scroll">
          <div class="toolbar-row">
            <span style="color:var(--text-dim);font-size:13px;">时间范围</span>
            <div class="mode-seg" id="trendRange">
              <button class="seg active" data-min="5">5 分钟</button>
              <button class="seg" data-min="15">15 分钟</button>
              <button class="seg" data-min="30">30 分钟</button>
            </div>
            <span class="clock" id="trendInfo"></span>
          </div>
          <div class="chart-wrap" style="height:300px;margin-bottom:14px;"><div class="chart" id="chart-trend-1"></div></div>
          <div class="chart-wrap" style="height:300px;"><div class="chart" id="chart-trend-2"></div></div>
        </div>
      </section>

      <!-- View: 报警记录 -->
      <section class="view" id="view-alarms">
        <div class="overview-scroll">
          <div class="kpi-strip" id="alarmKpis"></div>
          <div class="dash-panel"><div class="panel-h">当前报警 / 历史记录(阈值:液位 LL/HH、高压、偏离高效区、泵故障、SEC 异常)</div>
            <table class="alarm-table"><thead><tr><th>时间</th><th>级别</th><th>来源</th><th>描述</th><th>状态</th></tr></thead>
              <tbody id="alarmBody"></tbody></table>
          </div>
        </div>
      </section>

      <!-- View: 能耗分析 -->
      <section class="view" id="view-energy">
        <div class="overview-scroll">
          <div class="kpi-strip" id="energyKpis"></div>
          <div class="dash-bottom">
            <div class="dash-panel"><div class="panel-h">各泵实时功率 (kW)</div><div class="chart mini" id="chart-energy-pump"></div></div>
            <div class="dash-panel"><div class="panel-h">累计电量估算 (kWh,本会话)</div><div class="chart mini" id="chart-energy-kwh"></div></div>
          </div>
          <div class="dash-panel" style="margin-top:14px;"><div class="panel-h">SEC vs 全50Hz 基线(节能潜力)</div><div class="chart mini" id="chart-energy-sec"></div></div>
        </div>
      </section>

      <!-- View 5: AI 优化建议(Phase 2 开环建议 + 人工确认)-->
      <section class="view" id="view-suggest">
        <div class="overview-scroll">
          <div class="toolbar-row">
            <div class="mode-seg">
              <button id="modeManual" class="seg active">手动开环建议</button>
              <button id="modeAuto" class="seg">自动闭环(安全联锁)</button>
            </div>
            <label class="chk"><input type="checkbox" id="writeEnable" /> 写使能</label>
            <button id="getSuggestBtn" class="btn-primary">获取 AI 建议</button>
            <button id="confirmBtn" disabled>人工确认执行 ✓</button>
            <button id="revertBtn" class="btn-danger">⟲ 一键反悔 / 切回</button>
          </div>
          <div class="safety-bar" id="safetyBar"></div>
          <div class="clock" id="suggestStatus" style="margin:0 0 12px 2px;">手动模式:点「获取 AI 建议」调用优化后端,人工确认后执行</div>
          <div id="intervBox"></div>
          <div class="kpi-strip" id="suggestKpi"></div>
          <div id="suggestCompare"></div>
        </div>
      </section>

      <!-- View 6: 泵曲线管理(上传曲线图 → 图上点取 → 拟合 → 应用)-->
      <section class="view" id="view-curve">
        <div class="overview-scroll">
          <div class="toolbar-row">
            <select id="curvePump"></select>
            <label class="chk"><input type="file" id="curveImg" accept="image/*" style="max-width:180px" /> 上传曲线图</label>
            <select id="curveAxis">
              <option value="hq">标定/点取:H-Q 扬程曲线</option>
              <option value="eta">标定/点取:η-Q 效率曲线</option>
            </select>
            <button id="curveCalib" class="btn-primary">① 标定坐标轴</button>
            <button id="curveUndo">撤销点</button>
            <button id="curveClear">清空</button>
            <button id="curveFit" class="btn-primary">② 拟合预览</button>
            <button id="curveApply" disabled>③ 应用到该泵 ✓</button>
            <span class="clock" id="curveStatus">上传曲线图并标定坐标轴后,在曲线上点取数据点</span>
          </div>
          <div class="curve-work">
            <div class="curve-canvas-wrap">
              <canvas id="curveCanvas" width="640" height="440"></canvas>
              <div class="curve-hint" id="curveHint">未上传图片:也可在右侧「手动/粘贴数据点」直接输入</div>
            </div>
            <div class="curve-side">
              <h3>手动 / 粘贴数据点(额定 50Hz)</h3>
              <div class="curve-field"><label>H-Q 点 (每行 <b>Q,H</b>)</label>
                <textarea id="curveHQ" rows="6" placeholder="0,18.5&#10;300,17.8&#10;600,16.2&#10;850,14.5&#10;1050,11"></textarea></div>
              <div class="curve-field"><label>η-Q 点 (每行 <b>Q,η%</b>,可选)</label>
                <textarea id="curveEta" rows="5" placeholder="300,40&#10;600,68&#10;850,78&#10;1050,60"></textarea></div>
              <div class="curve-field"><label>泵名称(可选)</label>
                <input id="curveName" type="text" placeholder="如:3 号泵(海斯特 实测)" /></div>
              <div id="curveFitInfo" class="fit-info"></div>
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>

<script>
/* ============================================================
 * CONFIG — 现场对接改这里
 * ============================================================ */
const CONFIG = {
  // Node-RED 发布的 WebSocket / REST 端点。留空则纯仿真。
  // 同源优先:http(s) 下用当前源(单进程/单容器或 nginx 反代都零配置);file:// 本地开发回退到默认端口
  WS_URL:   (location.protocol.startsWith('http')) ? ((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws/realtime') : 'ws://localhost:1880/ws/realtime',
  REST_URL: (location.protocol.startsWith('http')) ? (location.origin + '/api/realtime') : 'http://localhost:1880/api/realtime',
  // 优化算法后端(FastAPI)基址:优化建议 / 配置 / 控制 / 安全联锁 / 曲线上传
  API_BASE: (location.protocol.startsWith('http')) ? location.origin : 'http://localhost:8077',
  AUTO_CYCLE_MS: 3000,  // 自动闭环周期
  RECONNECT_MS: 4000,
  SIM_FALLBACK: true,   // 无数据源时启用内置仿真,便于独立演示
};
const API = {
  suggestion: () => CONFIG.API_BASE + '/api/optimization/suggestion',
  apply:      () => CONFIG.API_BASE + '/api/optimization/apply',
  config:     () => CONFIG.API_BASE + '/api/config',
  mode:       () => CONFIG.API_BASE + '/api/control/mode',
  enable:     () => CONFIG.API_BASE + '/api/control/enable',
  revert:     () => CONFIG.API_BASE + '/api/control/revert',
  state:      () => CONFIG.API_BASE + '/api/control/state',
  curve:      (pid, freq = 50) => CONFIG.API_BASE + `/api/pump/${pid}/curve?freq=${freq}&n=40`,
};

// 泵组花名册(海斯特站默认 5 台:变频 1/2/5,工频 3/4)。启动时若后端 /api/config 可达则以其为准。
let PUMP_ROSTER = [
  { id: 1, name: '1 号泵(飞力 变频)', variable_speed: true },
  { id: 2, name: '2 号泵(海斯特 变频)', variable_speed: true },
  { id: 3, name: '3 号泵(海斯特 工频)', variable_speed: false },
  { id: 4, name: '4 号泵(海斯特 工频)', variable_speed: false },
  { id: 5, name: '5 号泵(海斯特 变频)', variable_speed: true },
];

/* ============================================================
 * 泵水力模型(相似定律 Q∝f, H∝f², P∝f³)— 用于生成曲线族
 * 单泵额定:50Hz 下 BEP ≈ (Q=150 m³/h, H=45 m, η=0.82, P≈45kW)
 * ============================================================ */
// 海斯特 F10K 铭牌:Q≈850 m³/h, H≈14.5m @50Hz(螺旋离心)。H(Q)=H0 - k·Q²(近似)
const PUMP = { Qbep: 850, H0: 18.5, k: 5.5e-6, etaMax: 0.78, Qmax: 1150, ratedKW: 55 };
const FREQS = [50, 48, 46, 44, 42];   // 曲线族频率(高静扬程站有效调频区间偏高)
const F_COLORS = ['#2ea8ff', '#22c58b', '#f6c343', '#c78bff', '#ff8f5c'];
const PUMP_CURVES = {};   // {pumpId: {frequency: API curve}}

function factoryCurve(pid, f = 50) { return PUMP_CURVES[pid] && PUMP_CURVES[pid][f]; }
function selectedPump() { return PUMP_ROSTER[+document.getElementById('pumpSelect').value] || PUMP_ROSTER[0]; }
function curveBep(pid, f = 50) {
  const c = factoryCurve(pid, f);
  return c ? c.bep_flow : PUMP.Qbep * f / 50;
}

// No discharge pressure/head is available in the historical replay, therefore
// hydraulic efficiency cannot be measured from ρgQH/P. This helper returns
// only a manufacturer-curve estimate and refuses unknown frequency or points
// outside the verified 50 Hz factory curve.
function estimatedCurveEfficiency(p) {
  if (!p || p.status !== 1 || !hasKnownFreq(p)) return null;
  const curve50 = factoryCurve(p.id, 50);
  if (!curve50?.etaQ?.length) return null;
  const ratio = p.freq / 50;
  if (!(ratio > 0)) return null;
  const equivalentQ50 = p.flow / ratio;
  const firstQ = curve50.etaQ[0][0];
  const lastQ = curve50.etaQ[curve50.etaQ.length - 1][0];
  if (equivalentQ50 < firstQ || equivalentQ50 > lastQ) return null;
  const eta50Pct = interpolateCurve(curve50.etaQ, equivalentQ50);
  const speedCorrection = 0.92 + 0.08 * ratio;
  return Math.max(0, Math.min(100, eta50Pct * speedCorrection));
}
function interpolateCurve(points, q) {
  if (!points || !points.length) return NaN;
  if (q <= points[0][0]) return points[0][1];
  for (let i = 1; i < points.length; i++) {
    if (q <= points[i][0]) {
      const [q0, y0] = points[i - 1], [q1, y1] = points[i];
      const t = (q - q0) / Math.max(1e-9, q1 - q0);
      return y0 + t * (y1 - y0);
    }
  }
  return points[points.length - 1][1];
}

function headAt(Q, f) {           // H(Q) at frequency f
  const r = f / 50;
  const Qe = Q / r;               // 等效 50Hz 流量
  const H50 = PUMP.H0 - PUMP.k * Qe * Qe;
  return H50 * r * r;
}
function effAt(Q, f) {            // η(Q):以 BEP 为峰的抛物线,随频率轻微下移
  const r = f / 50;
  const Qbep = PUMP.Qbep * r;
  const spread = 95 * r;
  let e = PUMP.etaMax * (1 - Math.pow((Q - Qbep) / spread, 2));
  e *= (0.92 + 0.08 * r);        // 低速效率修正
  return Math.max(0, e);
}
function powerAt(Q, f) {          // 轴功率近似 P = ρgQH/η (kW)
  const H = headAt(Q, f), e = effAt(Q, f);
  if (e < 0.05) return NaN;
  const Qs = Q / 3600;           // m³/s
  return (1000 * 9.81 * Qs * H) / (e * 1000) / 0.95; // /电机效率
}
function curve(fn, f, n = 40) {
  const r = f / 50, Qmax = PUMP.Qmax * r, out = [];
  for (let i = 0; i <= n; i++) {
    const Q = (Qmax * i) / n;
    const y = fn(Q, f);
    if (isFinite(y) && y >= 0) out.push([+Q.toFixed(1), +y.toFixed(2)]);
  }
  return out;
}
// 高效区多边形:各频率 BEP 的 60%~120% 流量围成的可行域
function feasiblePolygon(pid = null) {
  const lo = [], hi = [];
  FREQS.slice().reverse().forEach(f => {          // 30→50 上行边 (120%)
    const Q = curveBep(pid, f) * 1.2;
    const c = pid && factoryCurve(pid, f);
    const h = c ? interpolateCurve(c.HQ, Q) : headAt(Q, f);
    hi.push([+Q.toFixed(1), +h.toFixed(2)]);
  });
  FREQS.forEach(f => {                             // 50→30 下行边 (60%)
    const Q = curveBep(pid, f) * 0.6;
    const c = pid && factoryCurve(pid, f);
    const h = c ? interpolateCurve(c.HQ, Q) : headAt(Q, f);
    lo.push([+Q.toFixed(1), +h.toFixed(2)]);
  });
  return hi.concat(lo).concat([hi[0]]);
}

/* ============================================================
 * ECharts 通用暗色主题片段
 * ============================================================ */
const AX = {
  axisLine: { lineStyle: { color: '#345' } },
  axisLabel: { color: '#8fa8c0' },
  splitLine: { lineStyle: { color: 'rgba(120,150,180,.12)' } },
  nameTextStyle: { color: '#8fa8c0' },
};
const LEGEND = { textStyle: { color: '#cfe0f0' }, top: 6, type: 'scroll' };
const TT = { trigger: 'axis', backgroundColor: 'rgba(16,39,63,.95)', borderColor: '#1d3f60', textStyle: { color: '#e8f0f8' } };

/* ---------- Chart instances ---------- */
const charts = {};
const HAS_ECHARTS = typeof echarts !== 'undefined';
function getChart(id) {
  if (!HAS_ECHARTS) return null;
  if (!charts[id]) charts[id] = echarts.init(document.getElementById(id));
  return charts[id];
}

/* ---------- View 1: 泵组 H-Q 特性曲线 ---------- */
function renderHQ(snap) {
  const c = getChart('chart-hq');
  if (!c) return;
  const pump = selectedPump();
  const pid = pump ? pump.id : 2;
  const series = FREQS.map((f, i) => ({
    name: f + ' Hz', type: 'line', smooth: true, symbol: 'none',
    lineStyle: { width: 2, color: F_COLORS[i] },
    data: factoryCurve(pid, f)?.HQ || curve(headAt, f),
  }));
  series.push({
    name: '高效运行区', type: 'line', symbol: 'none', silent: true,
    data: feasiblePolygon(pid),
    lineStyle: { color: 'rgba(34,197,139,.5)', width: 1 },
    areaStyle: { color: 'rgba(34,197,139,.20)' },
  });
  if (snap) {
    // 单泵曲线族上叠加各运行泵的工况点(用单泵流量,而非并联总流量)
    const wp = snap.pumps
      .filter(p => p.status === 1 && Number.isFinite(p.head))
      .map(p => [+p.flow.toFixed(1), +p.head.toFixed(2)]);
    series.push({
      name: '实时工况点', type: 'scatter', symbolSize: 16, z: 10,
      itemStyle: { color: '#ff5c5c', borderColor: '#fff', borderWidth: 1.5,
        shadowBlur: 10, shadowColor: 'rgba(255,92,92,.6)' },
      data: wp,
    });
  }
  c.setOption({
    backgroundColor: 'transparent',
    title: { text: (pump?.name || pid + '号泵') + ' · 厂家 H-Q 曲线族', left: 'center', top: 4, textStyle: { color: '#e8f0f8', fontSize: 14 } },
    tooltip: TT, legend: { ...LEGEND, top: 28 },
    grid: { left: 60, right: 30, top: 66, bottom: 50 },
    xAxis: { type: 'value', name: 'Q (m³/h)', min: 0, ...AX },
    yAxis: { type: 'value', name: 'H (m)', min: 0, ...AX },
    series,
  }, true);
}

/* ---------- View 2: 单泵性能曲线 ---------- */
function renderSingle(snap, pumpIdx) {
  const c = getChart('chart-single');
  const p = snap ? snap.pumps[pumpIdx] : null;
  if (c) {
  const pumpMeta = PUMP_ROSTER[pumpIdx] || PUMP_ROSTER[0];
  const pid = pumpMeta ? pumpMeta.id : pumpIdx + 1;
  const fc = factoryCurve(pid, 50);
  const hqF = fc?.HQ || curve(headAt, 50);
  const etaF = fc?.etaQ || curve(effAt, 50).map(([q, e]) => [q, +(e * 100).toFixed(1)]);
  const bepFlow = fc?.bep_flow || PUMP.Qbep;
  const pqF = fc?.PQ || curve(powerAt, 50).filter(([q]) => q >= bepFlow * 0.55);
  const qMax = hqF.length ? hqF[hqF.length - 1][0] : PUMP.Qmax;
  const bepH = interpolateCurve(hqF, bepFlow);

  const hasMeasuredWorkPoint = p && Number.isFinite(p.head);
  const wpQ = hasMeasuredWorkPoint ? p.flow : bepFlow;
  const wpH = hasMeasuredWorkPoint ? p.head : bepH;
  c.setOption({
    backgroundColor: 'transparent',
    title: { text: (pumpMeta?.name || (pumpIdx + 1) + '号泵') + ' · 厂家性能曲线', left: 'center', top: 4, textStyle: { color: '#e8f0f8', fontSize: 14 } },
    tooltip: TT, legend: { ...LEGEND, top: 28 },
    grid: { left: 58, right: 62, top: 66, bottom: 50 },
    xAxis: { type: 'value', name: 'Q (m³/h)', min: 0, ...AX },
    yAxis: [
      { type: 'value', name: 'H (m) / P (kW)', min: 0, ...AX },
      { type: 'value', name: 'η (%)', min: 0, max: 100, position: 'right', ...AX },
    ],
    series: [
      { name: 'H-Q 出厂', type: 'line', smooth: true, symbol: 'none', data: hqF, lineStyle: { color: '#2ea8ff', width: 2 } },
      { name: 'η-Q 出厂', type: 'line', yAxisIndex: 1, smooth: true, symbol: 'none', data: etaF, lineStyle: { color: '#22c58b', width: 2 } },
      { name: 'P-Q 出厂', type: 'line', smooth: true, symbol: 'none', data: pqF, lineStyle: { color: '#f6c343', width: 2 } },
      // 高效区(BEP 60%~120%)绿色带 + 越界红色带
      { name: '高效区', type: 'line', symbol: 'none', silent: true,
        markArea: { silent: true, data: [
          [{ xAxis: bepFlow * 0.6, itemStyle: { color: 'rgba(34,197,139,.14)' } }, { xAxis: bepFlow * 1.2 }],
          [{ xAxis: 0, itemStyle: { color: 'rgba(255,92,92,.10)' } }, { xAxis: bepFlow * 0.6 }],
          [{ xAxis: bepFlow * 1.2, itemStyle: { color: 'rgba(255,92,92,.10)' } }, { xAxis: qMax }],
        ] }, data: [] },
      { name: 'BEP', type: 'scatter', symbolSize: 12, data: [[bepFlow, +bepH.toFixed(1)]], itemStyle: { color: '#fff' } },
      { name: '实测工况点', type: 'scatter', symbolSize: 15, z: 10,
        data: hasMeasuredWorkPoint ? [[+wpQ.toFixed(1), +wpH.toFixed(1)]] : [],
        itemStyle: { color: '#ff5c5c', borderColor: '#fff', borderWidth: 1.5 } },
    ],
  }, true);
  }

  // 左侧数值面板
  const panel = document.getElementById('singlePanel');
  if (p) {
    const liveBep = hasKnownFreq(p) ? curveBep(p.id, p.freq) : null;
    const dev = liveBep ? ((p.flow - liveBep) / liveBep * 100).toFixed(1) : '—';
    const meta = PUMP_ROSTER.find(x => x.id === p.id) || {};
    panel.innerHTML = `<h3>${pumpIdx + 1} 号泵 实时工况</h3>` + [
      ['型号', meta.hydraulic_code || meta.name || '—', ''],
      ['曲线来源', meta.curve_revision || '厂家曲线', ''],
      ['运行状态', p.status === 1 ? '运行' : (p.status === 2 ? '故障' : '停止'), ''],
      ['频率', freqValueText(p, 1, false), hasKnownFreq(p) ? 'Hz' : ''],
      ['电流', p.current.toFixed(1), 'A'],
      ['功率', p.power.toFixed(1), 'kW'],
      [p.flowSource === 'estimated_power_share' ? '流量(模型估算)' : '流量', p.flow.toFixed(1), 'm³/h'],
      ['扬程', Number.isFinite(p.head) ? p.head.toFixed(1) : '—', Number.isFinite(p.head) ? 'm' : '缺测'],
      ['效率(厂家曲线估算)',
        estimatedCurveEfficiency(p) != null ? estimatedCurveEfficiency(p).toFixed(1) : '—',
        estimatedCurveEfficiency(p) != null ? '%' : '缺测'],
      ['BEP 偏离', dev, hasKnownFreq(p) ? '%' : ''],
      ['累计运行', p.runHours.toFixed(0), 'h'],
      ['单泵 SEC', p.sec.toFixed(3), 'kWh/m³'],
    ].map(([k, v, u]) => `<div class="kv"><span class="k">${k}</span><span class="v">${v}<small>${u}</small></span></div>`).join('');
  } else {
    panel.innerHTML = '<h3>实时工况参数</h3><div class="kv"><span class="k">等待数据…</span></div>';
  }
}

/* ---------- View 3: 泵站总览 ---------- */
function renderOverview(snap) {
  if (!snap) return;
  const kpi = document.getElementById('kpiStrip');
  kpi.innerHTML = [
    ['集水池液位', snap.level.toFixed(2), 'm'],
    ['出口压力', snap.pressureKnown ? snap.pressure.toFixed(3) : '—', snap.pressureKnown ? 'MPa' : '缺测'],
    ['总流量', snap.totalFlow.toFixed(0), 'm³/h'],
    ['总功率', snap.totalPower.toFixed(1), 'kW'],
    ['系统 SEC', snap.sec.toFixed(3), 'kWh/m³'],
    ['运行台数', snap.pumps.filter(p => p.status === 1).length + ' / ' + snap.pumps.length, ''],
  ].map(([l, v, u]) => `<div class="kpi"><div class="kpi-l">${l}</div><div class="kpi-v">${v} <small>${u}</small></div></div>`).join('');

  const grid = document.getElementById('pumpGrid');
  grid.innerHTML = snap.pumps.map((p, i) => {
    const st = p.status === 1 ? ['run', '运行'] : p.status === 2 ? ['fault', '故障'] : ['stop', '停止'];
    return `<div class="card">
      <div class="card-h"><span class="name">${i + 1} 号泵</span><span class="badge ${st[0]}">${st[1]}</span></div>
      ${[['频率', freqValueText(p)], ['电流', p.current.toFixed(1) + ' A'],
         ['功率', p.power.toFixed(1) + ' kW'], [p.flowSource === 'estimated_power_share' ? '流量(估算)' : '流量', p.flow.toFixed(0) + ' m³/h'],
         ['累计', p.runHours.toFixed(0) + ' h']]
        .map(([l, v]) => `<div class="metric-row"><span class="lab">${l}</span><span class="val">${v}</span></div>`).join('')}
    </div>`;
  }).join('');
}

/* ---------- View 4: 效率性能曲线 ---------- */
function renderEff(snap) {
  const c = getChart('chart-eff');
  if (!c) return;
  const pump = selectedPump();
  const pid = pump ? pump.id : 2;
  const series = FREQS.map((f, i) => ({
    name: f + ' Hz', type: 'line', smooth: true, symbol: 'none',
    lineStyle: { width: 2, color: F_COLORS[i] },
    data: factoryCurve(pid, f)?.etaQ || curve(effAt, f).map(([q, e]) => [q, +(e * 100).toFixed(1)]),
  }));
  if (snap) {
    const livePump = snap.pumps.find(p => p.id === pid);
    const estimatedEta = estimatedCurveEfficiency(livePump);
    series.push({
      name: '厂家曲线估算点', type: 'scatter', symbolSize: 16, z: 10,
      itemStyle: { color: '#ff5c5c', borderColor: '#fff', borderWidth: 1.5 },
      data: livePump && estimatedEta != null
        ? [[+livePump.flow.toFixed(1), +estimatedEta.toFixed(1)]]
        : [],
    });
  }
  c.setOption({
    backgroundColor: 'transparent',
    title: { text: (pump?.name || pid + '号泵') + ' · 厂家效率曲线 η-Q', left: 'center', top: 4, textStyle: { color: '#e8f0f8', fontSize: 14 } },
    tooltip: TT, legend: { ...LEGEND, top: 28 },
    grid: { left: 55, right: 30, top: 66, bottom: 50 },
    xAxis: { type: 'value', name: 'Q (m³/h)', min: 0, ...AX },
    yAxis: { type: 'value', name: 'η (%)', min: 0, max: 100, ...AX },
    series,
  }, true);
}

/* ============================================================
 * 站配置 / 历史缓冲 / 报警引擎 / 能耗累计(完整显示系统)
 * ============================================================ */
const STATIONCFG = {           // 默认取海斯特;loadConfig 会用 /api/config 覆盖
  name: '海斯特污水提升泵站',
  level_min: 3.5, level_max: 8.5, level_ll: 3.0, level_hh: 9.0, level_scale: 10.0,
  pressure_max: 0.55, sec_warn: 0.09,
};
const HIST = [];               // 滚动历史:{t,level,pressure,totalFlow,totalPower,sec,running}
const HIST_MAX = 2000;
const ENERGY = { kwh: {}, lastT: null };   // 各泵累计电量估算 (kWh)
const ALARMS = [];             // 报警日志(新在前)
const ALARM_ACTIVE = {};       // key → 日志索引

function pushHist(s) {
  HIST.push({ t: s.ts || Date.now(), level: s.level, pressure: s.pressure,
    totalFlow: s.totalFlow, totalPower: s.totalPower, sec: s.sec,
    running: s.pumps.filter(p => p.status === 1).length });
  if (HIST.length > HIST_MAX) HIST.shift();
  // 电量累计
  const now = s.ts || Date.now();
  if (ENERGY.lastT) {
    const dtH = (now - ENERGY.lastT) / 3.6e6;
    if (dtH > 0 && dtH < 0.02) s.pumps.forEach(p => {
      ENERGY.kwh[p.id] = (ENERGY.kwh[p.id] || 0) + (p.power || 0) * dtH;
    });
  }
  ENERGY.lastT = now;
}

function raiseOrClear(key, cond, level, source, msg) {
  const t = new Date().toLocaleTimeString('zh-CN', { hour12: false });
  if (cond && !(key in ALARM_ACTIVE)) {
    ALARMS.unshift({ key, t, level, source, msg, status: 'active', clr: '' });
    ALARM_ACTIVE[key] = true;
    if (ALARMS.length > 200) ALARMS.pop();
  } else if (!cond && key in ALARM_ACTIVE) {
    const e = ALARMS.find(a => a.key === key && a.status === 'active');
    if (e) { e.status = 'cleared'; e.clr = t; }
    delete ALARM_ACTIVE[key];
  }
}

function runAlarms(s) {
  const c = STATIONCFG;
  raiseOrClear('lvl_ll', s.level < c.level_ll, 'crit', '集水井', `低水位保护 ${s.level.toFixed(2)}m < ${c.level_ll}m(停泵防干抽)`);
  raiseOrClear('lvl_hh', s.level > c.level_hh, 'crit', '集水井', `高水位 ${s.level.toFixed(2)}m > ${c.level_hh}m(溢流风险,需增泵)`);
  raiseOrClear('lvl_lo', s.level < c.level_min && s.level >= c.level_ll, 'warn', '集水井', `液位偏低 ${s.level.toFixed(2)}m`);
  raiseOrClear('lvl_hi', s.level > c.level_max && s.level <= c.level_hh, 'warn', '集水井', `液位偏高 ${s.level.toFixed(2)}m`);
  raiseOrClear('press', s.pressureKnown && s.pressure > c.pressure_max, 'crit', '出口', `出口压力越限 ${s.pressure.toFixed(3)} > ${c.pressure_max}MPa`);
  raiseOrClear('sec_hi', s.sec > c.sec_warn, 'info', '能效', `单位能耗偏高 SEC=${s.sec.toFixed(4)} kWh/m³`);
  s.pumps.forEach(p => {
    raiseOrClear('fault_' + p.id, p.status === 2, 'crit', p.id + '号泵', `${p.id}号泵故障`);
    let bepDev = 0;
    if (p.status === 1 && hasKnownFreq(p)) { const qb = curveBep(p.id, p.freq); bepDev = qb > 0 ? Math.abs(p.flow - qb) / qb : 0; }
    raiseOrClear('bep_' + p.id, p.status === 1 && hasKnownFreq(p) && bepDev > 0.30, 'warn', p.id + '号泵', `${p.id}号泵偏离高效区 ${(bepDev * 100).toFixed(0)}%(BEP±30%)`);
  });
}

/* ============================================================
 * 视图切换与渲染分发
 * ============================================================ */
let currentView = 'dashboard';
let latest = null;
const VIEW_TITLE = { dashboard: '运行总览大屏', hq: '泵组 H-Q 特性曲线', single: '单泵性能曲线', overview: '泵站总览', eff: '效率性能曲线', trends: '历史趋势', alarms: '报警记录', energy: '能耗分析', suggest: 'AI 优化建议', curve: '泵曲线管理' };

function renderCurrent() {
  const idx = +document.getElementById('pumpSelect').value;
  if (currentView === 'dashboard') renderDashboard(latest);
  else if (currentView === 'hq') renderHQ(latest);
  else if (currentView === 'single') renderSingle(latest, idx);
  else if (currentView === 'overview') renderOverview(latest);
  else if (currentView === 'eff') renderEff(latest);
  else if (currentView === 'trends') renderTrends();
  else if (currentView === 'alarms') renderAlarms();
  else if (currentView === 'energy') renderEnergy(latest);
  else if (currentView === 'suggest') renderSuggestion();
  else if (currentView === 'curve') drawCurveCanvas();
}

/* ---------- 运行总览大屏 ---------- */
function renderDashboard(s) {
  if (!s) return;
  const run = s.pumps.filter(p => p.status === 1).length;
  const base = latestSuggestion && latestSuggestion.baseline ? latestSuggestion.baseline.spec_energy : null;
  const saving = (base && s.sec) ? ((base - s.sec) / base * 100) : null;
  document.getElementById('dashKpis').innerHTML = [
    ['总流量', s.totalFlow.toFixed(0), 'm³/h', 'accent'],
    ['总功率', s.totalPower.toFixed(1), 'kW', 'accent'],
    ['系统 SEC', s.sec.toFixed(4), 'kWh/m³', 'green'],
    ['集水井液位', s.level.toFixed(2), 'm', ''],
    ['出口压力', s.pressureKnown ? s.pressure.toFixed(3) : '—', s.pressureKnown ? 'MPa' : '缺测', ''],
    ['运行台数', run + ' / ' + s.pumps.length, '', ''],
    ['活动报警', Object.keys(ALARM_ACTIVE).length, '', Object.keys(ALARM_ACTIVE).length ? 'amber' : ''],
    ['AI 节能潜力', saving == null ? '—' : saving.toFixed(1), '%', 'green'],
  ].map(([l, v, u, cls]) => `<div class="dash-kpi ${cls}"><div class="l">${l}</div><div class="v">${v} <small>${u}</small></div></div>`).join('');

  // SCADA 工艺组态
  const lvlPct = Math.max(0, Math.min(100, (s.level - 0) / STATIONCFG.level_scale * 100));
  const pumpsHtml = s.pumps.map(p => {
    const cls = p.status === 1 ? 'on' : p.status === 2 ? 'fault' : '';
    return `<div class="pump-node ${cls}">
      <div class="pid">${p.id}# 泵</div>
      <div class="ring"><span class="blade">${p.status === 1 ? '✷' : '◍'}</span></div>
      <div class="m">${p.status === 1 ? (hasKnownFreq(p) ? p.freq.toFixed(1) + '<span class="u"> Hz</span>' : '<span style="color:var(--amber)">频率未知</span>') : (p.status === 2 ? '<span style="color:var(--red)">故障</span>' : '停机')}</div>
      <div class="m">${p.power.toFixed(1)}<span class="u"> kW</span></div>
      <div class="m">${p.flow.toFixed(0)}<span class="u"> m³/h${p.flowSource === 'estimated_power_share' ? ' · 估算' : ''}</span></div>
    </div>`;
  }).join('');
  document.getElementById('scadaFlow').innerHTML = `
    <div class="scada-well">
      <div class="well-tank" style="--lvl:${lvlPct}%"><span class="lvl-txt">${s.level.toFixed(2)} m</span></div>
      <div class="cap">集水井</div>
    </div>
    <div class="scada-pumps">${pumpsHtml}</div>
    <div class="scada-out"><div class="big">${s.totalFlow.toFixed(0)}</div><div class="cap">出水总管<br>m³/h</div></div>`;

  // 组合 + AI 建议
  const combo = s.pumps.map(p => `<span class="combo-chip ${p.status === 1 ? 'on' : ''}">${p.id}#${p.status === 1 ? ' ' + freqValueText(p, 0) : ' 停'}</span>`).join('');
  let aiLine = '<span style="color:var(--text-dim)">切到「AI 优化建议」获取建议</span>';
  if (latestSuggestion && latestSuggestion.success && latestSuggestion.executable) {
    const sg = latestSuggestion;
    aiLine = `建议开泵 <b style="color:var(--green)">[${sg.active.join(', ')}]</b>,预计 ${sg.P_total} kW,SEC 改善 <b style="color:var(--green)">${sg.sec_saving_pct ?? '—'}%</b>`;
  } else if (latestSuggestion) {
    aiLine = `<span style="color:var(--amber)">${latestSuggestion.message || latestSuggestion.error || '无可执行节能建议,保持现状'}</span>`;
  }
  document.getElementById('dashCombo').innerHTML = `<div class="combo-line">${combo}</div><div style="font-size:13px;line-height:1.8">${aiLine}</div>`;

  // mini 趋势
  miniTrend('chart-dash-flow', [['总流量 m³/h', 'totalFlow', '#2ea8ff'], ['液位 m', 'level', '#22c58b']], true);
  miniTrend('chart-dash-power', [['总功率 kW', 'totalPower', '#f6c343'], ['SEC', 'sec', '#c78bff']], true);
}

function histWindow(min) { const cut = Date.now() - min * 60000; return HIST.filter(h => h.t >= cut); }
function miniTrend(id, series, dual) {
  const c = getChart(id); if (!c) return;
  const data = histWindow(30);
  const xs = data.map(h => new Date(h.t).toLocaleTimeString('zh-CN', { hour12: false }));
  c.setOption({
    backgroundColor: 'transparent', tooltip: { ...TT, trigger: 'axis' },
    legend: { ...LEGEND, top: 2 }, grid: { left: 46, right: 46, top: 28, bottom: 24 },
    xAxis: { type: 'category', data: xs, ...AX, axisLabel: { color: '#8fa8c0', showMaxLabel: true, interval: Math.max(0, Math.floor(xs.length / 5)) } },
    yAxis: [{ type: 'value', ...AX }, { type: 'value', position: 'right', ...AX }],
    series: series.map((s, i) => ({ name: s[0], type: 'line', smooth: true, symbol: 'none',
      yAxisIndex: dual ? i : 0, lineStyle: { color: s[2], width: 2 }, areaStyle: i === 0 ? { color: s[2] + '22' } : undefined,
      data: data.map(h => +(+h[s[1]]).toFixed(3)) })),
  }, true);
}

/* ---------- 历史趋势 ---------- */
let trendMin = 5;
function renderTrends() {
  const data = histWindow(trendMin);
  document.getElementById('trendInfo').textContent = `${data.length} 点 · 近 ${trendMin} 分钟`;
  const xs = data.map(h => new Date(h.t).toLocaleTimeString('zh-CN', { hour12: false }));
  const mk = (id, series) => {
    const c = getChart(id); if (!c) return;
    c.setOption({
      backgroundColor: 'transparent', tooltip: { ...TT, trigger: 'axis' }, legend: { ...LEGEND, top: 4 },
      grid: { left: 56, right: 56, top: 34, bottom: 30 },
      xAxis: { type: 'category', data: xs, ...AX, axisLabel: { color: '#8fa8c0', interval: Math.max(0, Math.floor(xs.length / 8)) } },
      yAxis: [{ type: 'value', name: series[0][3], ...AX }, { type: 'value', name: series[1] ? series[1][3] : '', position: 'right', ...AX }],
      series: series.map((s, i) => ({ name: s[0], type: 'line', smooth: true, symbol: 'none', yAxisIndex: i,
        lineStyle: { color: s[2], width: 2 }, areaStyle: i === 0 ? { color: s[2] + '22' } : undefined,
        data: data.map(h => +(+h[s[1]]).toFixed(3)) })),
    }, true);
  };
  mk('chart-trend-1', [['总流量', 'totalFlow', '#2ea8ff', 'm³/h'], ['集水井液位', 'level', '#22c58b', 'm']]);
  mk('chart-trend-2', [['总功率', 'totalPower', '#f6c343', 'kW'], ['系统 SEC', 'sec', '#c78bff', 'kWh/m³']]);
}

/* ---------- 报警记录 ---------- */
function renderAlarms() {
  const active = ALARMS.filter(a => a.status === 'active');
  const by = l => active.filter(a => a.level === l).length;
  document.getElementById('alarmKpis').innerHTML = [
    ['活动报警', active.length, '', active.length ? 'amber' : 'green'],
    ['紧急', by('crit'), '', by('crit') ? 'amber' : ''],
    ['警告', by('warn'), '', ''],
    ['累计记录', ALARMS.length, '', ''],
  ].map(([l, v, u, cls]) => `<div class="kpi ${cls === 'amber' ? 'hl' : ''}"><div class="kpi-l">${l}</div><div class="kpi-v">${v}</div></div>`).join('');
  const nm = { crit: '紧急', warn: '警告', info: '提示' };
  document.getElementById('alarmBody').innerHTML = ALARMS.length
    ? ALARMS.slice(0, 100).map(a => `<tr>
        <td>${a.t}</td><td><span class="lv ${a.level}">${nm[a.level]}</span></td>
        <td>${a.source}</td><td>${a.msg}</td>
        <td class="${a.status === 'active' ? 'st-active' : 'st-cleared'}">${a.status === 'active' ? '● 活动' : '○ 已恢复 ' + a.clr}</td></tr>`).join('')
    : '<tr><td colspan="5" style="color:var(--text-dim);padding:16px">暂无报警</td></tr>';
}

/* ---------- 能耗分析 ---------- */
function renderEnergy(s) {
  if (!s) return;
  const base = latestSuggestion && latestSuggestion.baseline ? latestSuggestion.baseline.spec_energy : null;
  const saving = (base && s.sec) ? ((base - s.sec) / base * 100) : null;
  const totalKwh = Object.values(ENERGY.kwh).reduce((a, b) => a + b, 0);
  document.getElementById('energyKpis').innerHTML = [
    ['实时总功率', s.totalPower.toFixed(1), 'kW'],
    ['系统 SEC', s.sec.toFixed(4), 'kWh/m³'],
    ['本会话累计电量', totalKwh.toFixed(1), 'kWh'],
    ['相对基线节能', saving == null ? '—' : saving.toFixed(1), '%'],
  ].map(([l, v, u]) => `<div class="kpi"><div class="kpi-l">${l}</div><div class="kpi-v">${v} <small>${u}</small></div></div>`).join('');

  const ids = s.pumps.map(p => p.id + '#');
  const bar = (id, name, data, color, unit) => {
    const c = getChart(id); if (!c) return;
    c.setOption({ backgroundColor: 'transparent', tooltip: { ...TT, trigger: 'axis' }, grid: { left: 50, right: 20, top: 30, bottom: 30 },
      title: { text: name, left: 'center', top: 2, textStyle: { color: '#cfe0f0', fontSize: 12 } },
      xAxis: { type: 'category', data: ids, ...AX }, yAxis: { type: 'value', name: unit, ...AX },
      series: [{ type: 'bar', data, itemStyle: { color }, barWidth: '46%', label: { show: true, position: 'top', color: '#cfe0f0', fontSize: 11 } }] }, true);
  };
  bar('chart-energy-pump', '实时功率', s.pumps.map(p => +p.power.toFixed(1)), '#2ea8ff', 'kW');
  bar('chart-energy-kwh', '累计电量', s.pumps.map(p => +(ENERGY.kwh[p.id] || 0).toFixed(2)), '#22c58b', 'kWh');

  const c = getChart('chart-energy-sec');
  if (c) c.setOption({ backgroundColor: 'transparent', tooltip: { ...TT, trigger: 'axis' }, grid: { left: 60, right: 20, top: 20, bottom: 30 },
    xAxis: { type: 'category', data: ['当前优化', '全50Hz基线'], ...AX },
    yAxis: { type: 'value', name: 'SEC kWh/m³', ...AX },
    series: [{ type: 'bar', barWidth: '40%', data: [{ value: +s.sec.toFixed(4), itemStyle: { color: '#22c58b' } }, { value: base ? +base.toFixed(4) : null, itemStyle: { color: '#8fa8c0' } }],
      label: { show: true, position: 'top', color: '#cfe0f0' } }] }, true);
}

document.getElementById('nav').addEventListener('click', e => {
  const li = e.target.closest('li'); if (!li) return;
  document.querySelectorAll('.nav li').forEach(n => n.classList.remove('active'));
  li.classList.add('active');
  currentView = li.dataset.view;
  document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
  document.getElementById('view-' + currentView).classList.add('active');
  document.getElementById('viewTitle').textContent = VIEW_TITLE[currentView];
  requestAnimationFrame(() => { resizeAll(); renderCurrent(); });
});
document.getElementById('pumpSelect').addEventListener('change', renderCurrent);
document.getElementById('refreshBtn').addEventListener('click', renderCurrent);

function resizeAll() { Object.values(charts).forEach(c => c.resize()); }
window.addEventListener('resize', resizeAll);

/* clock */
setInterval(() => {
  document.getElementById('clock').textContent = new Date().toLocaleTimeString('zh-CN', { hour12: false });
}, 1000);

/* ============================================================
 * 数据层:WebSocket(Node-RED) → 失败降级仿真
 * ============================================================ */
function setStatus(mode) {
  const pill = document.getElementById('statusPill'), txt = document.getElementById('statusText');
  pill.className = 'pill ' + mode;
  txt.textContent = { live: '已连接 · OPC 实时', sim: '仿真数据 · 无数据源', off: '未连接' }[mode];
}

// 统一快照归一化(兼容 Node-RED 的字段命名)
function hasKnownFreq(p) {
  return p != null && Number.isFinite(p.freq) && p.freq > 0;
}

function freqValueText(p, digits = 1, withUnit = true) {
  if (!hasKnownFreq(p)) return p && p.status === 1 ? '频率未知' : '—';
  return p.freq.toFixed(digits) + (withUnit ? ' Hz' : '');
}

function normalize(raw) {
  const pressureKnown = raw.pressure !== null && raw.pressure !== ''
    && Number.isFinite(Number(raw.pressure));
  const pumps = (raw.pumps || []).map((p, i) => {
    const rawFreq = p.freq ?? p.frequency ?? null;
    const freq = rawFreq === null || rawFreq === '' ? null : Number(rawFreq);
    const knownFreq = Number.isFinite(freq) && freq > 0;
    return {
      id: p.id || i + 1,
      freq: knownFreq ? freq : null, current: +p.current || 0, power: +p.power || 0,
      status: p.status != null ? +p.status : (knownFreq ? 1 : 0),
      flow: +p.flow || 0,
      head: p.head !== null && p.head !== '' && Number.isFinite(Number(p.head))
        ? Number(p.head) : null,
      headSource: p.headSource || p.head_source || '',
      flowSource: p.flowSource || p.flow_source || '',
      runHours: +p.runHours || +p.run_hours || 0,
      sec: +p.sec || 0,
    };
  });
  const totalFlow = raw.totalFlow != null ? +raw.totalFlow : pumps.reduce((s, p) => s + p.flow, 0);
  const totalPower = raw.totalPower != null ? +raw.totalPower : pumps.reduce((s, p) => s + p.power, 0);
  const pressure = pressureKnown ? Number(raw.pressure) : 0;
  return {
    station: raw.station || '泵站1号机组',
    level: +raw.level || 0, pressure, pressureKnown,
    pressureQuality: raw.pressureQuality || (pressureKnown ? 'measured' : 'missing'),
    source: raw.source || '', sourceLabel: raw.sourceLabel || '',
    historicalTimestamp: raw.historicalTimestamp || '',
    head: raw.head != null
      ? +raw.head
      : (pressureKnown ? pressure * 102 : null),   // MPa→m 近似;压力缺测时不虚构
    totalFlow, totalPower,
    sec: raw.sec != null ? +raw.sec : (totalFlow > 0 ? totalPower / totalFlow : 0),
    pumps,
    ts: raw.ts || Date.now(),
  };
}

function onData(raw) {
  latest = normalize(raw);
  if (latest.source === 'historical_opc_replay') {
    const stamp = latest.historicalTimestamp
      ? latest.historicalTimestamp.replace('T', ' ').slice(0, 16)
      : '';
    document.getElementById('statusText').textContent =
      'OPC 历史回放' + (stamp ? ' · ' + stamp : '');
  }
  pushHist(latest);           // 累积历史趋势 + 电量
  runAlarms(latest);          // 报警引擎(后台常跑,不看也累积)
  renderCurrent();
}

/* ============================================================
 * AI 优化建议:把实时快照 POST 给优化后端 → 展示建议 → 人工确认执行
 * ============================================================ */
let latestSuggestion = null;
let ctrlMode = 'manual';
let autoTimer = null;

async function postJSON(url, body) {
  const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
  return r.json();
}

async function fetchSuggestion() {
  const el = document.getElementById('suggestStatus');
  if (!latest) { el.textContent = '等待实时数据…'; return; }
  const running = latest.pumps.filter(p => p.status === 1);
  const body = {
    Q_target: +latest.totalFlow.toFixed(1),                 // 以当前需求为目标,找更省电的开法
    current_active: running.map(p => p.id),
    current_freqs: Object.fromEntries(
      running.filter(hasKnownFreq).map(p => [p.id, +p.freq.toFixed(1)])
    ),
    current_total_power: latest.totalPower,
    level: latest.level,
    run_hours: Object.fromEntries(latest.pumps.map(p => [p.id, p.runHours])),
  };
  try {
    if (ctrlMode === 'manual') el.textContent = '请求优化后端…';
    const sug = await postJSON(API.suggestion(), body);
    latestSuggestion = sug;
    if (!sug || !sug.success) {
      document.getElementById('confirmBtn').disabled = true;
      el.textContent = (sug && (sug.error || sug.message)) || '没有可行工作点';
      renderSuggestion();
      return;
    }
    if (ctrlMode === 'manual') {
      document.getElementById('confirmBtn').disabled = !sug.executable;
      el.textContent = sug.executable
        ? '建议已更新 · ' + new Date().toLocaleTimeString('zh-CN', { hour12: false })
        : (sug.message || '建议保持现状');
    }
    renderSuggestion();
  } catch (e) {
    latestSuggestion = null;
    document.getElementById('confirmBtn').disabled = true;
    el.textContent = '优化后端未连接(' + CONFIG.API_BASE + '),请先启动 backend';
  }
}

function renderSuggestion() {
  const sug = latestSuggestion;
  const kpi = document.getElementById('suggestKpi');
  const cmp = document.getElementById('suggestCompare');
  if (!sug) {
    kpi.innerHTML = '';
    cmp.innerHTML = '<div class="card" style="color:var(--text-dim)">尚无建议。点击「获取 AI 建议」调用优化后端(backend/ 的 /api/optimization/suggestion)。</div>';
    return;
  }
  if (!sug.success) {
    kpi.innerHTML = '';
    cmp.innerHTML = `<div class="card" style="color:var(--amber)">${sug.error || sug.message || '当前没有满足目标流量的可行工作点'}。系统不会生成或下发控制建议。</div>`;
    return;
  }
  const base = sug.baseline || {};
  const saving = sug.sec_saving_pct;
  kpi.innerHTML = [
    ['目标流量', (sug.Q_target ?? 0).toFixed(0), 'm³/h', false],
    ['AI 建议功率', sug.P_total.toFixed(1), 'kW', false],
    ['基线功率(' + (base.kind === 'current_measured' ? '当前实测' : '模型') + ')', (base.P_total ?? 0).toFixed(1), 'kW', false],
    ['AI SEC', sug.spec_energy.toFixed(4), 'kWh/m³', false],
    ['SEC 改善', (saving == null ? '—' : saving.toFixed(1)), '%', saving != null && saving > 0],
  ].map(([l, v, u, hl]) => `<div class="kpi ${hl ? 'hl' : ''}"><div class="kpi-l">${l}</div><div class="kpi-v">${v} <small>${u}</small></div></div>`).join('');

  if (!sug.executable) {
    cmp.innerHTML = `<div class="card" style="color:var(--amber)"><b>保持现状</b><br>${sug.message || '候选方案没有形成正节能收益,因此不生成启停或调频指令。'}</div>`;
    return;
  }

  const recActive = new Set(sug.active);
  const recFreq = sug.freqs || {};
  const cur = {};
  (latest ? latest.pumps : []).forEach(p => { cur[p.id] = p; });
  const ids = latest ? latest.pumps.map(p => p.id) : sug.active;

  const cards = ids.map(id => {
    const c = cur[id] || { status: 0, freq: 0 };
    const wasOn = c.status === 1;
    const willOn = recActive.has(id);
    let tag, changed = false;
    if (!wasOn && willOn) { tag = ['start', '启泵']; changed = true; }
    else if (wasOn && !willOn) { tag = ['stop', '停泵']; changed = true; }
    else if (wasOn && willOn) {
      const df = hasKnownFreq(c) ? Math.abs((recFreq[id] || 0) - c.freq) : Infinity;
      if (df >= 0.5) { tag = ['adjust', '调频']; changed = true; }
      else { tag = ['keep', '保持']; }
    } else { tag = ['keep', '不启']; }
    const fromTxt = wasOn ? freqValueText(c) : '停止';
    const toTxt = willOn ? (recFreq[id] || 0).toFixed(1) + ' Hz' : '停止';
    return `<div class="cmp-card ${changed ? 'changed' : ''}">
      <div class="cmp-h"><span class="name">${id} 号泵</span><span class="tag ${tag[0]}">${tag[1]}</span></div>
      <div class="cmp-row"><span class="from">当前:${fromTxt}</span><span class="arrow">→</span><span class="to">建议:${toTxt}</span></div>
    </div>`;
  }).join('');

  cmp.innerHTML = `<div style="margin:4px 0 12px;color:var(--text-dim);font-size:13px;">
      建议开泵组合:<b style="color:var(--text)">[${sug.active.join(', ')}]</b> ·
      启 ${sug.n_starts} / 停 ${sug.n_stops} 台 ·
      工作点 Q=${sug.wp.Q_total} m³/h, H=${sug.wp.H} m</div>
    <div class="compare-grid">${cards}</div>`;
}

// 把(安全指令 or 建议)应用到仿真基态,闭环可视化
function applyCommandToSim(cmd) {
  const active = new Set(cmd.active);
  simBase.forEach(b => {
    if (active.has(b.id)) { b.status = 1; b.freq = cmd.freqs[b.id] ?? b.freq; }
    else { b.status = 0; b.freq = 0; }
  });
}

// 手动开环:人工确认执行(Phase 2)
function confirmSuggestion() {
  if (!latestSuggestion || !latestSuggestion.executable) return;
  const el = document.getElementById('suggestStatus');
  if (simTimer) {
    applyCommandToSim({ active: latestSuggestion.active, freqs: latestSuggestion.freqs });
    el.textContent = '✓ 已确认执行(应用到仿真,观察各视图工况点变化)';
  } else {
    el.textContent = '✓ 已确认。实况回写走自动闭环安全联锁或 Node-RED 写回';
  }
}

/* ---- 模式切换 / 写使能 / 自动闭环 / 反悔 ---- */
function updateModeButtons(mode) {
  document.getElementById('modeManual').classList.toggle('active', mode === 'manual');
  const ab = document.getElementById('modeAuto');
  ab.classList.toggle('active', mode === 'auto');
  ab.classList.toggle('auto', mode === 'auto');
  document.getElementById('confirmBtn').style.display = mode === 'manual' ? '' : 'none';
}

async function setMode(mode) {
  ctrlMode = mode;
  updateModeButtons(mode);
  const st = document.getElementById('suggestStatus');
  try { await postJSON(API.mode(), { mode }); }
  catch (e) { if (mode === 'auto') st.textContent = '自动闭环需要优化后端(' + CONFIG.API_BASE + '),未连接'; }
  if (mode === 'auto') { st.textContent = '自动闭环启动…'; startAuto(); }
  else { stopAuto(); st.textContent = '手动模式:获取建议 → 人工确认执行'; }
  refreshSafetyBar();
}

async function setWriteEnable(on) {
  try { await postJSON(API.enable(), { enable: on }); } catch (e) {}
  refreshSafetyBar();
}

function startAuto() { if (!autoTimer) { autoTimer = setInterval(autoCycle, CONFIG.AUTO_CYCLE_MS); autoCycle(); } }
function stopAuto() { if (autoTimer) { clearInterval(autoTimer); autoTimer = null; } }

async function autoCycle() {
  if (!latest) return;
  await fetchSuggestion();
  if (!latestSuggestion) return;
  const realtime = {
    pressure: latest.pressure,
    pumps: latest.pumps.map(p => ({ id: p.id, freq: p.freq, status: p.status })),
  };
  let gated;
  try {
    gated = await postJSON(API.apply(), {
      suggestion: { active: latestSuggestion.active, freqs: latestSuggestion.freqs },
      realtime,
    });
  } catch (e) { document.getElementById('suggestStatus').textContent = '自动闭环:优化后端未连接'; return; }
  const st = document.getElementById('suggestStatus');
  if (gated.approved && gated.command) {
    applyCommandToSim(gated.command);       // 下发经安全门控(限幅/斜坡)后的指令
    st.textContent = '⟳ 自动闭环运行中 · 已下发安全指令 ' + new Date().toLocaleTimeString('zh-CN', { hour12: false });
  } else {
    st.textContent = '⏸ 自动闭环 · 本周期未下发:' + (gated.reasons || []).join(';');
  }
  renderInterventions(gated);
  refreshSafetyBar(gated);
}

async function revert() {
  stopAuto();
  ctrlMode = 'manual';
  updateModeButtons('manual');
  document.getElementById('writeEnable').checked = false;
  try { await postJSON(API.revert()); } catch (e) {}
  document.getElementById('suggestStatus').textContent = '⟲ 已反悔 / 无扰切回手动(维持最后有效设定,写使能已关)';
  document.getElementById('intervBox').innerHTML = '';
  refreshSafetyBar();
}

function refreshSafetyBar(gated) {
  const bar = document.getElementById('safetyBar');
  if (!bar) return;
  const we = document.getElementById('writeEnable').checked;
  const wd = gated ? gated.watchdog_ok : true;
  const items = [
    ['模式', ctrlMode === 'auto' ? '自动闭环' : '手动开环', ctrlMode === 'auto' ? 'ok' : ''],
    ['写使能 bWriteEnable', we ? 'ON' : 'OFF', we ? 'ok' : 'warn'],
    ['Watchdog 心跳', wd ? '正常' : '超时·切回PID', wd ? 'ok' : 'bad'],
    ['指令限幅/斜坡', '20–50Hz · ≤5Hz/周期', 'ok'],
  ];
  bar.innerHTML = items.map(([k, v, c]) => `<span class="sf ${c}"><span class="led"></span>${k}: <b>${v}</b></span>`).join('');
}

function renderInterventions(gated) {
  const box = document.getElementById('intervBox');
  if (!box) return;
  const list = (gated.interventions || []).concat(gated.approved ? [] : (gated.reasons || []));
  if (!list.length) { box.innerHTML = ''; return; }
  box.innerHTML = '<div class="interv-list"><b>安全联锁动作(' + list.length + ')</b>' +
    list.map(x => `<div>· ${x}</div>`).join('') + '</div>';
}

document.getElementById('getSuggestBtn').addEventListener('click', fetchSuggestion);
document.getElementById('confirmBtn').addEventListener('click', confirmSuggestion);
document.getElementById('modeManual').addEventListener('click', () => setMode('manual'));
document.getElementById('modeAuto').addEventListener('click', () => setMode('auto'));
document.getElementById('writeEnable').addEventListener('change', e => setWriteEnable(e.target.checked));
document.getElementById('revertBtn').addEventListener('click', revert);

/* ============================================================
 * 泵曲线管理:上传曲线图 → 坐标标定 → 图上点取 → 拟合 → 应用(软件形态,不改 YAML)
 * ============================================================ */
const CV = {
  img: null, imgRect: null,
  calib: { hq: null, eta: null },       // {x:[{px,val}x2], y:[{py,val}x2]}
  pts: { hq: [], eta: [] },             // 数字化点(数据坐标)
  preview: null,                        // {HQ, etaQ}
  fit: null,                            // {poly, eta_gauss, head_r2, eta_r2}
  calibStep: -1, calibTmp: null,
};
function curveCtx() { return document.getElementById('curveCanvas').getContext('2d'); }
function curAxis() { return document.getElementById('curveAxis').value; }

function cvStatus(t) { document.getElementById('curveStatus').textContent = t; }

function pxToData(axis, px, py) {
  const c = CV.calib[axis]; if (!c) return null;
  const q = c.x[0].val + (px - c.x[0].px) * (c.x[1].val - c.x[0].val) / (c.x[1].px - c.x[0].px);
  const v = c.y[0].val + (py - c.y[0].py) * (c.y[1].val - c.y[0].val) / (c.y[1].py - c.y[0].py);
  return [q, v];
}
function dataToPx(axis, q, v) {
  const c = CV.calib[axis]; if (!c) return null;
  const px = c.x[0].px + (q - c.x[0].val) * (c.x[1].px - c.x[0].px) / (c.x[1].val - c.x[0].val);
  const py = c.y[0].py + (v - c.y[0].val) * (c.y[1].py - c.y[0].py) / (c.y[1].val - c.y[0].val);
  return [px, py];
}

function drawCurveCanvas() {
  const cv = document.getElementById('curveCanvas'), ctx = cv.getContext('2d');
  ctx.clearRect(0, 0, cv.width, cv.height);
  const axis = curAxis();
  if (CV.img) {
    ctx.drawImage(CV.img, CV.imgRect.x, CV.imgRect.y, CV.imgRect.w, CV.imgRect.h);
    // 数字化点(图上叠加,需已标定)
    ['hq', 'eta'].forEach(ax => {
      if (!CV.calib[ax]) return;
      ctx.fillStyle = ax === 'hq' ? '#2ea8ff' : '#22c58b';
      CV.pts[ax].forEach(([q, v]) => {
        const p = dataToPx(ax, q, v); if (!p) return;
        ctx.beginPath(); ctx.arc(p[0], p[1], 4, 0, 7); ctx.fill();
      });
    });
    // 拟合预览曲线
    if (CV.preview) {
      drawPreviewOnImage(ctx, 'hq', CV.preview.HQ, '#2ea8ff');
      if (CV.preview.etaQ) drawPreviewOnImage(ctx, 'eta', CV.preview.etaQ, '#22c58b');
    }
    // 标定标记
    if (CV.calib[axis]) {
      ctx.fillStyle = '#f6c343';
      CV.calib[axis].x.concat(CV.calib[axis].y).forEach(m => {
        ctx.beginPath(); ctx.arc(m.px, m.py, 5, 0, 7); ctx.stroke ? 0 : 0; ctx.fill();
      });
    }
  } else {
    drawPlotMode(ctx, cv);
  }
}
function drawPreviewOnImage(ctx, axis, series, color) {
  if (!CV.calib[axis]) return;
  ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.beginPath();
  let started = false;
  series.forEach(([q, v]) => {
    const p = dataToPx(axis, q, v); if (!p) return;
    if (!started) { ctx.moveTo(p[0], p[1]); started = true; } else ctx.lineTo(p[0], p[1]);
  });
  ctx.stroke();
}
function drawPlotMode(ctx, cv) {
  // 无图:把 H-Q 点与预览画成简单坐标图
  const hq = CV.pts.hq.length >= 2 ? CV.pts.hq : parsePts('curveHQ');
  const all = hq.concat(CV.preview ? CV.preview.HQ : []);
  if (!all.length) {
    ctx.fillStyle = '#8fa8c0'; ctx.font = '13px sans-serif';
    ctx.fillText('上传曲线图,或在右侧输入 H-Q 数据点后点「拟合预览」', 24, 40);
    return;
  }
  const pad = 44, W = cv.width, H = cv.height;
  const xs = all.map(p => p[0]), ys = all.map(p => p[1]);
  const xmin = 0, xmax = Math.max(...xs) * 1.05, ymin = 0, ymax = Math.max(...ys) * 1.15;
  const X = q => pad + (q - xmin) / (xmax - xmin) * (W - pad - 20);
  const Y = v => H - pad - (v - ymin) / (ymax - ymin) * (H - pad - 20);
  ctx.strokeStyle = '#345'; ctx.lineWidth = 1;
  ctx.beginPath(); ctx.moveTo(pad, 20); ctx.lineTo(pad, H - pad); ctx.lineTo(W - 20, H - pad); ctx.stroke();
  ctx.fillStyle = '#8fa8c0'; ctx.font = '11px sans-serif';
  ctx.fillText('Q (m³/h)', W - 70, H - pad + 28); ctx.fillText('H (m)', 8, 24);
  if (CV.preview) {
    ctx.strokeStyle = '#2ea8ff'; ctx.lineWidth = 2; ctx.beginPath();
    CV.preview.HQ.forEach(([q, v], i) => { const x = X(q), y = Y(v); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
    ctx.stroke();
  }
  ctx.fillStyle = '#f6c343';
  hq.forEach(([q, v]) => { ctx.beginPath(); ctx.arc(X(q), Y(v), 4, 0, 7); ctx.fill(); });
}

function parsePts(id) {
  return document.getElementById(id).value.trim().split('\n').map(l => {
    const m = l.split(/[,\s]+/).map(Number).filter(x => !isNaN(x));
    return m.length >= 2 ? [m[0], m[1]] : null;
  }).filter(Boolean);
}

document.getElementById('curveImg').addEventListener('change', e => {
  const f = e.target.files[0]; if (!f) return;
  const rd = new FileReader();
  rd.onload = ev => {
    const im = new Image();
    im.onload = () => {
      CV.img = im;
      const cv = document.getElementById('curveCanvas');
      const s = Math.min(cv.width / im.width, cv.height / im.height);
      const w = im.width * s, h = im.height * s;
      CV.imgRect = { x: (cv.width - w) / 2, y: (cv.height - h) / 2, w, h };
      CV.calib = { hq: null, eta: null }; CV.pts = { hq: [], eta: [] }; CV.preview = null;
      drawCurveCanvas();
      cvStatus('图片已载入。点「① 标定坐标轴」,按提示在图上点两个已知 Q 点、两个已知 ' + (curAxis() === 'hq' ? 'H' : 'η') + ' 点。');
    };
    im.src = ev.target.result;
  };
  rd.readAsDataURL(f);
});

document.getElementById('curveCalib').addEventListener('click', () => {
  if (!CV.img) { cvStatus('请先上传曲线图'); return; }
  CV.calibStep = 0; CV.calibTmp = { x: [], y: [] };
  cvStatus('标定 [' + curAxis().toUpperCase() + ']:点 X轴上第 1 个已知 Q 点');
});

document.getElementById('curveCanvas').addEventListener('click', e => {
  const cv = document.getElementById('curveCanvas'), r = cv.getBoundingClientRect();
  const px = (e.clientX - r.left) * cv.width / r.width, py = (e.clientY - r.top) * cv.height / r.height;
  const axis = curAxis();
  if (CV.calibStep >= 0) {                        // 标定中
    const prompts = ['X轴第1个已知 Q 值', 'X轴第2个已知 Q 值',
      (axis === 'hq' ? 'Y轴第1个已知 H 值' : 'Y轴第1个已知 η(%)'),
      (axis === 'hq' ? 'Y轴第2个已知 H 值' : 'Y轴第2个已知 η(%)')];
    const val = parseFloat(prompt(prompts[CV.calibStep] + ':'));
    if (isNaN(val)) { cvStatus('已取消标定'); CV.calibStep = -1; return; }
    if (CV.calibStep < 2) CV.calibTmp.x.push({ px, py, val });
    else CV.calibTmp.y.push({ px, py, val });
    CV.calibStep++;
    if (CV.calibStep >= 4) {
      CV.calib[axis] = CV.calibTmp; CV.calibStep = -1;
      cvStatus('[' + axis.toUpperCase() + '] 坐标已标定,现在在曲线上依次点取数据点(' + (axis === 'hq' ? '蓝' : '绿') + '点)。');
    } else {
      cvStatus('标定:' + prompts[CV.calibStep].replace('已知', '已知'));
    }
    drawCurveCanvas(); return;
  }
  if (CV.calib[axis]) {                            // 数字化点取
    const d = pxToData(axis, px, py);
    CV.pts[axis].push([+d[0].toFixed(1), +d[1].toFixed(2)]);
    drawCurveCanvas();
    cvStatus('已取 ' + CV.pts[axis].length + ' 个 ' + axis.toUpperCase() + ' 点(Q=' + d[0].toFixed(0) + ')。够 3+ 点后点「② 拟合预览」。');
  }
});

document.getElementById('curveUndo').addEventListener('click', () => { CV.pts[curAxis()].pop(); drawCurveCanvas(); });
document.getElementById('curveClear').addEventListener('click', () => {
  CV.pts = { hq: [], eta: [] }; CV.preview = null; CV.fit = null;
  document.getElementById('curveApply').disabled = true;
  document.getElementById('curveFitInfo').innerHTML = ''; drawCurveCanvas();
});

async function curveFitPreview() {
  const pid = +document.getElementById('curvePump').value;
  const hq = CV.pts.hq.length >= 3 ? CV.pts.hq : parsePts('curveHQ');
  const eta = CV.pts.eta.length >= 4 ? CV.pts.eta : parsePts('curveEta');
  if (hq.length < 3) { cvStatus('H-Q 至少需要 3 个点(图上点取或右侧输入)'); return; }
  try {
    const res = await postJSON(CONFIG.API_BASE + `/api/pump/${pid}/curve/fit`,
      { hq, eta: eta.length >= 4 ? eta : null });
    if (!res.success) { cvStatus('拟合失败:' + res.error); return; }
    CV.fit = res; CV.preview = res.preview || { HQ: [], etaQ: null };
    document.getElementById('curveApply').disabled = false;
    const g = res.eta_gauss;
    document.getElementById('curveFitInfo').innerHTML =
      `拟合结果:<br>H(Q)=<b>${res.poly.a0.toFixed(3)}${res.poly.a1>=0?'+':''}${res.poly.a1.toFixed(4)}·Q${res.poly.a2>=0?'+':''}${res.poly.a2.toExponential(2)}·Q²</b><br>` +
      `扬程拟合 R²=<b>${res.head_r2}</b>` +
      (g ? `<br>η_max=<b>${g.eta_max}</b> Q_bep=<b>${g.q_bep}</b> σ=${g.sigma}(R²=${res.eta_r2})` : '<br>(未给 η 点,效率沿用默认)');
    drawCurveCanvas();
    cvStatus('拟合完成,预览曲线已叠加。确认无误后点「③ 应用到该泵」。');
  } catch (e) { cvStatus('优化后端未连接(' + CONFIG.API_BASE + ')'); }
}
document.getElementById('curveFit').addEventListener('click', curveFitPreview);

document.getElementById('curveApply').addEventListener('click', async () => {
  const pid = +document.getElementById('curvePump').value;
  if (!CV.fit) return;
  const body = { poly: CV.fit.poly, eta_gauss: CV.fit.eta_gauss || { eta_max: 0.78, q_bep: CV.fit.poly.q_max * 0.75, sigma: CV.fit.poly.q_max * 0.4 } };
  const nm = document.getElementById('curveName').value.trim(); if (nm) body.name = nm;
  try {
    const res = await postJSON(CONFIG.API_BASE + `/api/pump/${pid}/curve/apply`, body);
    if (res.success) cvStatus('✓ 已应用到 ' + res.meta.name + '(已持久化,优化器即刻采用新曲线)');
    else cvStatus('应用失败:' + res.error);
  } catch (e) { cvStatus('优化后端未连接'); }
});
document.getElementById('curveAxis').addEventListener('change', drawCurveCanvas);

// 历史趋势时间范围
document.getElementById('trendRange').addEventListener('click', e => {
  const b = e.target.closest('.seg'); if (!b) return;
  document.querySelectorAll('#trendRange .seg').forEach(s => s.classList.remove('active'));
  b.classList.add('active'); trendMin = +b.dataset.min; renderTrends();
});

/* ---- 内置仿真器(相似定律 + 噪声,落在文档约定区间内)---- */
let simTimer = null;
// 仿真基态(module 级,从 PUMP_ROSTER 构建;便于「确认执行」/自动闭环把指令应用回来做闭环可视化)
let simBase = [];
function buildSimBase() {
  // 初始让前两台变频泵运行,其余待机;工频泵运行时锁 50Hz
  let started = 0;
  simBase = PUMP_ROSTER.map((r, i) => {
    let status = 0, freq = 0;
    if (r.variable_speed && started < 2) { status = 1; freq = 49 - started * 1.5; started++; }
    return { id: r.id, variable_speed: r.variable_speed, freq, status, runHours: 4700 + i * 180 };
  });
}
function startSim() {
  if (simTimer) return;
  setStatus('sim');
  simTimer = setInterval(() => {
    const t = Date.now() / 1000;
    const pumps = simBase.map((b, i) => {
      // 工频泵不抖动(锁 50Hz),变频泵带小幅波动
      const jitter = b.variable_speed ? Math.sin(t / 7 + i) * 1.2 : 0;
      const freq = b.status === 1 ? Math.max(20, Math.min(50, b.freq + jitter)) : 0;
      const r = freq / 50;
      const flow = b.status === 1 ? PUMP.Qbep * r * (1.0 + 0.06 * Math.sin(t / 5 + i)) : 0;
      const head = b.status === 1 ? headAt(flow, freq) : 0;
      const power = b.status === 1 ? (powerAt(flow, freq) || 0) : 0;
      const current = power > 0 ? power * 1.9 : 0;
      const sec = flow > 0 ? power / flow : 0;
      const reportedFreq = b.id === 2 && b.status === 1 ? null : freq;
      return { id: b.id, freq: reportedFreq, current, power, status: b.status, flow, head, runHours: b.runHours, sec };
    });
    const totalFlow = pumps.reduce((s, p) => s + p.flow, 0);
    const totalPower = pumps.reduce((s, p) => s + p.power, 0);
    const head = pumps.filter(p => p.status === 1).reduce((s, p, _, a) => s + p.head / a.length, 0);
    onData({
      station: '泵站1号机组',
      level: 5.5 + 1.2 * Math.sin(t / 30),
      pressure: head / 102,
      head, totalFlow, totalPower,
      sec: totalFlow > 0 ? totalPower / totalFlow : 0,
      pumps,
    });
  }, 1000);
}
function stopSim() { if (simTimer) { clearInterval(simTimer); simTimer = null; } }

/* ---- WebSocket 连接(优先),失败/断开则降级仿真 ---- */
let ws = null;
function connectWS() {
  if (!CONFIG.WS_URL) { if (CONFIG.SIM_FALLBACK) startSim(); return; }
  try {
    ws = new WebSocket(CONFIG.WS_URL);
  } catch (e) { if (CONFIG.SIM_FALLBACK) startSim(); return; }
  ws.onopen = () => { stopSim(); setStatus('live'); };
  ws.onmessage = ev => {
    try {
      const raw = typeof ev.data === 'string' ? JSON.parse(ev.data) : ev.data;
      onData(raw.payload || raw);
    } catch (e) { /* ignore malformed */ }
  };
  ws.onclose = () => {
    setStatus('off');
    if (CONFIG.SIM_FALLBACK) startSim();
    setTimeout(connectWS, CONFIG.RECONNECT_MS);   // 后台持续尝试重连真实数据源
  };
  ws.onerror = () => { try { ws.close(); } catch (e) {} };
}

/* ---- 泵组花名册 → 下拉选择 ---- */
function populatePumpSelect() {
  const opts = PUMP_ROSTER.map((r, i) => `<option value="${i}">${r.name || (r.id + ' 号泵')}</option>`).join('');
  document.getElementById('pumpSelect').innerHTML = opts;
  // 曲线管理页用泵 id 作 value
  document.getElementById('curvePump').innerHTML =
    PUMP_ROSTER.map(r => `<option value="${r.id}">${r.name || (r.id + ' 号泵')}</option>`).join('');
}

async function loadFactoryCurves() {
  const jobs = [];
  for (const pump of PUMP_ROSTER) {
    PUMP_CURVES[pump.id] = PUMP_CURVES[pump.id] || {};
    for (const f of FREQS) jobs.push(
      fetch(API.curve(pump.id, f)).then(r => r.json()).then(c => {
        if (c && c.success) PUMP_CURVES[pump.id][f] = c;
      }).catch(() => {})
    );
  }
  await Promise.all(jobs);
}

// 启动时若后端 /api/config 可达,用其泵组配置覆盖默认花名册
async function loadConfig() {
  try {
    const r = await fetch(API.config());
    const c = await r.json();
    if (c && Array.isArray(c.pumps) && c.pumps.length) {
      PUMP_ROSTER = c.pumps;
    }
    if (c && c.station) STATIONCFG.name = c.station;
    if (c && c.level_range) {
      const L = c.level_range;
      if (L.level_min != null) STATIONCFG.level_min = L.level_min;
      if (L.level_max != null) STATIONCFG.level_max = L.level_max;
      if (L.level_ll_stop) STATIONCFG.level_ll = L.level_ll_stop;
      if (L.level_hh) STATIONCFG.level_hh = L.level_hh;
      if (L.level_scale_max) STATIONCFG.level_scale = L.level_scale_max;
    }
    if (c && c.constraints && c.constraints.pressure_max_mpa) STATIONCFG.pressure_max = c.constraints.pressure_max_mpa;
  } catch (e) { /* 后端未连接 → 保留默认 5 台花名册与站配置 */ }
  buildSimBase();
  populatePumpSelect();
  await loadFactoryCurves();
}

/* ---- 启动 ---- */
async function applyBranding() {
  try {
    const b = await fetch(CONFIG.API_BASE + '/api/branding').then(r => r.json());
    if (b && b.system_title) document.getElementById('brandTitle').textContent = b.system_title;
    if (b && b.plant_name) document.getElementById('brandPlant').textContent = b.plant_name;
    else if (b && b.company) document.getElementById('brandPlant').textContent = b.company;
    if (b && (b.plant_name || b.system_title)) document.title = (b.plant_name ? b.plant_name + ' · ' : '') + (b.system_title || '节能系统');
    const foot = [];
    if (b && b.company) foot.push(b.company);
    if (b && b.contact_phone) foot.push('电话 ' + b.contact_phone);
    if (foot.length) document.getElementById('brandFoot').innerHTML = foot.join('<br/>');
  } catch (e) { /* 后端未连接则保留默认名 */ }
}

window.addEventListener('load', async () => {
  applyBranding();          // 品牌名/公司/联系方式(可配置)
  await loadConfig();       // 先确定泵组(数量/性质)
  refreshSafetyBar();       // 初始化安全状态条
  renderCurrent();          // 先画空曲线族
  connectWS();
});
</script>
</body>
</html>