鞍钢鲅鱼圈能源管控系统后端代码
潘志宝
2025-06-17 314732a211804507b775deeb06eb7f9d08e451e6
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
package com.iailab.module.ansteel.api.controller.admin;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iailab.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.iailab.framework.common.pojo.CommonResult;
import com.iailab.framework.common.pojo.PageResult;
import com.iailab.framework.common.util.date.DateUtils;
import com.iailab.framework.common.util.object.BeanUtils;
import com.iailab.framework.common.util.object.ConvertUtils;
import com.iailab.framework.excel.core.util.ExcelUtils;
import com.iailab.module.ansteel.api.dto.*;
import com.iailab.module.ansteel.api.vo.PowerCapacitorHisPageReqVO;
import com.iailab.module.ansteel.api.vo.PowerExportCosVO;
import com.iailab.module.ansteel.api.vo.PowerExportPqVO;
import com.iailab.module.ansteel.api.vo.PowerMaxDemandMainPageReqVO;
import com.iailab.module.ansteel.common.constant.CommonConstant;
import com.iailab.module.ansteel.common.enums.ProcessConfDataTypeEnum;
import com.iailab.module.ansteel.common.utils.DecimalUtil;
import com.iailab.module.ansteel.common.utils.PowerUtil;
import com.iailab.module.ansteel.power.entity.*;
import com.iailab.module.ansteel.power.service.*;
import com.iailab.module.data.api.point.DataPointApi;
import com.iailab.module.data.api.point.dto.ApiPointValueDTO;
import com.iailab.module.data.api.point.dto.ApiPointValueQueryDTO;
import com.iailab.module.data.api.point.dto.ApiPointsValueQueryDTO;
import com.iailab.module.model.api.mcs.McsApi;
import com.iailab.module.model.api.mcs.dto.ChartParamDTO;
import com.iailab.module.model.api.mcs.dto.PredictLastValueReqVO;
import com.iailab.module.model.api.mdk.MdkApi;
import com.iailab.module.model.api.mdk.dto.MdkScheduleReqDTO;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
import static com.iailab.framework.common.pojo.CommonResult.error;
import static com.iailab.framework.common.pojo.CommonResult.success;
 
/**
 * 电力接口
 *
 * @author PanZhibao
 * @Description
 * @createTime 2025年04月11日
 */
@Slf4j
@RestController
@RequestMapping("/ansteel/api/power")
public class PowerController {
 
    @Autowired
    private PowerNetFactorService powerNetFactorService;
 
    @Autowired
    private PowerCapacitorStatusService powerCapacitorStatusService;
 
    @Autowired
    private PowerControlMainService powerControlMainService;
 
    @Autowired
    private PowerControlDetService powerControlDetService;
 
    @Autowired
    private PowerGenStatusDaoService powerGenStatusDaoService;
 
    @Autowired
    private PowerDemandService powerDemandService;
 
    @Autowired
    private PowerAdjustedFactorService powerAdjustedFactorService;
 
    @Autowired
    private DataPointApi dataPointApi;
 
    @Autowired
    private McsApi mcsApi;
 
    @Autowired
    private MdkApi mdkApi;
 
    @Autowired
    private PowerCapacitorHisService powerCapacitorHisService;
 
    @Autowired
    private PowerCapacitorDetService powerCapacitorDetService;
 
    @Autowired
    private PowerNetDropdownService powerNetDropdownService;
 
    @Autowired
    private PowerVoltageStatusService powerVoltageStatusService;
 
    @Autowired
    private PowerMaxdemandMainService powerMaxDemandMainService;
 
    @Autowired
    private PowerMaxdemandDetService powerMaxdemandDetService;
 
    @Autowired
    private PowerPriceMainService powerPriceMainService;
 
    @Autowired
    private PowerFactorControlService powerFactorControlService;
 
    public static final String VALUE = "value";
 
    public static final String TIME = "time";
 
    //private String pointNo = "F0000201825";
 
    @GetMapping("/net-factor/list")
    @Operation(summary = "功率因数-电网拓扑列表")
    public CommonResult<List<PowerNetFactorDTO>> getPowerNetFactorList(@RequestParam Map<String, Object> params) {
        log.info("功率因数电网拓扑");
        List<PowerNetFactorDTO> result = new ArrayList<>();
        List<PowerNetFactorEntity> list = powerNetFactorService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            log.info("list is empty");
            return success(result);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
 
        for (PowerNetFactorEntity entity : list) {
            PowerNetFactorDTO powerNetFactorDTO = new PowerNetFactorDTO();
            powerNetFactorDTO.setId(entity.getId());
            powerNetFactorDTO.setGroupName(entity.getGroupName());
            powerNetFactorDTO.setNodeCode(entity.getNodeCode());
            powerNetFactorDTO.setNodeName(entity.getNodeName());
            boolean cosFlag = false;
            try {
                List<String> points = new ArrayList<>();
                if (StringUtils.isNotBlank(entity.getCurA())) {
                    points.add(entity.getCurA());
                }
                if (StringUtils.isNotBlank(entity.getCurP())) {
                    points.add(entity.getCurP());
                }
                if (StringUtils.isNotBlank(entity.getCurQ())) {
                    points.add(entity.getCurQ());
                }
                if (StringUtils.isNotBlank(entity.getCurCos())) {
                    points.add(entity.getCurCos());
                }
                log.info("points=" + points);
                if (!CollectionUtils.isEmpty(points)) {
                    Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(points);
                    log.info("pointsRealValue=" + pointsRealValue);
                    if (pointsRealValue.get(entity.getCurA()) != null) {
                        powerNetFactorDTO.setCurA(new BigDecimal(pointsRealValue.get(entity.getCurA()).toString()));
                    }
                    if (pointsRealValue.get(entity.getCurP()) != null) {
                        powerNetFactorDTO.setCurP(new BigDecimal(pointsRealValue.get(entity.getCurP()).toString()));
                    }
                    if (pointsRealValue.get(entity.getCurQ()) != null) {
                        powerNetFactorDTO.setCurQ(new BigDecimal(pointsRealValue.get(entity.getCurQ()).toString()));
                    }
                    if (pointsRealValue.get(entity.getCurCos()) != null) {
                        powerNetFactorDTO.setCurCos(new BigDecimal(pointsRealValue.get(entity.getCurCos()).toString()));
                        cosFlag = true;
                    }
                }
            } catch (Exception ex) {
                log.info(entity.getNodeName() + "获取当前值异常" + ex.getMessage());
                ex.printStackTrace();
            }
 
            try {
                PredictLastValueReqVO reqVO = new PredictLastValueReqVO();
                reqVO.setPredictTime(calendar.getTime());
                List<String[]> itemNos = new ArrayList<>();
                if (StringUtils.isNotBlank(entity.getPreP())) {
                    itemNos.add(entity.getPreP().split(","));
                }
                if (StringUtils.isNotBlank(entity.getPreQ())) {
                    itemNos.add(entity.getPreQ().split(","));
                }
                if (StringUtils.isNotBlank(entity.getPreCos())) {
                    itemNos.add(entity.getPreCos().split(","));
                }
                if (!CollectionUtils.isEmpty(itemNos)) {
                    reqVO.setItemNos(itemNos);
                    log.info("reqVO=" + JSONObject.toJSONString(reqVO));
                    Map<String, BigDecimal> preValues = mcsApi.getPredictValueByTime(reqVO);
                    if (StringUtils.isNotBlank(entity.getPreP()) && preValues.get(entity.getPreP()) != null) {
                        powerNetFactorDTO.setPreP(new BigDecimal(preValues.get(entity.getPreP()).toString()));
                    }
                    if (StringUtils.isNotBlank(entity.getPreQ()) && preValues.get(entity.getPreQ()) != null) {
                        powerNetFactorDTO.setPreQ(new BigDecimal(preValues.get(entity.getPreQ()).toString()));
                    }
                    if (StringUtils.isNotBlank(entity.getPreCos()) && preValues.get(entity.getPreCos()) != null) {
                        powerNetFactorDTO.setPreCos(new BigDecimal(preValues.get(entity.getPreCos()).toString()));
                    }
                }
            } catch (Exception ex) {
                log.info(entity.getNodeName() + "获取预测值异常," + ex.getMessage());
                ex.printStackTrace();
            }
 
            // 设置电流状态
            powerNetFactorDTO.setStatus(0);
            if (powerNetFactorDTO.getCurA() != null) {
                BigDecimal curA = powerNetFactorDTO.getCurA();
                if (entity.getLimitL() != null && curA.compareTo(entity.getLimitL()) < 0) {
                    powerNetFactorDTO.setStatus(1);
                } else if (entity.getLimitH() != null && curA.compareTo(entity.getLimitH()) > 0) {
                    powerNetFactorDTO.setStatus(1);
                }
            }
 
            // 设置功率因数状态
            powerNetFactorDTO.setQstatus(0);
            if (cosFlag && powerNetFactorDTO.getCurCos() != null) {
                BigDecimal curCos = powerNetFactorDTO.getCurCos();
                if (entity.getCosLimitL() != null && curCos.compareTo(entity.getCosLimitL()) < 0) {
                    powerNetFactorDTO.setQstatus(1);
                } else if (entity.getCosLimitH() != null && curCos.compareTo(entity.getCosLimitH()) > 0) {
                    powerNetFactorDTO.setQstatus(1);
                }
            }
 
            // 设置有功预警状态
            powerNetFactorDTO.setPstatus(0);
            if (powerNetFactorDTO.getCurP() != null) {
                BigDecimal curP = powerNetFactorDTO.getCurP();
                if (entity.getPLimitL() != null && curP.compareTo(entity.getPLimitL()) < 0) {
                    powerNetFactorDTO.setPstatus(1);
                } else if (entity.getPLimitH() != null && curP.compareTo(entity.getPLimitH()) > 0) {
                    powerNetFactorDTO.setPstatus(1);
                }
            }
 
            // 设置无功预警状态
            powerNetFactorDTO.setQstatus(0);
            if (powerNetFactorDTO.getCurQ() != null) {
                BigDecimal curQ = powerNetFactorDTO.getCurQ();
                if (entity.getQLimitL() != null && curQ.compareTo(entity.getQLimitL()) < 0) {
                    powerNetFactorDTO.setQstatus(1);
                } else if (entity.getQLimitH() != null && curQ.compareTo(entity.getQLimitH()) > 0) {
                    powerNetFactorDTO.setQstatus(1);
                }
            }
 
            // 日功率因数
            if (StringUtils.isNotBlank(entity.getPDay()) && StringUtils.isNotBlank(entity.getQDay())) {
                List<String> pointNos = new ArrayList<>();
                pointNos.add(entity.getPDay());
                pointNos.add(entity.getQDay());
                Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(pointNos);
                if (!CollectionUtils.isEmpty(pointsRealValue)) {
                    double pValue = new BigDecimal(pointsRealValue.get(entity.getPDay()).toString()).doubleValue();
                    double qValue = new BigDecimal(pointsRealValue.get(entity.getQDay()).toString()).doubleValue();
                    powerNetFactorDTO.setDayCos(new BigDecimal(PowerUtil.calculateCos(pValue, qValue)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
 
            // 月功率因数
            if (StringUtils.isNotBlank(entity.getPMon()) && StringUtils.isNotBlank(entity.getQMon())) {
                List<String> pointNos = new ArrayList<>();
                pointNos.add(entity.getPMon());
                pointNos.add(entity.getQMon());
                Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(pointNos);
                if (!CollectionUtils.isEmpty(pointsRealValue)) {
                    double pValue = new BigDecimal(pointsRealValue.get(entity.getPMon()).toString()).doubleValue();
                    double qValue = new BigDecimal(pointsRealValue.get(entity.getQMon()).toString()).doubleValue();
                    powerNetFactorDTO.setMonthCos(new BigDecimal(PowerUtil.calculateCos(pValue, qValue)).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
            result.add(powerNetFactorDTO);
        }
        return success(result);
    }
 
    @GetMapping("/net-factor-dropdown/list")
    @Operation(summary = "功率因数-电网拓扑下拉列表")
    public CommonResult<List<PowerNetDropdownDTO>> getPowerNetFactorDropdownList(@RequestParam String nodeCode) {
        log.info("nodeCode=" + nodeCode);
        List<PowerNetDropdownDTO> result = new ArrayList<>();
        PowerNetFactorEntity entity = powerNetFactorService.getByNodeCode(nodeCode);
        if (entity == null) {
            return success(result);
        }
        List<PowerNetDropdownEntity> list = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        if ("望铁关口".equals(entity.getGroupName())) {
            params.put("groupName", entity.getGroupName());
            params.put("neNodeName", entity.getNodeName());
        } else {
            params.put("groupName", entity.getNodeName());
        }
        list = powerNetDropdownService.list(params);
        List<String> points = list.stream().map(item -> {
            return item.getCurCos();
        }).collect(Collectors.toList());
        Map<String, Object> pointsRealValue = new HashMap<>();
        if (!CollectionUtils.isEmpty(points)) {
            pointsRealValue = dataPointApi.queryPointsRealValue(points);
        }
        for (PowerNetDropdownEntity netDropdown : list) {
            PowerNetDropdownDTO dto = ConvertUtils.sourceToTarget(netDropdown, PowerNetDropdownDTO.class);
            BigDecimal curCos = BigDecimal.ZERO;
            if (pointsRealValue.get(netDropdown.getCurCos()) != null) {
                curCos = new BigDecimal(pointsRealValue.get(netDropdown.getCurCos()).toString());
            }
            dto.setCurCos(curCos);
            result.add(dto);
        }
        return success(result);
    }
 
    /**
     * 判断 curCos 是否超上下限
     * {nodeName}功率因数超上限/下限。
     * <p>
     * 判断 curQ
     * {nodeName}发生无功返送
     */
    @GetMapping("/net-factor/alarm")
    @Operation(summary = "功率因数-电网拓扑预警信息")
    public CommonResult<List<String>> getPowerNetFactorAlarm(@RequestParam Map<String, Object> params) {
        List<String> result = new ArrayList<>();
        List<PowerNetFactorEntity> list = powerNetFactorService.list(params);
        List<PowerNetFactorDTO> dtoList = ConvertUtils.sourceToTarget(list, PowerNetFactorDTO.class);
        if (CollectionUtils.isEmpty(dtoList)) {
            return success(result);
        }
        for (PowerNetFactorEntity entity : list) {
            List<String> points = new ArrayList<>();
            String message = "";
            if (StringUtils.isNotBlank(entity.getCurQ())) {
                points.add(entity.getCurQ());
            }
            if (StringUtils.isNotBlank(entity.getCurCos())) {
                points.add(entity.getCurCos());
            }
            if (CollectionUtils.isEmpty(points)) {
                continue;
            }
 
            Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(points);
            if (pointsRealValue.get(entity.getCurQ()) != null) {
                BigDecimal curQ = new BigDecimal(pointsRealValue.get(entity.getCurQ()).toString());
                if (entity.getCurFlag() != null && curQ.compareTo(BigDecimal.ZERO) == entity.getCurFlag()) {
                    message = entity.getNodeName() + "发生无功返送;";
                }
            }
            if (pointsRealValue.get(entity.getCurCos()) != null) {
                BigDecimal curCos = new BigDecimal(pointsRealValue.get(entity.getCurCos()).toString());
                if (entity.getLimitH() != null && curCos.compareTo(entity.getLimitH()) > 0) {
                    message += entity.getNodeName() + "功率因数超上限";
                } else if (entity.getLimitL() != null && curCos.compareTo(entity.getLimitL()) < 0) {
                    message += entity.getNodeName() + "功率因数超下限";
                }
            }
            if (!message.isEmpty()) {
                result.add(message);
            }
        }
        return success(result);
    }
 
    @GetMapping("/gen-status/list")
    @Operation(summary = "功率因数-发电机组实时状态")
    public CommonResult<List<PowerGenStatusDTO>> getPowerGenStatusList(@RequestParam Map<String, Object> params) {
        List<PowerGenStatusDTO> result = new ArrayList<>();
        List<PowerGenStatusEntity> list = powerGenStatusDaoService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            return success(result);
        }
        for (PowerGenStatusEntity entity : list) {
            PowerGenStatusDTO dto = new PowerGenStatusDTO();
            dto.setId(entity.getId());
            dto.setName(entity.getName());
            dto.setSort(entity.getSort());
 
            List<String> points = new ArrayList<>();
            if (StringUtils.isNotBlank(entity.getCurP())) {
                points.add(entity.getCurP());
            }
            if (StringUtils.isNotBlank(entity.getCurQ())) {
                points.add(entity.getCurQ());
            }
            if (StringUtils.isNotBlank(entity.getCurCos())) {
                points.add(entity.getCurCos());
            }
            if (!CollectionUtils.isEmpty(points)) {
                Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(points);
                if (pointsRealValue.get(entity.getCurP()) != null) {
                    dto.setCurP(new BigDecimal(pointsRealValue.get(entity.getCurP()).toString()));
                }
                if (pointsRealValue.get(entity.getCurQ()) != null) {
                    dto.setCurQ(new BigDecimal(pointsRealValue.get(entity.getCurQ()).toString()));
                }
                if (pointsRealValue.get(entity.getCurCos()) != null) {
                    dto.setCurCos(new BigDecimal(pointsRealValue.get(entity.getCurCos()).toString()));
                }
            }
 
            result.add(dto);
        }
 
        return success(result);
    }
 
    @PostMapping("/gen-status/history")
    @Operation(summary = "功率因数-发电机组功率历史")
    public CommonResult<PowerHistoryDTO> getPowerGenStatusHistory(@RequestBody PowerGenStatusHisReqDTO dto) {
        log.info("请求参数: {}", JSONObject.toJSONString(dto));
 
        // 参数校验
        if (StringUtils.isBlank(dto.getId())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "id不能为空");
        }
        if (StringUtils.isBlank(dto.getQueryType())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "queryType不能为空");
        }
        log.info("id={}", dto.getId());
        PowerGenStatusEntity powerGenStatus = powerGenStatusDaoService.getById(dto.getId());
        if (powerGenStatus == null) {
            log.info("未找到code对应的数据: {}", dto.getId());
            return success(new PowerHistoryDTO());
        }
 
        String queryType = dto.getQueryType().toUpperCase();
        log.info("queryType={}", queryType);
        String pointNo;
        switch (queryType.toUpperCase()) {
            case "P":
                pointNo = powerGenStatus.getCurP();
                break;
            case "Q":
                pointNo = powerGenStatus.getCurQ();
                break;
            case "COS":
                pointNo = powerGenStatus.getCurCos();
                break;
            default:
                throw new IllegalArgumentException("不支持的queryType: " + queryType);
        }
        log.info("开始查询,pointNo={}", pointNo);
 
        // 默认查最近24小时
        Date end = Optional.ofNullable(dto.getEndTime()).orElseGet(() -> {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            return cal.getTime();
        });
 
        Date start = Optional.ofNullable(dto.getStartTime()).orElseGet(() -> {
            Calendar cal = Calendar.getInstance();
            cal.setTime(end);
            cal.add(Calendar.MINUTE, -1440); // 24小时前
            return cal.getTime();
        });
 
        // 查询历史数据
        ApiPointValueQueryDTO query = new ApiPointValueQueryDTO();
        query.setPointNo(pointNo);
        query.setStart(start);
        query.setEnd(end);
 
        log.info("开始查询发电机组功率历史数据,测点: {}", pointNo);
        List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(query);
 
        // 构建返回结果
        PowerHistoryDTO result = new PowerHistoryDTO();
        result.setCategories(DateUtils.getTimeScale(start, end, 60));
        result.setDataList(chartData.stream()
                .map(pv -> new Object[]{
                        DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND),
                        pv.getV()
                })
                .collect(Collectors.toList()));
 
        return success(result);
    }
 
    @GetMapping("/capacitor-status/list")
    @Operation(summary = "功率因数-电容器投退状态")
    public CommonResult<List<PowerCapacitorStatusDTO>> getPowerCapacitorStatusList(@RequestParam Map<String, Object> params) {
        List<PowerCapacitorStatusDTO> result = new ArrayList<>();
        List<PowerCapacitorStatusEntity> list = powerCapacitorStatusService.list(params);
        for (PowerCapacitorStatusEntity entity : list) {
            PowerCapacitorStatusDTO dto = new PowerCapacitorStatusDTO();
            dto.setId(entity.getId());
            dto.setName(entity.getName());
            dto.setRemark(entity.getRemark());
            dto.setMainCount(DecimalUtil.toBigDecimal(entity.getMainCount()).intValue());
            dto.setChildCount(DecimalUtil.toBigDecimal(entity.getChildCount()).intValue());
            int onCount = 0;
            Map<String, Object> params1 = new HashMap<>();
            params1.put("statusId", entity.getId());
            List<PowerCapacitorDetEntity> detList = powerCapacitorDetService.list(params1);
            if (CollectionUtils.isEmpty(detList)) {
                dto.setOnCount(onCount);
                continue;
            }
            List<String> points = new ArrayList<>();
            Map<String, Object> pointsRealValue = new HashMap<>();
            for (PowerCapacitorDetEntity det : detList) {
                if (StringUtils.isNotBlank(det.getPointNo())) {
                    points.add(det.getPointNo());
                }
            }
            if (!CollectionUtils.isEmpty(points)) {
                pointsRealValue = dataPointApi.queryPointsRealValue(points);
            }
            for (PowerCapacitorDetEntity det : detList) {
                if (StringUtils.isBlank(det.getId())) {
                    continue;
                }
                Object obj = pointsRealValue.get(det.getPointNo());
                if (obj == null) {
                    continue;
                }
                BigDecimal pv = new BigDecimal(obj.toString());
                if (pv.compareTo(BigDecimal.ZERO) <= 0) {
                    continue;
                }
                onCount++;
            }
            dto.setOnCount(onCount);
            String remark = String.format("共%d台,在投%d台", DecimalUtil.toBigDecimal(entity.getMainCount()).intValue(), onCount);
            dto.setRemark(remark);
            result.add(dto);
        }
        return success(result);
    }
 
    @GetMapping("/capacitor-det/list")
    @Operation(summary = "功率因数-电容器投退指示灯")
    public CommonResult<List<PowerCapacitorDetDTO>> getPowerCapacitorDetList(@RequestParam Map<String, Object> params) {
        List<PowerCapacitorDetEntity> list = powerCapacitorDetService.list(params);
        log.info("list.size=" + list.size());
        List<String> points = new ArrayList<>();
        Map<String, Object> pointsRealValue = new HashMap<>();
        for (PowerCapacitorDetEntity det : list) {
            if (StringUtils.isNotBlank(det.getPointNo())) {
                points.add(det.getPointNo());
            }
        }
        if (!CollectionUtils.isEmpty(points)) {
            pointsRealValue = dataPointApi.queryPointsRealValue(points);
        }
 
        List<PowerCapacitorDetDTO> result = new ArrayList<>();
        for (PowerCapacitorDetEntity entity : list) {
            PowerCapacitorDetDTO dto = ConvertUtils.sourceToTarget(entity, PowerCapacitorDetDTO.class);
            result.add(dto);
            dto.setStatus(0);
            if (!pointsRealValue.containsKey(entity.getPointNo()) || pointsRealValue.get(entity.getPointNo()) == null) {
                continue;
            }
            BigDecimal val = new BigDecimal(pointsRealValue.get(entity.getPointNo()).toString());
            if (val.compareTo(BigDecimal.ZERO) >= 0.1) {
                dto.setStatus(1);
            }
        }
        return success(result);
    }
 
    @GetMapping("/capacitor-his/list")
    @Operation(summary = "功率因数-电容器投退历史")
    public CommonResult<List<PowerCapacitorHisDTO>> getPowerCapacitorHisList(@RequestParam Map<String, Object> params) {
        String statusId = (String) params.get("statusId");
        if (StringUtils.isBlank(statusId)) {
            return success(new ArrayList<>());
        }
 
        List<PowerCapacitorDetEntity> detList = powerCapacitorDetService.list(statusId);
        List<String> detIds = detList.stream().map(PowerCapacitorDetEntity::getId).collect(Collectors.toList());
        List<PowerCapacitorHisEntity> list = powerCapacitorHisService.list(detIds);
        return success(ConvertUtils.sourceToTarget(list, PowerCapacitorHisDTO.class));
    }
 
    @PostMapping("/capacitor-his/page")
    @Operation(summary = "功率因数-电容器投退历史(分页)")
    public CommonResult<PageResult<PowerCapacitorHisDTO>> getPowerCapacitorHisPage(@RequestBody PowerCapacitorHisPageReqVO reqVO) {
        if (StringUtils.isBlank(reqVO.getStatusId())) {
            return error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
 
        List<PowerCapacitorDetEntity> detList = powerCapacitorDetService.list(reqVO.getStatusId());
        List<String> detIds = detList.stream().map(PowerCapacitorDetEntity::getId).collect(Collectors.toList());
        reqVO.setDetIdList(detIds);
 
        PageResult<PowerCapacitorHisEntity> data = powerCapacitorHisService.page(reqVO);
        return success(BeanUtils.toBean(data, PowerCapacitorHisDTO.class));
    }
 
    @GetMapping("/control-main/list")
    @Operation(summary = "功率因数-管控变电站列表(已废弃)")
    public CommonResult<List<PowerControlMainDTO>> getPowerControlMainList(@RequestParam Map<String, Object> params) {
        List<PowerControlMainEntity> list = powerControlMainService.list(params);
        return success(ConvertUtils.sourceToTarget(list, PowerControlMainDTO.class));
    }
 
    @PostMapping("/control-main/update")
    @Operation(summary = "功率因数-管控变电站修改上下限(已废弃)")
    public CommonResult<Boolean> updatePowerControlMain(@RequestBody PowerControlMainDTO dto) {
        if (StringUtils.isBlank(dto.getId())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        PowerControlMainEntity entity = new PowerControlMainEntity();
        entity.setId(dto.getId());
        entity.setLimitH(dto.getLimitH());
        entity.setLimitL(dto.getLimitL());
        powerControlMainService.update(entity);
        return success(true);
    }
 
    @GetMapping("/control-det/list")
    @Operation(summary = "功率因数-管控功率因数详情(已废弃)")
    public CommonResult<List<PowerControlDetDTO>> getPowerControlDetList(@RequestParam Map<String, Object> params) {
        List<PowerControlDetDTO> result = new ArrayList<>();
        String name = (String) params.get("name");
        if (StringUtils.isBlank(name)) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        PowerControlMainEntity main = powerControlMainService.getByName(name);
        if (main == null) {
            return CommonResult.error(GlobalErrorCodeConstants.NOT_FOUND);
        }
        List<PowerControlDetEntity> list = powerControlDetService.list(main.getId());
        result = ConvertUtils.sourceToTarget(list, PowerControlDetDTO.class);
 
        result.forEach(item -> {
            /*BigDecimal rv = new BigDecimal(randomNumber * 0.001).setScale(4, BigDecimal.ROUND_HALF_UP);
            item.setValue(rv);
            if (item.getLimitL() != null && rv.compareTo(item.getLimitL()) < 0) {
                item.setStatus(1);
            } else {
                item.setStatus(0);
            }*/
        });
        return success(result);
    }
 
    @GetMapping("/demand/list")
    @Operation(summary = "负荷移植-月最大需量,实测需量,有功功率")
    public CommonResult<List<PowerDemandDTO>> getPowerDemandList(@RequestParam Map<String, Object> params) {
        log.info("负荷移植-月最大需量,实测需量,有功功率");
        List<PowerDemandDTO> result = new ArrayList<>();
        List<PowerDemandEntity> list = powerDemandService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            log.info("list.size=" + list.size());
            return success(result);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date start = calendar.getTime();
        Date end = new Date();
 
        for (PowerDemandEntity entity : list) {
            PowerDemandDTO demandDTO = new PowerDemandDTO();
            demandDTO.setId(entity.getId());
            demandDTO.setCode(entity.getCode());
            demandDTO.setName(entity.getName());
 
            List<String> points = new ArrayList<>();
            if (StringUtils.isNotBlank(entity.getCurDemand())) {
                points.add(entity.getCurDemand());
            }
            if (StringUtils.isNotBlank(entity.getActivePower())) {
                points.add(entity.getActivePower());
            }
            if (!CollectionUtils.isEmpty(points)) {
                Map<String, Object> pointsRealValue = dataPointApi.queryPointsRealValue(points);
                if (pointsRealValue.get(entity.getCurDemand()) != null) {
                    demandDTO.setCurDemand(new BigDecimal(pointsRealValue.get(entity.getCurDemand()).toString()));
                }
                if (pointsRealValue.get(entity.getActivePower()) != null) {
                    demandDTO.setActivePower(new BigDecimal(pointsRealValue.get(entity.getActivePower()).toString()));
                }
            }
 
            if (!StringUtils.isEmpty(entity.getMaxDemand())) {
                /*ApiPointValueQueryDTO apiPointValueQueryDTO = new ApiPointValueQueryDTO();
                apiPointValueQueryDTO.setStart(start);
                apiPointValueQueryDTO.setEnd(end);
                apiPointValueQueryDTO.setPointNo(entity.getMaxDemand());
                Map<String, Object> maxValue = dataPointApi.queryPointMaxTimeValue(apiPointValueQueryDTO);
                if (maxValue != null) {
                    demandDTO.setMaxDemand(new BigDecimal(maxValue.get(VALUE).toString()));
                    demandDTO.setOccurTime(DateUtils.parse( maxValue.get(TIME).toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
                }*/
                PowerMaxdemandMainEntity maxdemandMainEntity = powerMaxDemandMainService.getMonthMax(entity.getCode(), start);
                if (maxdemandMainEntity != null) {
                    demandDTO.setMaxDemand(maxdemandMainEntity.getMaxDemand());
                    demandDTO.setOccurTime(maxdemandMainEntity.getOccurTime());
                }
            }
            result.add(demandDTO);
        }
        return success(result);
    }
 
    @GetMapping("/demand-dropdown/list")
    @Operation(summary = "负荷移植-功率因数下拉列表")
    public CommonResult<List<PowerNetDropdownDTO>> getDemandDropdownList(@RequestParam String code) {
        if (StringUtils.isBlank(code)) {
            log.info("code isBlank");
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        log.info("code=" + code);
 
        List<PowerNetDropdownDTO> result = new ArrayList<>();
        PowerDemandEntity entity = powerDemandService.getByCode(code);
        if (entity == null) {
            log.info("PowerDemandEntity is null");
            return success(result);
        }
        Map<String, Object> params0 = new HashMap<>();
        params0.put("groupName", entity.getName());
        List<PowerNetDropdownEntity> list = powerNetDropdownService.list(params0);
        List<String> points = list.stream().map(item -> {
            return item.getCurCos();
        }).collect(Collectors.toList());
        Map<String, Object> pointsRealValue = new HashMap<>();
        if (!CollectionUtils.isEmpty(points)) {
            pointsRealValue = dataPointApi.queryPointsRealValue(points);
        }
        for (PowerNetDropdownEntity netDropdown : list) {
            PowerNetDropdownDTO dto = ConvertUtils.sourceToTarget(netDropdown, PowerNetDropdownDTO.class);
            BigDecimal curCos = BigDecimal.ZERO;
            if (pointsRealValue.get(netDropdown.getCurCos()) != null) {
                curCos = new BigDecimal(pointsRealValue.get(netDropdown.getCurCos()).toString());
            }
            dto.setCurCos(curCos);
            result.add(dto);
        }
        return success(result);
    }
 
    @PostMapping("/demand-query/list")
    @Operation(summary = "负荷移植-需量值查询")
    public CommonResult<List<PowerDemandQueryRespDTO>> getDemandQueryList(@RequestBody PowerDemandQueryDTO queryDto) {
        List<PowerDemandQueryRespDTO> result = new ArrayList<>();
        if (StringUtils.isBlank(queryDto.getCode())) {
            log.info("code isBlank");
            return success(result);
        }
        PowerDemandEntity entity = powerDemandService.getByCode(queryDto.getCode());
        if (entity == null) {
            log.info("PowerDemandEntity is null");
            return success(result);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = queryDto.getStartTime();
        Date endTime = queryDto.getEndTime();
        if (endTime == null) {
            endTime = calendar.getTime();
        }
        if (startTime == null) {
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            startTime = calendar.getTime();
        }
 
        Map<String, Object> params0 = new HashMap<>();
        params0.put("groupName", entity.getName());
        List<PowerNetDropdownEntity> dropdownList = powerNetDropdownService.list(params0);
        List<String> pointNos = new ArrayList<>();
        Map<String, String> demandPointMap = new HashMap<>();
        for (PowerNetDropdownEntity netDropdown : dropdownList) {
            demandPointMap.put(netDropdown.getNodeCode(), netDropdown.getExt1());
            if (StringUtils.isNotBlank(netDropdown.getExt1())) {
                pointNos.add(netDropdown.getExt1());
            }
        }
        for (PowerNetDropdownEntity netDropdown : dropdownList) {
            PowerDemandQueryRespDTO dto = ConvertUtils.sourceToTarget(netDropdown, PowerDemandQueryRespDTO.class);
            dto.setCurDemand(null);
            result.add(dto);
        }
        if (queryDto.getCurDemand() == null) {
            log.info("查询值为空,显示空白");
            return success(result);
        }
        ApiPointValueQueryDTO queryCodeValue = new ApiPointValueQueryDTO();
        queryCodeValue.setStart(startTime);
        queryCodeValue.setEnd(endTime);
        queryCodeValue.setPointNo(entity.getCurDemand());
        List<ApiPointValueDTO> codeValueList = dataPointApi.queryPointHistoryValue(queryCodeValue);
        if (CollectionUtils.isEmpty(codeValueList)) {
            return success(result);
        }
        ApiPointValueDTO curValue = new ApiPointValueDTO();
        for (ApiPointValueDTO valueDTO : codeValueList) {
            if (Math.abs(queryDto.getCurDemand().doubleValue() - valueDTO.getV()) <= 0.0001) {
                log.info("curValue is find");
                curValue = valueDTO;
                break;
            }
        }
        log.info("curValue={}", curValue);
        if (curValue.getT() == null) {
            log.info("curValue is not find");
            return success(result);
        }
 
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(curValue.getT());
        ApiPointsValueQueryDTO valueQueryDTO = new ApiPointsValueQueryDTO();
        valueQueryDTO.setPointNos(pointNos);
        valueQueryDTO.setEnd(calendar1.getTime());
        calendar1.add(Calendar.MINUTE, -1);
        valueQueryDTO.setStart(calendar1.getTime());
        Map<String, List<Map<String, Object>>> pointsHisValues = dataPointApi.queryPointsHistoryValue(valueQueryDTO);
        if (CollectionUtils.isEmpty(pointsHisValues)) {
            log.info("pointsHisValues is null");
            return success(result);
        }
        for (PowerDemandQueryRespDTO respDTO : result) {
            if (StringUtils.isBlank(demandPointMap.get(respDTO.getNodeCode()))) {
                continue;
            }
            List<Map<String, Object>> hisList = pointsHisValues.get(demandPointMap.get(respDTO.getNodeCode()));
            if (CollectionUtils.isEmpty(hisList)) {
                continue;
            }
            Map<String, Object> valueMap = hisList.get(hisList.size() - 1);
            respDTO.setDataTime(DateUtils.parse(valueMap.get("time").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
            respDTO.setCurDemand(DecimalUtil.toBigDecimal(valueMap.get("value")));
        }
        return success(result);
    }
 
    /**
     * 导出功率日累计
     * 月报表导出:最大值、最小值、平均值、受电累计、返送累计
     * 日功率因数二级界面:最大值、最小值、平均值、日功率因数
     * 月功率因数二级界面:最大值、最小值、平均值、月功率因数
     *
     * @param response
     * @param request
     * @param dto
     */
    @PostMapping("/net-factor/export-day")
    @Operation(summary = "功率因数-电网拓扑功率导出(功率日累计)")
    public void getPowerFactorExportDay(HttpServletResponse response, HttpServletRequest
            request, @RequestBody PowerFactorExcelReqDTO dto) throws IOException {
 
        List<PowerExportPqVO> exportPqList = new ArrayList<>();
        List<PowerExportCosVO> exportCos = new ArrayList<>();
 
        if (dto.getStartTime() == null) {
            dto.setStartTime(new Date());
        }
        if (dto.getEndTime() == null) {
            dto.setEndTime(new Date());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dto.getStartTime());
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        Date startTime = calendar.getTime();
        calendar.setTime(dto.getEndTime());
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        Date endTime = calendar.getTime();
 
        String pointNo = "=";
        String[] pointNoArr = new String[2];
        String queryType = dto.getQueryType();
        PowerNetFactorEntity powerNetFactorEntity = powerNetFactorService.getByNodeCode(dto.getNodeCode());
        Calendar curDay = Calendar.getInstance();
        curDay.setTime(startTime);
        do {
            log.info("do excel");
            PowerFactorExcelDTO excelDTO = new PowerFactorExcelDTO();
            switch (queryType.toUpperCase()) {
                case "P":
                    pointNo = powerNetFactorEntity.getCurP();
                    break;
                case "Q":
                    pointNo = powerNetFactorEntity.getCurQ();
                    break;
                case "DAYCOS":
                    pointNoArr[0] = powerNetFactorEntity.getPDay();
                    pointNoArr[1] = powerNetFactorEntity.getQDay();
                    break;
                case "MONTHCOS":
                    pointNoArr[0] = powerNetFactorEntity.getPMon();
                    pointNoArr[1] = powerNetFactorEntity.getQMon();
                    break;
                default:
                    return;
            }
 
            ApiPointValueQueryDTO apiPointValueQueryDTO = new ApiPointValueQueryDTO();
            apiPointValueQueryDTO.setStart(curDay.getTime());
            curDay.add(Calendar.DAY_OF_YEAR, 1);
            apiPointValueQueryDTO.setEnd(curDay.getTime());
            List<Double> valueList = new ArrayList<>();
            Double lastValue = null;
            if (StringUtils.isNotBlank(pointNo)) {
                // 单点
                apiPointValueQueryDTO.setPointNo(pointNo);
                List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
                for (ApiPointValueDTO pv : chartData) {
                    Object[] data = new Object[2];
                    data[0] = DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
                    data[1] = pv.getV();
                    valueList.add(pv.getV());
                }
            } else if (StringUtils.isNotBlank(pointNoArr[0]) && StringUtils.isNotBlank(pointNoArr[1])) {
                List<String> categories = new ArrayList<>();
 
                // P/Q
                apiPointValueQueryDTO.setPointNo(pointNoArr[0]);
                List<ApiPointValueDTO> chartDataP = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
                Map<String, Double> dataMapP = new HashMap<>();
                for (ApiPointValueDTO pv : chartDataP) {
                    categories.add(DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
                    dataMapP.put(DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND), pv.getV());
                }
 
                apiPointValueQueryDTO.setPointNo(pointNoArr[1]);
                List<ApiPointValueDTO> chartDataQ = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
                Map<String, Double> dataMapQ = new HashMap<>();
                for (ApiPointValueDTO pv : chartDataQ) {
                    dataMapQ.put(DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND), pv.getV());
                }
                for (String cate : categories) {
                    Double cos = PowerUtil.calculateCos(dataMapP.get(cate), dataMapQ.get(cate));
                    valueList.add(cos);
                }
 
            }
 
            double max = 0;
            double min = 0;
            double avg = 0;
            if (!CollectionUtils.isEmpty(valueList)) {
                max = valueList.stream().mapToDouble(Double::doubleValue).max().getAsDouble();
                min = valueList.stream().mapToDouble(Double::doubleValue).min().getAsDouble();
                avg = valueList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
            }
 
            if ("P".equals(queryType.toUpperCase()) || "Q".equals(queryType.toUpperCase())) {
                PowerExportPqVO evo = new PowerExportPqVO();
                double sdl = 0;
                double fsl = 0;
                if (!CollectionUtils.isEmpty(valueList)) {
                    if (powerNetFactorEntity.getCurFlag() != null && powerNetFactorEntity.getCurFlag().intValue() != 0) {
                        for ( Double val : valueList) {
                            if (new BigDecimal(val).compareTo(BigDecimal.ZERO) != powerNetFactorEntity.getCurFlag()) {
                                // 未发生返送
                                sdl += val;
                            } else {
                                // 发生返送
                                fsl += val;
                            }
                        }
                    }
                }
                evo.setSdl(new BigDecimal(sdl).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setFsl(new BigDecimal(fsl).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setMax(new BigDecimal(max).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setMin(new BigDecimal(min).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setAvg(new BigDecimal(avg).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setDate(DateUtils.format(apiPointValueQueryDTO.getStart()));
                exportPqList.add(evo);
            } else if ("DAYCOS".equals(queryType.toUpperCase()) || "MONTHCOS".equals(queryType.toUpperCase())) {
                double dayLast = 0;
                if (!CollectionUtils.isEmpty(valueList)) {
                    dayLast = valueList.get(valueList.size() - 1);
                }
                PowerExportCosVO evo = new PowerExportCosVO();
                evo.setCos(new BigDecimal(dayLast).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setMax(new BigDecimal(max).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setMin(new BigDecimal(min).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setAvg(new BigDecimal(avg).setScale(2, BigDecimal.ROUND_HALF_UP));
                evo.setDate(DateUtils.format(apiPointValueQueryDTO.getStart()));
                exportCos.add(evo);
            }
 
        } while (curDay.getTime().getTime() <= endTime.getTime());
 
        if ("P".equals(queryType.toUpperCase()) || "Q".equals(queryType.toUpperCase())) {
            String name = powerNetFactorEntity.getNodeName() +
                    queryType.toUpperCase().replace("P", "有功").replace("Q", "无功") +
                    "功率报表.xls";
            ExcelUtils.write(response, name, "功率数据", PowerExportPqVO.class, exportPqList);
        } else if ("DAYCOS".equals(queryType.toUpperCase()) || "MONTHCOS".equals(queryType.toUpperCase())) {
            String name = powerNetFactorEntity.getNodeName() +
                    queryType.toUpperCase().replace("DAYCOS", "日").replace("MONTHCOS", "月") +
                    "功率因数报表.xls";
            ExcelUtils.write(response, name, "功率数据", PowerExportPqVO.class, exportPqList);
        }
    }
 
    @PostMapping("/net-factor/history")
    @Operation(summary = "功率因数-电网拓扑功率历史")
    public CommonResult<PowerHistoryDTO> getPowerHistoryData(@RequestBody PowerNetFactorHisReqDTO dto) {
        log.info("PowerNetFactorHisReqDTO=" + JSONObject.toJSONString(dto));
        PowerHistoryDTO result = new PowerHistoryDTO();
        String nodeCode = dto.getNodeCode();
        if (StringUtils.isBlank(nodeCode)) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        String queryType = dto.getQueryType();
        if (StringUtils.isBlank(queryType)) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        PowerNetFactorQuery powerNetFactorQuery = null;
        PowerNetFactorEntity powerNetFactorEntity = powerNetFactorService.getByNodeCode(nodeCode);
        PowerNetDropdownEntity powerNetDropdownEntity = powerNetDropdownService.getByNodeCode(nodeCode);
        if (powerNetFactorEntity != null) {
            powerNetFactorQuery = ConvertUtils.sourceToTarget(powerNetFactorEntity, PowerNetFactorQuery.class);
        } else if (powerNetDropdownEntity != null) {
            powerNetFactorQuery = ConvertUtils.sourceToTarget(powerNetDropdownEntity, PowerNetFactorQuery.class);
        }
        if (powerNetFactorQuery == null) {
            log.info("powerNetFactor is null");
            return success(result);
        }
        log.info("开始查询,");
        ApiPointValueQueryDTO apiPointValueQueryDTO = new ApiPointValueQueryDTO();
        String pointNo = "";
        String[] pointNoArr = new String[2];
        switch (queryType.toUpperCase()) {
            case "P":
                pointNo = powerNetFactorQuery.getCurP();
                break;
            case "Q":
                pointNo = powerNetFactorQuery.getCurQ();
                break;
            case "COS":
                pointNo = powerNetFactorQuery.getCurCos();
                break;
            case "DAYCOS":
                pointNoArr[0] = powerNetFactorEntity.getPDay();
                pointNoArr[1] = powerNetFactorEntity.getQDay();
                break;
            case "MONTHCOS":
                pointNoArr[0] = powerNetFactorEntity.getPMon();
                pointNoArr[1] = powerNetFactorEntity.getQMon();
                break;
            default:
                break;
        }
 
 
        //查询图表
        List<Object[]> dataList = new ArrayList<>();
 
        Calendar calendar0 = Calendar.getInstance();
        calendar0.set(Calendar.MILLISECOND, 0);
        calendar0.set(Calendar.SECOND, 0);
        Date end = dto.getEndTime() == null ? calendar0.getTime() : dto.getEndTime();
        calendar0.add(Calendar.MINUTE, -1440);
        Date start = dto.getStartTime() == null ? calendar0.getTime() : dto.getStartTime();
        apiPointValueQueryDTO.setEnd(end);
        apiPointValueQueryDTO.setStart(start);
 
        List<String> categories = DateUtils.getTimeScale(start, end, 60);
        result.setCategories(categories);
        if (StringUtils.isNotBlank(pointNo)) {
            apiPointValueQueryDTO.setPointNo(pointNo);
            List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
            for (ApiPointValueDTO pv : chartData) {
                Object[] data = new Object[2];
                data[0] = DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
                data[1] = pv.getV();
                dataList.add(data);
            }
 
        } else if (StringUtils.isNotBlank(pointNoArr[0]) && StringUtils.isNotBlank(pointNoArr[1])) {
            apiPointValueQueryDTO.setPointNo(pointNoArr[0]);
            List<ApiPointValueDTO> chartDataP = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
            Map<String, Double> dataMapP = new HashMap<>();
            for (ApiPointValueDTO pv : chartDataP) {
                dataMapP.put(DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND), pv.getV());
            }
 
            apiPointValueQueryDTO.setPointNo(pointNoArr[1]);
            List<ApiPointValueDTO> chartDataQ = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
            Map<String, Double> dataMapQ = new HashMap<>();
            for (ApiPointValueDTO pv : chartDataQ) {
                dataMapQ.put(DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND), pv.getV());
            }
 
            for (String cate : categories) {
                Object[] data = new Object[2];
                data[0] = cate;
                data[1] = PowerUtil.calculateCos(dataMapP.get(cate), dataMapQ.get(cate));
                dataList.add(data);
            }
        }
 
        result.setDataList(dataList);
 
        //查询月最大最小值
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        start = calendar.getTime();
        apiPointValueQueryDTO.setStart(start);
        apiPointValueQueryDTO.setEnd(new Date());
        Map<String, Object> maxV = dataPointApi.queryPointMaxValueRange(apiPointValueQueryDTO);
        Map<String, Object> minV = dataPointApi.queryPointMaxValueRange(apiPointValueQueryDTO);
        if (maxV != null && maxV.containsKey(pointNo)) {
            result.setMax(new BigDecimal(maxV.get(pointNo).toString()));
        }
        if (minV != null && minV.containsKey(pointNo)) {
            result.setMin(new BigDecimal(minV.get(pointNo).toString()));
        }
        return success(result);
    }
 
    @PostMapping("/net-factor/history-list")
    @Operation(summary = "功率因数-电网拓扑功率历史(多code)")
    public CommonResult<LinkedHashMap<String, PowerHistoryDTO>> getPowerHistoryList(@RequestBody PowerNetFactorHisReqDTO dto) {
        log.info("PowerNetFactorHisReqDTO=" + JSONObject.toJSONString(dto));
        LinkedHashMap<String, PowerHistoryDTO> result = new LinkedHashMap<>();
        List<String> nodeCodeList = dto.getNodeCodeList();
        if (CollectionUtils.isEmpty(nodeCodeList)) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        String queryType = dto.getQueryType();
        if (StringUtils.isBlank(queryType)) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        Calendar calendar0 = Calendar.getInstance();
        calendar0.set(Calendar.MILLISECOND, 0);
        calendar0.set(Calendar.SECOND, 0);
        Date end0 = dto.getEndTime() == null ? calendar0.getTime() : dto.getEndTime();
        calendar0.set(Calendar.MINUTE, 0);
        calendar0.set(Calendar.HOUR_OF_DAY, 0);
        Date start0 = dto.getStartTime() == null ? calendar0.getTime() : dto.getStartTime();
 
 
        List<String> categories = DateUtils.getTimeScale(start0, end0, 60);
        for (String nodeCode : nodeCodeList) {
            PowerHistoryDTO powerHistoryDTO = new PowerHistoryDTO();
            PowerNetFactorQuery powerNetFactorQuery = null;
            PowerNetFactorEntity powerNetFactorEntity = powerNetFactorService.getByNodeCode(nodeCode);
            PowerNetDropdownEntity powerNetDropdownEntity = powerNetDropdownService.getByNodeCode(nodeCode);
            if (powerNetFactorEntity != null) {
                powerNetFactorQuery = ConvertUtils.sourceToTarget(powerNetFactorEntity, PowerNetFactorQuery.class);
            } else if (powerNetDropdownEntity != null) {
                powerNetFactorQuery = ConvertUtils.sourceToTarget(powerNetDropdownEntity, PowerNetFactorQuery.class);
            }
            if (powerNetFactorQuery == null) {
                log.info("powerNetFactor is null");
                continue;
            }
 
            log.info("开始查询,");
            ApiPointValueQueryDTO apiPointValueQueryDTO = new ApiPointValueQueryDTO();
            String pointNo = "";
            String[] pointNoArr = new String[2];
            switch (queryType.toUpperCase()) {
                case "P":
                    pointNo = powerNetFactorQuery.getCurP();
                    break;
                case "Q":
                    pointNo = powerNetFactorQuery.getCurQ();
                    break;
                case "COS":
                    pointNo = powerNetFactorQuery.getCurCos();
                    break;
                case "DAYCOS":
                    pointNoArr[0] = powerNetFactorEntity.getPDay();
                    pointNoArr[1] = powerNetFactorEntity.getQDay();
                    break;
                case "MONTHCOS":
                    pointNoArr[0] = powerNetFactorEntity.getPMon();
                    pointNoArr[1] = powerNetFactorEntity.getQMon();
                    break;
                default:
                    break;
            }
 
            //查询图表
            apiPointValueQueryDTO.setEnd(end0);
            apiPointValueQueryDTO.setStart(start0);
            List<Object[]> dataList = new ArrayList<>();
 
            if (StringUtils.isNotBlank(pointNo)) {
                List<Double> valueList = new ArrayList<>();
                apiPointValueQueryDTO.setPointNo(pointNo);
                List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(apiPointValueQueryDTO);
                for (ApiPointValueDTO pv : chartData) {
                    Object[] data = new Object[2];
                    data[0] = DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
                    data[1] = pv.getV();
                    dataList.add(data);
                    valueList.add(pv.getV());
                }
 
                double fsl = 0;
                double max = 0;
                double min = 0;
                double avg = 0;
                if (!CollectionUtils.isEmpty(valueList)) {
                    max = valueList.stream().mapToDouble(Double::doubleValue).max().getAsDouble();
                    min = valueList.stream().mapToDouble(Double::doubleValue).min().getAsDouble();
                    avg = valueList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
 
                    if (powerNetFactorQuery.getCurFlag() != null && powerNetFactorQuery.getCurFlag().intValue() != 0) {
                        for ( Double val : valueList) {
                            if (new BigDecimal(val).compareTo(BigDecimal.ZERO) != powerNetFactorQuery.getCurFlag()) {
                                // 未发生返送
                                continue;
                            }
                            fsl += val;
                        }
                    }
                }
 
                powerHistoryDTO.setMax(new BigDecimal(max).setScale(2, BigDecimal.ROUND_HALF_UP));
                powerHistoryDTO.setMin(new BigDecimal(min).setScale(2, BigDecimal.ROUND_HALF_UP));
                powerHistoryDTO.setAvg(new BigDecimal(avg).setScale(2, BigDecimal.ROUND_HALF_UP));
 
                // 当查询为P, Q,且有返送flag时 计算 返送累计
                if (("P".equals(queryType.toUpperCase()) || "Q".equals(queryType.toUpperCase())) &&
                        powerNetFactorQuery.getCurFlag() != null &&
                        powerNetFactorQuery.getCurFlag().intValue() != 0) {
                    powerHistoryDTO.setFsl(new BigDecimal(fsl).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
 
            } else if (StringUtils.isNotBlank(pointNoArr[0]) && StringUtils.isNotBlank(pointNoArr[1])) {
 
            }
            powerHistoryDTO.setDataList(dataList);
            result.put(nodeCode, powerHistoryDTO);
        }
        return success(result);
    }
 
    @GetMapping("/adjust-factor")
    @Operation(summary = "功率因数-调整后的功率因数与无功倒送量")
    public CommonResult<Map<String, Double>> getPowerAdjustFactor(@RequestParam Map<String, Object> params) {
        List<PowerAdjustedFactorEntity> list = powerAdjustedFactorService.list(params);
        List<PowerAdjustedFactorDTO> dtoList = ConvertUtils.sourceToTarget(list, PowerAdjustedFactorDTO.class);
        Map<String, Double> result = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            log.info("PowerAdjustedFactor List is empty");
            return success(result);
        }
        List<String> points = new ArrayList<>();
        Map<String, Object> dataMap = new HashMap<>();
        for (PowerAdjustedFactorDTO dto : dtoList) {
            if (StringUtils.isNotBlank(dto.getPointNo())) {
                points.add(dto.getPointNo());
            }
        }
        if (!CollectionUtils.isEmpty(points)) {
            dataMap = dataPointApi.queryPointsRealValue(points);
        }
 
        for (PowerAdjustedFactorDTO powerAdjustedFactorDTO : dtoList) {
            Double value = dataMap.get(powerAdjustedFactorDTO.getPointNo()) == null ? 0 : Double.parseDouble(dataMap.get(powerAdjustedFactorDTO.getPointNo()).toString());
            result.put(powerAdjustedFactorDTO.getName(), value);
        }
        return success(result);
    }
 
    @PostMapping("/demand/history")
    @Operation(summary = "负荷移植-实测需量有功功率历史")
    public CommonResult<PowerHistoryDTO> getPowerDemandHistory(@RequestBody PowerDemandHisReqDTO dto) {
        log.info("请求参数: {}", JSONObject.toJSONString(dto));
 
        // 参数校验
        if (StringUtils.isBlank(dto.getCode())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "code不能为空");
        }
        if (StringUtils.isBlank(dto.getQueryType())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "queryType不能为空");
        }
 
        PowerDemandEntity powerDemand = powerDemandService.getByCode(dto.getCode());
        if (powerDemand == null) {
            log.info("未找到code对应的数据: {}", dto.getCode());
            return success(new PowerHistoryDTO());
        }
 
        String queryType = dto.getQueryType().toUpperCase();
        String pointNo;
        switch (queryType.toUpperCase()) {
            case "D":
                pointNo = powerDemand.getCurDemand();
                break;
            case "P":
                pointNo = powerDemand.getActivePower();
                break;
            default:
                throw new IllegalArgumentException("不支持的queryType: " + queryType);
        }
 
        // 默认查最近24小时
        Date end = Optional.ofNullable(dto.getEndTime()).orElseGet(() -> {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            return cal.getTime();
        });
 
        Date start = Optional.ofNullable(dto.getStartTime()).orElseGet(() -> {
            Calendar cal = Calendar.getInstance();
            cal.setTime(end);
            cal.add(Calendar.MINUTE, -1440); // 24小时前
            return cal.getTime();
        });
 
        // 查询历史数据
        ApiPointValueQueryDTO query = new ApiPointValueQueryDTO();
        query.setPointNo(pointNo);
        query.setStart(start);
        query.setEnd(end);
 
        log.info("开始查询实测需量/有功功率历史数据,测点: {}", pointNo);
        List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(query);
 
        // 构建返回结果
        PowerHistoryDTO result = new PowerHistoryDTO();
        result.setCategories(DateUtils.getTimeScale(start, end, 60));
        result.setDataList(chartData.stream()
                .map(pv -> new Object[]{
                        DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND),
                        pv.getV()
                })
                .collect(Collectors.toList()));
 
        return success(result);
    }
 
    @PostMapping("/demand/history-list")
    @Operation(summary = "负荷移植-实测需量有功功率历史(多code)")
    public CommonResult<LinkedHashMap<String, PowerHistoryDTO>> getPowerDemandHistoryList(@RequestBody PowerDemandHisReqDTO dto) {
        log.info("请求参数: {}", JSONObject.toJSONString(dto));
        LinkedHashMap<String, PowerHistoryDTO> result = new LinkedHashMap<>();
 
        // 参数校验
        if (CollectionUtils.isEmpty(dto.getCodeList())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "codeList不能为空");
        }
        if (StringUtils.isBlank(dto.getQueryType())) {
            return CommonResult.error(GlobalErrorCodeConstants.BAD_REQUEST, "queryType不能为空");
        }
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        Date endTime = dto.getEndTime() == null ? cal.getTime() : dto.getEndTime();
        Date startTime = dto.getStartTime();
        if (dto.getStartTime() == null) {
            cal.add(Calendar.DAY_OF_YEAR, -1);
            startTime = cal.getTime();
        }
 
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.DAY_OF_MONTH, 1);
        calendar1.set(Calendar.HOUR_OF_DAY, 0);
        calendar1.set(Calendar.MINUTE, 0);
        calendar1.set(Calendar.SECOND, 0);
        calendar1.set(Calendar.MILLISECOND, 0);
        Date start1 = calendar1.getTime();
 
        for (String code : dto.getCodeList()) {
            PowerHistoryDTO powerHistoryDTO = new PowerHistoryDTO();
            PowerNetFactorQuery powerNetFactorQuery = new PowerNetFactorQuery();
            PowerDemandEntity powerDemandEntity = powerDemandService.getByCode(code);
            PowerNetDropdownEntity powerNetDropdownEntity = powerNetDropdownService.getByNodeCode(code);
            if (powerDemandEntity != null) {
                powerNetFactorQuery.setCurP(powerDemandEntity.getActivePower());
                powerNetFactorQuery.setCurDem(powerDemandEntity.getCurDemand());
            } else if (powerNetDropdownEntity != null) {
                powerNetFactorQuery.setCurP(powerNetDropdownEntity.getCurP());
                powerNetFactorQuery.setCurDem(powerNetDropdownEntity.getExt1());
            } else {
                log.info("未找到code对应的数据: {}", dto.getCode());
                continue;
            }
 
            String queryType = dto.getQueryType().toUpperCase();
            String pointNo;
            switch (queryType.toUpperCase()) {
                case "D":
                    pointNo = powerNetFactorQuery.getCurDem();
                    break;
                case "P":
                    pointNo = powerNetFactorQuery.getCurP();
                    break;
                default:
                    throw new IllegalArgumentException("不支持的queryType: " + queryType);
            }
 
            // 查询历史数据
            ApiPointValueQueryDTO query = new ApiPointValueQueryDTO();
            query.setPointNo(pointNo);
            query.setStart(startTime);
            query.setEnd(endTime);
            log.info("开始查询实测需量有功功率历史数据,测点: {}", pointNo);
            List<ApiPointValueDTO> chartData = dataPointApi.queryPointHistoryValue(query);
            List<Object[]> dataList = chartData.stream()
                    .map(pv -> new Object[]{
                            DateUtils.format(pv.getT(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND),
                            pv.getV()
                    })
                    .collect(Collectors.toList());
 
            powerHistoryDTO.setDataList(dataList);
 
            //查询月最大最小值
            ApiPointValueQueryDTO apiPointValueQueryDTO1 = new ApiPointValueQueryDTO();
            apiPointValueQueryDTO1.setStart(start1);
            apiPointValueQueryDTO1.setEnd(new Date());
            apiPointValueQueryDTO1.setPointNo(pointNo);
            Map<String, Object> maxV = dataPointApi.queryPointMaxValueRange(apiPointValueQueryDTO1);
            Map<String, Object> minV = dataPointApi.queryPointMinValueRange(apiPointValueQueryDTO1);
            if (maxV != null && maxV.containsKey(pointNo)) {
                powerHistoryDTO.setMax(new BigDecimal(maxV.get(pointNo).toString()));
            }
            if (minV != null && minV.containsKey(pointNo)) {
                powerHistoryDTO.setMin(new BigDecimal(minV.get(pointNo).toString()));
            }
 
            result.put(code, powerHistoryDTO);
        }
 
        return success(result);
    }
 
 
    @GetMapping("/voltage/status-list")
    @Operation(summary = "功率因数-母线电压状态")
    public CommonResult<List<PowerVoltageStatusDTO>> getPowerVoltageStatusList(@RequestParam Map<String, Object> params) {
        List<PowerVoltageStatusDTO> result = new ArrayList<>();
        List<PowerVoltageStatusEntity> list = powerVoltageStatusService.list(params);
        if (CollectionUtils.isEmpty(list)) {
            return success(result);
        }
 
        List<String> points = new ArrayList<>();
        for (PowerVoltageStatusEntity entity : list) {
            if (StringUtils.isBlank(entity.getPoint())) {
                continue;
            }
            points.add(entity.getPoint());
        }
        Map<String, Object> pointsRealValue = new HashMap<>();
        if (!CollectionUtils.isEmpty(points)) {
            pointsRealValue = dataPointApi.queryPointsRealValue(points);
        }
        for (PowerVoltageStatusEntity entity : list) {
            PowerVoltageStatusDTO dto = ConvertUtils.sourceToTarget(entity, PowerVoltageStatusDTO.class);
            dto.setStatus(0);
            BigDecimal value = new BigDecimal(pointsRealValue.get(entity.getPoint()).toString());
            if (value.compareTo(entity.getLimitH()) > 0) {
                dto.setStatus(1);
            }
            dto.setVoltage(value);
            result.add(dto);
        }
        return success(result);
    }
 
    @PostMapping("/power-maxdemand/page")
    @Operation(summary = "负荷移植-最大需量发生记录分页")
    public CommonResult<PageResult<PowerMaxDemandMainDTO>> getPowerMaxDemandMainPage(@RequestBody PowerMaxDemandMainPageReqVO reqVO) {
        if (StringUtils.isBlank(reqVO.getCode())) {
            log.info("code is blank");
            return error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        PageResult<PowerMaxdemandMainEntity> page = powerMaxDemandMainService.page(reqVO);
        PageResult<PowerMaxDemandMainDTO> result = BeanUtils.toBean(page, PowerMaxDemandMainDTO.class);
        result.getList().forEach(dto0 -> {
            List<PowerMaxdemandDetEntity> detList0 = powerMaxdemandDetService.selectListByRelId(dto0.getId(), dto0.getOccurTime());
            dto0.setChildren(ConvertUtils.sourceToTarget(detList0, PowerMaxdemandDetDTO.class));
            if (!CollectionUtils.isEmpty(dto0.getChildren())) {
                dto0.getChildren().forEach(dto1 -> {
                    List<PowerMaxdemandDetEntity> detList1 = powerMaxdemandDetService.selectListByRelId(dto1.getId(), dto1.getOccurTime());
                    dto1.setChildren(ConvertUtils.sourceToTarget(detList1, PowerMaxdemandDetDTO.class));
                });
            }
        });
        return success(result);
    }
 
    @PostMapping("/power-maxdemand/det-list")
    @Operation(summary = "负荷移植-最大需量发生记录详情")
    public CommonResult<List<PowerMaxdemandDetDTO>> getPowerMaxDemandDetList(@RequestBody Map<String, Object> params) {
        String relId = (String) params.get("relId");
        if (StringUtils.isBlank(relId)) {
            return error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        List<PowerMaxdemandDetEntity> list = powerMaxdemandDetService.selectListByRelId(relId);
        return success(ConvertUtils.sourceToTarget(list, PowerMaxdemandDetDTO.class));
    }
 
    @GetMapping("/power-price/list")
    @Operation(summary = "获取峰谷平电价信息")
    public CommonResult<List<PowerPriceMainDTO>> getPowerPriceList(@RequestParam Map<String, Object> params) {
        List<PowerPriceMainDTO> result = powerPriceMainService.list(params);
        return success(result);
    }
 
    @PostMapping("/power-price/save")
    @Operation(summary = "保存峰谷平电价信息")
    public CommonResult<Boolean> savePowerPriceList(@RequestBody PowerPriceMainDTO mainDTO) {
        return success(powerPriceMainService.save(mainDTO));
    }
 
    @PostMapping("/power-price/update")
    @Operation(summary = "修改峰谷平电价信息")
    public CommonResult<Boolean> updatePowerPriceList(@RequestBody PowerPriceMainDTO mainDTO) {
        if (StringUtils.isBlank(mainDTO.getId())) {
            return error(GlobalErrorCodeConstants.BAD_REQUEST);
        }
        return success(powerPriceMainService.update(mainDTO));
    }
 
    @PostMapping("/factor-control/list")
    @Operation(summary = "功率因数调整结果查询")
    public CommonResult<List<PowerFactorControlDTO>> powerFactorControlList(@RequestBody PowerFactorReqVO powerFactorReqVO) {
        List<PowerFactorControlDTO> result = new ArrayList<>();
        Map<String, Object> chartMap = new HashMap<>();
        List<ChartParamDTO> chartList = mcsApi.getChartParamList(CommonConstant.POWER_CODE);
        chartList.forEach(item -> {
            chartMap.put(item.getParamName(), item.getParamCode());
        });
        List<String> contentList = powerFactorReqVO.getContentList();
        if (CollectionUtils.isEmpty(contentList)) {
            log.info("contentList为空");
            return new CommonResult<>();
        }
        List<Integer> contentListNew = new ArrayList<>();
        contentList.forEach(item -> {
            chartMap.forEach((key, value) -> {
                if (item.contains(key)) {
                    contentListNew.add(Integer.parseInt(value.toString()));
                }
            });
        });
 
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
 
        if (!CollectionUtils.isEmpty(powerFactorReqVO.getContentList())) {
 
        }
        MdkScheduleReqDTO dto = new MdkScheduleReqDTO();
        dto.setScheduleTime(calendar.getTime());
        dto.setScheduleCode("AnsteelOffPowerAC");
        Map<String, String> dynamicSettings = new HashMap<>();
        dynamicSettings.put("option_param", JSONArray.toJSONString(contentListNew.stream().toArray(Integer[]::new)));
        List<String> cosParam = new ArrayList<>();
        cosParam.add(powerFactorReqVO.getAdjustValueCcpp().toString());
        cosParam.add(powerFactorReqVO.getAdjustValue135().toString());
        cosParam.add(powerFactorReqVO.getAdjustValueTrt().toString());
        dynamicSettings.put("cos_param", JSONArray.toJSONString(cosParam));
        dto.setDynamicSettings(dynamicSettings);
 
        log.info("调度方案开始执行," + JSONObject.toJSONString(dto));
        // MdkScheduleRespDTO mdkScheduleRespDTO = mdkApi.doSchedule(dto);
        //log.info("调度方案执行完成," + mdkScheduleRespDTO);
 
        /*String statusCode = mdkScheduleRespDTO.getStatusCode();
        if (!CommonConstant.MDK_STATUS_100.equals(statusCode)) {
            log.info("statusCode=" + statusCode);
            return CommonResult.error(GlobalErrorCodeConstants.UNKNOWN.getCode(), "工序异常,无计算结果");
        }
 
        Map<String, Object> data = mdkScheduleRespDTO.getResult();*/
        // 调整后的功率因数
        // List<String> adjustCosList = Arrays.asList(data.get("adjust_cos").toString().split(","));
        String fakeData = "[0.39,0.98,0.98,0 91,1.0,0.93,0.86,0.89,0.98,0.9,0.97,0.89,0.84,0.91]";
        List<BigDecimal> adjustCosList = JSONArray.parseArray(fakeData, BigDecimal.class);
 
        // 无功管控结果
        BigDecimal back_wugong_buchang = new BigDecimal(36.92);
        adjustCosList.add(back_wugong_buchang);
 
        Map<Integer, BigDecimal> adjustCosMap = new HashMap<>();
        for (int i = 0; i < adjustCosList.size(); i++) {
            adjustCosMap.put(i, adjustCosList.get(i));
        }
 
        List<PowerFactorControlEntity> list = powerFactorControlService.list();
        if (CollectionUtils.isEmpty(list)) {
            log.info("list is empty");
            return success(result);
        }
 
        for (int i = 0; i < list.size(); i++) {
            PowerFactorControlEntity entity = list.get(i);
            PowerFactorControlDTO controlDTO = new PowerFactorControlDTO();
            controlDTO.setName(entity.getName());
            controlDTO.setSort(entity.getSort());
            try {
                // 预测结果
                switch (ProcessConfDataTypeEnum.getEumByCode(entity.getDataType())) {
                    case DATAPOINT:
                        List<String> params1 = new ArrayList<>();
                        params1.add(entity.getPredResult());
                        Map<String, Object> pointValues = dataPointApi.queryPointsRealValue(params1);
                        if (!CollectionUtils.isEmpty(pointValues)) {
                            controlDTO.setPredResult(DecimalUtil.toBigDecimal(pointValues.get(entity.getPredResult())));
                        }
                        break;
                    case PREDICTVALUE:
                        PredictLastValueReqVO reqVO = new PredictLastValueReqVO();
                        calendar.set(calendar.HOUR_OF_DAY, 0);
                        reqVO.setPredictTime(calendar.getTime());
                        List<String[]> itemNos = new ArrayList<>();
                        if (StringUtils.isNotBlank(entity.getPredResult())) {
                            itemNos.add(entity.getPredResult().split(","));
                        }
                        reqVO.setItemNos(itemNos);
                        Map<String, BigDecimal> preValues = mcsApi.getPredictValueByTime(reqVO);
                        if (preValues.get(entity.getPredResult()) != null) {
                            controlDTO.setPredResult(new BigDecimal(preValues.get(entity.getPredResult()).toString()));
                        }
                        break;
                    default:
                        break;
                }
 
                // 管控结果
                if (adjustCosMap.containsKey(entity.getCosIndex())) {
                    controlDTO.setAdjustCos(adjustCosMap.get(entity.getCosIndex()));
                }
            } catch (Exception ex) {
                log.info(controlDTO.getName() + "获取预测值异常," + ex.getMessage());
                ex.printStackTrace();
            }
            result.add(controlDTO);
        }
        log.info("result===" + JSONObject.toJSONString(result));
        return success(result);
    }
}