Pu Zhibing
2024-10-28 72a76cd3ad51a520100ec59481d99118ffebd33c
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
package com.ruoyi.order.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
 
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.account.api.feignClient.AppUserCarClient;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.account.api.model.TAppUserCar;
import com.ruoyi.chargingPile.api.dto.GetSiteListDTO;
import com.ruoyi.chargingPile.api.feignClient.ChargingGunClient;
import com.ruoyi.chargingPile.api.feignClient.ChargingPileClient;
import com.ruoyi.chargingPile.api.feignClient.ParkingLotClient;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.chargingPile.api.model.TChargingGun;
import com.ruoyi.chargingPile.api.model.TChargingPile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.dto.ChargingOrderGroup;
import com.ruoyi.common.core.dto.ChargingPercentProvinceDto;
import com.ruoyi.common.core.web.domain.BasePojo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringData;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.integration.api.feignClient.UploadRealTimeMonitoringDataClient;
import com.ruoyi.integration.api.model.ChargingOrderAndUploadRealTimeMonitoringDataDto;
import com.ruoyi.order.api.model.*;
import com.ruoyi.order.api.query.ChargingOrderQuery;
import com.ruoyi.common.core.dto.MongoChargingOrderQuery;
import com.ruoyi.order.api.query.TChargingCountQuery;
import com.ruoyi.order.api.query.UploadRealTimeMonitoringDataQuery;
import com.ruoyi.order.api.vo.*;
import com.ruoyi.order.api.vo.ChargingOrderInfoVO;
import com.ruoyi.order.api.vo.GetChargingOrderByLicensePlate;
import com.ruoyi.order.api.vo.TCharingOrderVO;
import com.ruoyi.order.dto.GetMyChargingOrderList;
import com.ruoyi.order.dto.GetNoInvoicedOrder;
import com.ruoyi.order.dto.MyChargingOrderInfo;
import com.ruoyi.order.dto.MyChargingOrderList;
import com.ruoyi.order.dto.OrderEvaluateVo;
import com.ruoyi.order.dto.*;
import com.ruoyi.order.service.*;
import com.ruoyi.order.util.PreviousSixMonths;
import com.ruoyi.order.vo.EndOfChargePageInfo;
import com.ruoyi.payment.api.feignClient.AliPaymentClient;
import com.ruoyi.payment.api.feignClient.WxPaymentClient;
import com.ruoyi.payment.api.vo.AliQueryOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaochen
 * @since 2024-08-07
 */
@Api(tags = "充电订单")
@RestController
@RequestMapping("/t-charging-order")
public class TChargingOrderController {
    
    private Logger log = LoggerFactory.getLogger(TChargingOrderController.class);
 
    @Resource
    private TChargingOrderService chargingOrderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TOrderEvaluateService orderEvaluateService;
    @Autowired
    private TGrantVipService tGrantVipService;
    @Resource
    private WxPaymentClient wxPaymentClient;
    
    @Resource
    private RedisService redisService;
    
    @Resource
    private AliPaymentClient aliPaymentClient;
    @Resource
    private TShoppingOrderService shoppingOrderService;
    
    @Resource
    private AppUserClient appUserClient;
    
 
    @Resource
    private TVipOrderService vipOrderService;
    @Resource
    private ParkingLotClient parkingLotClient;
    @Resource
    private TChargingOrderRefundService chargingOrderRefundService;
 
    @Resource
    private TShoppingOrderRefundService shoppingOrderRefundService;
    @Resource
    private TVipOrderRefundService vipOrderRefundService;
    @Resource
    private SiteClient siteClient;
    @Resource
    private ChargingPileClient chargingPileClient;
    @Resource
    private ChargingGunClient chargingGunClient;
    @Resource
    private AppUserCarClient appUserCarClient;
    @Resource
    private TChargingOrderAccountingStrategyService chargingOrderAccountingStrategyService;
    
    @Resource
    private TOrderInvoiceService invoiceService;
 
    /**
     * 远程调用 增加管理后台赠送会员记录
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/management/give/vip")
    public R managementGiveVip(@RequestBody TGrantVip grantVip) {
        return R.ok(tGrantVipService.save(grantVip));
    }
 
    /**
     * 远程调用根据枪id 查询最新的订单id 用户后台结束充电
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/queryOrderByGunId/{id}")
    public R<String> queryOrderByGunId(@PathVariable("id") String id) {
        List<Integer> integers = new ArrayList<>();
        integers.add(2);
        integers.add(3);
        integers.add(4);
        TChargingOrder one = chargingOrderService.lambdaQuery()
                .eq(TChargingOrder::getChargingGunId, id)
                .in(TChargingOrder::getStatus, integers)
                .one();
        if (one!=null){
            return R.ok(one.getId().toString());
        }
        return R.ok();
    }
    @ResponseBody
    @PostMapping(value = "/pay/order/list")
    @ApiOperation(value = "列表", tags = {"管理后台-支付订单-订单信息"})
    public R<PageInfo<PayOrderDto>> payOrderList(@RequestBody PayOrderQueryDto payOrderQueryDto) {
        return chargingOrderService.payOrderQuery(payOrderQueryDto);
    }
    @ResponseBody
    @PostMapping(value = "/pay/order/refund")
    @ApiOperation(value = "退款", tags = {"管理后台-支付订单-订单信息"})
    public R refund(@RequestBody PayOrderRefundDto payOrderQueryDto) {
        return chargingOrderService.payRefund(payOrderQueryDto);
    }
 
    @ResponseBody
    @GetMapping(value = "/pay/order/pay/detail")
    @ApiOperation(value = "支付信息", tags = {"管理后台-支付订单-订单信息"})
    public R<PayOrderInfoDto> payOrderList(Long orderId, Integer type) {
        switch (type) {
            case 1:
                TChargingOrder byId = chargingOrderService.getById(orderId);
                PayOrderInfoDto payOrderInfoDto = new PayOrderInfoDto();
                payOrderInfoDto.setOrderId(byId.getId().toString());
                payOrderInfoDto.setCode(byId.getCode());
                payOrderInfoDto.setTradeNo(byId.getRechargeSerialNumber());
                payOrderInfoDto.setPayType(byId.getRechargePaymentType());
                payOrderInfoDto.setPayAmount(byId.getPaymentAmount());
                payOrderInfoDto.setPayTime(byId.getCreateTime());
                payOrderInfoDto.setRefundAmount(byId.getRefundAmount());
                return R.ok(payOrderInfoDto);
            case 2:
                TShoppingOrder byId1 = shoppingOrderService.getById(orderId);
                PayOrderInfoDto payOrderInfoDto1 = new PayOrderInfoDto();
                payOrderInfoDto1.setOrderId(byId1.getId().toString());
                payOrderInfoDto1.setCode(byId1.getCode());
                payOrderInfoDto1.setTradeNo(byId1.getSerialNumber());
                payOrderInfoDto1.setPayType(byId1.getPaymentType());
                payOrderInfoDto1.setPayAmount(byId1.getPaymentAmount());
                payOrderInfoDto1.setPayTime(byId1.getCreateTime());
                payOrderInfoDto1.setRefundAmount(byId1.getRefundAmount());
                return R.ok(payOrderInfoDto1);
            case 3:
                TVipOrder byId2 = vipOrderService.getById(orderId);
                PayOrderInfoDto payOrderInfoDto2 = new PayOrderInfoDto();
                payOrderInfoDto2.setOrderId(byId2.getId().toString());
                payOrderInfoDto2.setCode(byId2.getCode());
                payOrderInfoDto2.setTradeNo(byId2.getSerialNumber());
                payOrderInfoDto2.setPayType(byId2.getPaymentType());
                payOrderInfoDto2.setPayAmount(byId2.getPaymentAmount());
                payOrderInfoDto2.setPayTime(byId2.getCreateTime());
                payOrderInfoDto2.setRefundAmount(byId2.getRefundAmount());
                return R.ok(payOrderInfoDto2);
            //todo luo 停车场订单
//                case 4:
//                    TParkingRecord byId3 = parkingLotClient.getRecordById(orderId).getData();
//                    PayOrderInfoDto payOrderInfoDto3 = new PayOrderInfoDto();
//                    payOrderInfoDto3.setOrderId(byId3.getId().toString());
//                    payOrderInfoDto3.setCode(byId3.getCode());
//                    payOrderInfoDto3.setTradeNo(byId3);
//                    payOrderInfoDto3.setPayType(0);
//                    payOrderInfoDto3.setPayAmount(new BigDecimal("0"));
//                    payOrderInfoDto3.setPayTime(LocalDateTime.now());
//                    payOrderInfoDto3.setRefundAmount(new BigDecimal("0"));
 
 
 
 
            }
        return R.ok();
 
    }
    @ResponseBody
    @GetMapping(value = "/pay/order/refund/detail")
    @ApiOperation(value = "退款信息", tags = {"管理后台-支付订单-订单信息"})
    public R refundDetail(Long orderId, Integer type) {
        switch (type) {
            case 1:
                List<TChargingOrderRefund> byId = chargingOrderRefundService.lambdaQuery().eq(TChargingOrderRefund::getChargingOrderId, orderId).orderByDesc(TChargingOrderRefund::getRefundTime).list();
                return R.ok(byId);
            case 2:
                List<TShoppingOrderRefund> list = shoppingOrderRefundService.lambdaQuery().eq(TShoppingOrderRefund::getShoppingOrderId, orderId).orderByDesc(TShoppingOrderRefund::getRefundTime).list();
                return R.ok(list);
            case 3:
                List<TVipOrderRefund> list1 = vipOrderRefundService.lambdaQuery().eq(TVipOrderRefund::getVipOrderId, orderId).orderByDesc(TVipOrderRefund::getRefundTime).list();
                return R.ok(list1);
 
        }
        return R.ok();
 
    }
 
    @ResponseBody
    @GetMapping(value = "/pay/order/charging")
    @ApiOperation(value = "充电信息", tags = {"管理后台-支付订单-订单信息"})
    public R<PayOrderChargingInfo> refundDetail(Long orderId) {
        PayOrderChargingInfo payOrderChargingInfo = new PayOrderChargingInfo();
        TChargingOrder byId = chargingOrderService.getById(orderId);
        List<Site> data = siteClient.getSiteByIds(Collections.singletonList(byId.getSiteId())).getData();
        payOrderChargingInfo.setSiteName(data.get(0).getName());
        TChargingPile data1 = chargingPileClient.getChargingPileById(byId.getChargingPileId()).getData();
        payOrderChargingInfo.setChargingName(data1.getName());
        TChargingGun data2 = chargingGunClient.getChargingGunById(byId.getChargingGunId()).getData();
        payOrderChargingInfo.setGunName(data2.getName());
        if (byId.getAppUserCarId()!=null) {
            List<TAppUserCar> data3 = appUserCarClient.getCarByIds(Collections.singletonList(byId.getAppUserCarId())).getData();
            payOrderChargingInfo.setCarNum(data3.get(0).getLicensePlate());
        }
        payOrderChargingInfo.setTChargingOrder(byId);
 
        Long count = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, orderId).count();
        payOrderChargingInfo.setPeriodCount(count);
        if (byId.getAppUserCarId()!=null) {
            List<Long> carid = new ArrayList<>();
            carid.add(byId.getAppUserCarId());
            R<List<TAppUserCar>> carByIds = appUserCarClient.getCarByIds(carid);
            payOrderChargingInfo.setCarNum(carByIds.getData().get(0).getLicensePlate());
        }
        payOrderChargingInfo.setStartTime(byId.getStartTime());
        payOrderChargingInfo.setEndTime(byId.getEndTime());
        payOrderChargingInfo.setTimeCount(payOrderChargingInfo.calculateDuration());
        return R.ok(payOrderChargingInfo);
    }
 
    @ResponseBody
    @GetMapping(value = "/pay/order/charging/details")
    @ApiOperation(value = "充电明细", tags = {"管理后台-支付订单-订单信息"})
    public R<List<TChargingOrderAccountingStrategy>> chargingDetail(Long orderId) {
        List<TChargingOrderAccountingStrategy> list = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, orderId).orderByDesc(TChargingOrderAccountingStrategy::getStartTime).list();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (TChargingOrderAccountingStrategy tChargingOrderAccountingStrategy : list) {
            String format = tChargingOrderAccountingStrategy.getCreateTime().format(formatter);
            tChargingOrderAccountingStrategy.setStartTime(format+" "+tChargingOrderAccountingStrategy.getStartTime());
            tChargingOrderAccountingStrategy.setEndTime(format+" "+tChargingOrderAccountingStrategy.getEndTime());
        }
 
 
        return R.ok(list);
    }
 
 
 
    @ResponseBody
    @PostMapping(value = "/pay/order/refund/list")
    @ApiOperation(value = "列表", tags = {"管理后台-支付订单-退款订单"})
    public R<PageInfo<TChargingOrderRefund>> refundList(@RequestBody ChargingRefundDto chargingRefundDto) {
        R<PageInfo<TChargingOrderRefund>> refundList = chargingOrderService.getRefundList(chargingRefundDto);
        for (TChargingOrderRefund record : refundList.getData().getRecords()) {
            record.setUid(record.getId().toString());
        }
        return refundList;
 
    }
    @ResponseBody
    @PostMapping(value = "/pay/order/refund/list1")
    @ApiOperation(value = "列表1", tags = {"管理后台-支付订单-退款订单"})
    public R<PageInfo<TChargingOrderRefund>> refundList1(@RequestBody ChargingRefundDto chargingRefundDto) {
        return chargingOrderService.getRefundList(chargingRefundDto);
 
    }
 
 
 
 
 
 
    @ResponseBody
    @PostMapping(value = "/chargingOrder")
    @ApiOperation(value = "充电桩订单列表", tags = {"管理后台-订单管理"})
    public AjaxResult<TCharingOrderVO> chargingOrder(@RequestBody ChargingOrderQuery dto) {
        List<Long> data = appUserClient.getUserIdsByPhone(dto.getPhone()).getData();
        dto.setUserIds(data);
        TCharingOrderVO res = chargingOrderService.chargingOrder(dto);
        return AjaxResult.success(res);
    }
 
    @ResponseBody
    @GetMapping(value = "/chargingOrderInfo")
    @ApiOperation(value = "充电桩订单列表查看详情", tags = {"管理后台-订单管理"})
    public AjaxResult<ChargingOrderInfoVO> chargingOrderInfo(String strategyId) {
        TChargingOrder byId = chargingOrderService.getById(strategyId);
        ChargingOrderInfoVO chargingOrderInfoVO = new ChargingOrderInfoVO();
        chargingOrderInfoVO.setCdElectronic(byId.getCurrent()!=null?byId.getCurrent().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setCdVoltage(byId.getVoltage()!=null?byId.getVoltage().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setSurplus(byId.getTotalElectricity()!=null?byId.getTotalElectricity().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        chargingOrderInfoVO.setTotalPower(byId.getPower()!=null?byId.getPower().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":"");
        if (byId.getAppUserCarId()!=null){
            List<TAppUserCar> data = appUserCarClient.getCarByIds(Arrays.asList(byId.getAppUserCarId())).getData();
            if (!data.isEmpty()){
                chargingOrderInfoVO.setLicensePlate(data.get(0).getLicensePlate());
                chargingOrderInfoVO.setVehicleBrand(data.get(0).getVehicleBrand());
                chargingOrderInfoVO.setVehicleModel(data.get(0).getVehicleModel());
                chargingOrderInfoVO.setVehicleUse(data.get(0).getVehicleUse());
            }
        }
        // 时段总服务费
        BigDecimal bigDecimal = new BigDecimal("0");
        List<TChargingOrderAccountingStrategy> list = chargingOrderAccountingStrategyService.lambdaQuery().eq(TChargingOrderAccountingStrategy::getChargingOrderId, strategyId).orderByDesc(TChargingOrderAccountingStrategy::getStartTime).list();
 
        for (TChargingOrderAccountingStrategy tChargingOrderAccountingStrategy : list) {
            if (byId.getVipDiscountAmount()!=null){
                BigDecimal multiply = byId.getVipDiscountAmount().divide(byId.getServiceCharge(), 2)
                        .multiply(tChargingOrderAccountingStrategy.getPeriodOriginalServicePrice());
                tChargingOrderAccountingStrategy.setVipDiscount(multiply);
            }
            bigDecimal = bigDecimal.add(tChargingOrderAccountingStrategy.getPeriodOriginalServicePrice());
 
            if (byId.getCouponDiscountAmount()!=null){
                BigDecimal multiply = byId.getCouponDiscountAmount().divide(byId.getServiceCharge(), 2)
                        .multiply(tChargingOrderAccountingStrategy.getPeriodOriginalServicePrice());
                tChargingOrderAccountingStrategy.setCouponDiscount(multiply);
            }
        }
        chargingOrderInfoVO.setList(list);
        return AjaxResult.success(chargingOrderInfoVO);
    }
 
    @ResponseBody
    @PostMapping(value = "/addEvaluate")
    @ApiOperation(value = "添加评价", tags = {"小程序-扫一扫"})
    public AjaxResult getMyChargingOrderList(@RequestBody OrderEvaluateVo dto) {
        dto.setAppUserId(tokenService.getLoginUserApplet().getUserId());
        orderEvaluateService.addOrderEvaluate(dto);
        return AjaxResult.success();
    }
    /**
     * 查询用户最近一次充电记录使用的车辆
     *
     * @param
     * @return
     */
    @GetMapping(value = "/getCar/{id}")
    public R<Long> getCar(@PathVariable("id")String id) {
        List<TChargingOrder> list = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>()
                .eq(TChargingOrder::getAppUserId, id)
                .isNotNull(TChargingOrder::getAppUserCarId));
        if (!list.isEmpty()){
            // 最近使用的车辆id
            Long size = list.get(0).getAppUserCarId();
            return R.ok(size);
        }else{
            return R.ok(-1L);
        }
    }
 
    /**
     * 查询会员在本月有多少次享受了充电折扣
     * @param req
     * @return
     */
    @PostMapping(value = "/getChargingCount")
    public R<Integer> getChargingCount(@RequestBody TChargingCountQuery req) {
        int size = chargingOrderService.list(new LambdaQueryWrapper<TChargingOrder>()
                .eq(TChargingOrder::getAppUserId, req.getUserId())
                .eq(TChargingOrder::getRechargePaymentStatus, 2)
                .between(TChargingOrder::getStartTime, req.getStartTime(), req.getEndTime())).size();
        return R.ok(size);
    }
    //用户订单数量
    @PostMapping(value = "/useOrderCount")
    public R<Long> useOrderCount(@RequestParam("userId") Long userId) {
        Long count = chargingOrderService.lambdaQuery().eq(TChargingOrder::getAppUserId, userId).count();
 
        return R.ok(count);
    }
 
    //订单详情
    @PostMapping(value = "/detail")
    public R<TChargingOrder> detail(@RequestParam("orderId") Long orderId) {
        return R.ok(chargingOrderService.getById(orderId));
    }
 
    @PostMapping(value = "/getList")
    public R<List<TChargingOrder>> getList(@RequestParam("siteId") Integer siteId) {
 
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().eq(TChargingOrder::getSiteId, siteId).list();
        return R.ok(list);
    }
 
    @PostMapping(value = "/getBySiteIdAndTime")
    public R<List<ChargingOrderGroup>> getBySiteIdAndTime(@RequestBody ChargingPercentProvinceDto chargingPercentProvinceDto) {
 
        List<ChargingOrderGroup> groups = chargingOrderService.chargingOrderGroup(chargingPercentProvinceDto);
        return R.ok(groups);
    }
 
    /**
     * 根据充电枪id获取正在进行中的订单
     * @param chargingGunId 充电枪id
     * @return
     */
    @PostMapping(value = "/getOrderDetailByGunId")
    public R<TChargingOrder> getOrderDetailByGunId(@RequestParam("chargingGunId") Integer chargingGunId) {
        TChargingOrder one = chargingOrderService.getOne(new LambdaQueryWrapper<TChargingOrder>().eq(TChargingOrder::getChargingGunId, chargingGunId)
                .eq(TChargingOrder::getDelFlag, 0).eq(TChargingOrder::getStatus, 3));
        return R.ok(one);
    }
    
    
    
    
    @ResponseBody
    @GetMapping(value = "/getMyChargingOrderList")
    @ApiOperation(value = "获取充电记录列表", tags = {"小程序-充电记录"})
    public AjaxResult<Map<String, Object>> getMyChargingOrderList(GetMyChargingOrderList query) {
        Map<String, Object> orderList = chargingOrderService.getMyChargingOrderList(query);
        return AjaxResult.success(orderList);
    }
    
    
    @ResponseBody
    @GetMapping(value = "/getMyChargingOrderInfo")
    @ApiOperation(value = "获取充电记订单明细", tags = {"小程序-充电记录"})
    public AjaxResult<MyChargingOrderInfo> getMyChargingOrderInfo(String id) {
        MyChargingOrderInfo myChargingOrderInfo = chargingOrderService.getMyChargingOrderInfo(id);
        return AjaxResult.success(myChargingOrderInfo);
    }
    
    
    
    @ResponseBody
    @GetMapping(value = "/getNoInvoicedOrder")
    @ApiOperation(value = "获取未开票的订单数据", tags = {"小程序-充电发票"})
    public AjaxResult<List<MyChargingOrderList>> getNoInvoicedOrder(GetNoInvoicedOrder query) {
        List<MyChargingOrderList> list = chargingOrderService.getNoInvoicedOrder(query);
        return AjaxResult.success(list);
    }
    
    
    
    @ResponseBody
    @PostMapping(value = "/paymentChargingOrder")
    @ApiOperation(value = "支付充电充值费用", tags = {"小程序-扫一扫"})
    public AjaxResult paymentChargingOrder(@RequestBody AddChargingOrder addChargingOrder) {
        return chargingOrderService.paymentChargingOrder(addChargingOrder);
    }
    
    /**
     * 充电充值支付回调
     */
    @ResponseBody
    @PostMapping(value = "/chargingOrderWXCallback")
    public void chargingOrderWXCallback(@RequestParam("out_trade_no") String out_trade_no, @RequestParam("transaction_id") String transaction_id,
                                        @RequestParam("attach") String attach) {
        AjaxResult ajaxResult = chargingOrderService.chargingOrderCallback(1, out_trade_no, transaction_id, attach);
    }
    
    
    /**
     * 修改安全检测数据
     * @param securityDetection
     */
    @ResponseBody
    @PostMapping(value = "/securityDetection")
    public void securityDetection(@RequestBody SecurityDetectionVO securityDetection){
        log.error("-------------------安全检测数据-------------------:" + securityDetection);
        chargingOrderService.securityDetection(securityDetection);
    }
    
    /**
     * 远程启动充电应答
     * @param message
     */
    @ResponseBody
    @PostMapping(value = "/startChargeSuccessfully")
    public void startChargeSuccessfully(@RequestBody PlatformStartChargingReplyMessageVO message){
        log.error("-------------------远程启动充电请求应答-------------------:" + message);
        chargingOrderService.startChargeSuccessfully(message);
    }
    
    
 
    /**
     * 支付宝支付成功后的回调
     */
    @ResponseBody
    @PostMapping(value = "/chargingOrderALICallback")
    public void chargingOrderALICallback(@RequestBody AliQueryOrder aliQueryOrder, HttpServletResponse response) {
        try {
            String out_trade_no = aliQueryOrder.getOutTradeNo();
            String transaction_id = aliQueryOrder.getTradeNo();
            String attach = aliQueryOrder.getPassbackParams();
            AjaxResult ajaxResult = chargingOrderService.chargingOrderCallback(2, out_trade_no, transaction_id, attach);
            if (ajaxResult.isSuccess()) {
                PrintWriter writer = response.getWriter();
                writer.println("success");
                writer.flush();
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     * 远程启动失败后退款回调
     */
    @ResponseBody
    @PostMapping(value = "/chargingOrderStartupFailureWxRefund")
    public void chargingOrderStartupFailureWxRefund(@RequestParam("out_refund_no") String out_refund_no,
                                                    @RequestParam("refund_id") String refund_id,
                                                    @RequestParam("tradeState") String tradeState,
                                                    @RequestParam("success_time") String success_time){
        chargingOrderService.chargingOrderStartupFailureWxRefund(out_refund_no, refund_id, tradeState, success_time);
    }
    
    
    
 
 
    @ResponseBody
    @GetMapping(value = "/preChargeCheck/{id}")
    @ApiOperation(value = "获取安全检测数据", tags = {"小程序-扫一扫"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "充电枪id", required = true)
    })
    public AjaxResult<PreChargeCheck> preChargeCheck(@PathVariable Integer id) {
        String key = "AQJC_" + id;
        Object cacheObject = redisService.getCacheObject(key);
        return AjaxResult.success(cacheObject);
    }
    
    
    
    @ResponseBody
    @GetMapping(value = "/getChargingDetails/{id}")
    @ApiOperation(value = "获取充电中页面数据", tags = {"小程序-扫一扫"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "充电枪id", required = true)
    })
    public AjaxResult<ChargingDetails> getChargingDetails(@PathVariable Integer id) {
        ChargingDetails chargingDetails = chargingOrderService.getChargingDetails(id);
        return AjaxResult.success(chargingDetails);
    }
 
 
    @ResponseBody
    @PutMapping(value = "/stopCharging/{id}")
    @ApiOperation(value = "手动停止充电", tags = {"小程序-扫一扫"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true)
    })
    public AjaxResult stopCharging(@PathVariable String id) {
        return chargingOrderService.stopCharging(id);
    }
    
    
    /**
     * 停止充电应答处理逻辑
     * @param platformStopChargingReply
     */
    @PostMapping("/terminateSuccessfulResponse")
    public void terminateSuccessfulResponse(@RequestBody PlatformStopChargingReplyVO platformStopChargingReply){
        log.error("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply);
        chargingOrderService.terminateSuccessfulResponse(platformStopChargingReply);
    }
    
    
    /**
     * 停止充电返回账单后计算费用
     * @param vo
     */
    @PostMapping("/endChargeBillingCharge")
    public void endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){
        log.error("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo);
        chargingOrderService.endChargeBillingCharge(vo);
    }
    
    
    
 
    @ResponseBody
    @GetMapping(value = "/six/charge")
    @ApiOperation(value = "电站收入分析", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixChargingDto>> charge(Integer siteId) {
        Long userId = SecurityUtils.getUserId();
        //如果没传siteId,获取当前登陆人所有的siteIds
        List<Integer> siteIds = new ArrayList<>();
        if (siteId==null){
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        }else {
            siteIds.add(siteId);
        }
        LocalDate sixBefore = PreviousSixMonths.get();
        //通过siteIds进行sql查询统计
        List<SixChargingDto> sixChargingDtos = generateLastSixMonths();
        List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds);
        for (SixChargingDto sixChargingDto : sixChargingDtos) {
            for (SixChargingDto chargingDto : chargingDtos) {
                if (sixChargingDto.getMonth().equals(chargingDto.getMonth())){
                    BeanUtils.copyProperties(chargingDto,sixChargingDto);
                }
            }
 
        }
 
        return R.ok(sixChargingDtos);
 
    }
 
 
    public static List<SixChargingDto> generateLastSixMonths() {
        LocalDate today = LocalDate.now();
        List<SixChargingDto> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
 
        for (int i = 5; i >= 0; i--) {
            LocalDate date = today.minusMonths(i);
            String month = date.format(formatter);
            SixChargingDto sixChargingDto = new SixChargingDto();
            sixChargingDto.setMonth(month);
            months.add(sixChargingDto);
        }
 
        return months;
    }
 
    @ResponseBody
    @GetMapping(value = "/six/circle")
    @ApiOperation(value = "电站收入占比", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixCircleDto>> circle() {
        Long userId = SecurityUtils.getUserId();
        //获取当前登录的siteIds
        List<Integer> siteIds = new ArrayList<>();
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        //进行统计groupBySiteId
        LocalDate sixBefore = PreviousSixMonths.get();
 
        List<SixCircleDto> sixCircleDtos = chargingOrderService.circle(siteIds,sixBefore);
        for (SixCircleDto sixCircleDto : sixCircleDtos) {
            Site site = siteClient.getSiteByIds(Arrays.asList(sixCircleDto.getSiteId())).getData().get(0);
            sixCircleDto.setSiteName(site.getName());
        }
        return R.ok(sixCircleDtos);
 
    }
 
 
    @ResponseBody
    @GetMapping(value = "/six/shop")
    @ApiOperation(value = "购物收入", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixShopDto>> shop(Integer status) {
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        List<SixShopDto> sixShopDtos =  shoppingOrderService.sixBefore(sixBefore,status);
        List<SixShopDto> sixChargingDtos = generateLastSixMonths1();
        for (SixShopDto sixChargingDto : sixChargingDtos) {
            for (SixShopDto chargingDto : sixShopDtos) {
                if (sixChargingDto.getMonth().equals(chargingDto.getMonth())){
                    BeanUtils.copyProperties(chargingDto,sixChargingDto);
                }
            }
 
        }
 
        return R.ok(sixChargingDtos);
    }
 
    public static List<SixShopDto> generateLastSixMonths1() {
        LocalDate today = LocalDate.now();
        List<SixShopDto> months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM");
 
        for (int i = 5; i >= 0; i--) {
            LocalDate date = today.minusMonths(i);
            String month = date.format(formatter);
            SixShopDto sixChargingDto = new SixShopDto();
            sixChargingDto.setMonth(month);
            months.add(sixChargingDto);
        }
 
        return months;
    }
 
    @ResponseBody
    @PostMapping(value = "/work/shop")
    @ApiOperation(value = "购物收入", tags = {"后台-工作台"})
    public R workShop(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto) {
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        List<Map<String,Object >> shopData =  shoppingOrderService.getData(statisticsQueryDto);
        return R.ok(shopData);
    }
 
    @ResponseBody
    @GetMapping(value = "/six/vip")
    @ApiOperation(value = "vip收入", tags = {"后台-数据分析-平台收入分析"})
    public R<List<SixVipDto>> vip() {
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        List<SixVipDto> vipDtos =  vipOrderService.sixBefore(sixBefore);
        return R.ok(vipDtos);
    }
 
    @ResponseBody
    @GetMapping(value = "/six/total")
    @ApiOperation(value = "底部数据分类", tags = {"后台-数据分析-平台收入分析"})
    public R<Map<String,Object>> total() {
        //count近6个月的数据
        LocalDate sixBefore = PreviousSixMonths.get();
        Map<String,Object>  map = chargingOrderService.countAll(sixBefore);
        BigDecimal data = parkingLotClient.getRecordAmount(sixBefore).getData();
        map.put("parkingAmount",data);
        BigDecimal data1 =   shoppingOrderService.getSumAmount(sixBefore);
        map.put("shopAmount",data1);
        BigDecimal data2 =   vipOrderService.getSumAmout(sixBefore);
        map.put("vipAmount",data2);
 
 
 
        return R.ok(map);
    }
 
    @Resource
    private UploadRealTimeMonitoringDataClient uploadRealTimeMonitoringDataClient;
    @ResponseBody
    @PostMapping(value = "/watch/chargingOrder")
    @ApiOperation(value = "监控订单", tags = {"管理后台-订单管理"})
    public R watchChargingOrder(@RequestBody MongoChargingOrderQuery mongoChargingOrderQuery) {
//        Integer page = dto.getPageCurr();
//        Integer pageSize = dto.getPageSize();
//        List<Long> data = appUserClient.getUserIdsByPhone(dto.getPhone()).getData();
//        dto.setUserIds(data);
//        dto.setPageCurr(1);
//        dto.setPageSize(99999);
 
//        Map<String,TChargingOrder> map = new HashMap<>();
//        //吧list放入map中
//        for (ChargingOrderVO record : res.getList().getRecords()) {
//            map.put(record.getCode(),record);
//        }
//        Set<String> strings = map.keySet();
 
 
        List<UploadRealTimeMonitoringData> data1 = uploadRealTimeMonitoringDataClient.getAll(mongoChargingOrderQuery).getData();
 
        List<ChargingOrderAndUploadRealTimeMonitoringDataDto> dtos = new ArrayList<>();
        Map<String,ChargingOrderVO> map  = new HashMap<>();
        for (UploadRealTimeMonitoringData uploadRealTimeMonitoringData : data1) {
            ChargingOrderAndUploadRealTimeMonitoringDataDto dataDto = new ChargingOrderAndUploadRealTimeMonitoringDataDto();
            BeanUtils.copyProperties(uploadRealTimeMonitoringData,dataDto);
            ChargingOrderQuery dto = new ChargingOrderQuery();
            dto.setCode(uploadRealTimeMonitoringData.getTransaction_serial_number());
            TCharingOrderVO vo = chargingOrderService.chargingOrder(dto);
            if (!vo.getList().getRecords().isEmpty()) {
                ChargingOrderVO chargingOrderVO = vo.getList().getRecords().get(0);
                if (chargingOrderVO != null) {
                    BeanUtils.copyProperties(chargingOrderVO, dataDto);
                }
                dtos.add(dataDto);
            }else {
                continue;
            }
        }
 
 
        return R.ok(dtos);
    }
    
    
    
    
    /**
     * 处理充电订单实时监控数据相关的业务逻辑
     * @param query
     */
    @PostMapping("/chargeMonitoring")
    public void chargeMonitoring(@RequestBody UploadRealTimeMonitoringDataQuery query){
        chargingOrderService.chargeMonitoring(query);
    }
    /**
     * 通过流水号查询订单
     * @param code
     * @return
     */
    @PostMapping(value = "/getOrderByCode/{code}")
    public R<TChargingOrder> getOrderByCode(@PathVariable("code") String code){
        return R.ok(chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class)
                .eq(TChargingOrder::getCode,code)));
    }
 
 
 
 
 
    @ResponseBody
    @PostMapping(value = "/charging/statistics")
    @ApiOperation(value = "统计,充电订单分析", tags = {"管理后台-数据分析-充电运营分析"})
    public R<TCharingOrderMapVO> watchChargingOrder(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        }else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        TCharingOrderMapVO tCharingOrderMapVO = new TCharingOrderMapVO();
 
 
        LocalDate start = null;
        LocalDate end = null;
        if (statisticsQueryDto.getDayType()==1){
            start = LocalDate.now();
            end = LocalDate.now().plusDays(1);
 
        }else if (statisticsQueryDto.getDayType()==2){
            LocalDate today = LocalDate.now();
 
            // 获取本周一的日期
            LocalDate mondayThisWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
            System.out.println("本周一是: " + mondayThisWeek);
        }
        else if (statisticsQueryDto.getDayType()==3){
            // 获取当前日期
            LocalDate today = LocalDate.now();
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
            // 获取本月1号的日期
            YearMonth yearMonth = YearMonth.from(today);
//            start = yearMonth.atDay(1);
//
//            System.out.println("本月1号是: " + start);
        }else if (statisticsQueryDto.getDayType()==4){
            LocalDate today = LocalDate.now();
            // 获取当前年份
            int currentYear = today.getYear();
            // 获取今年1月1日的日期
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        }else if (statisticsQueryDto.getDayType()==5){
 
            // 获取今年1月1日的日期
            start = statisticsQueryDto.getStartTime();
            end = statisticsQueryDto.getEndTime();
        }
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().ge(TChargingOrder::getCreateTime, start).le(TChargingOrder::getCreateTime, end).in(TChargingOrder::getSiteId, siteIds).list();
        List<Long> chargingOrderIds = list.stream().map(TChargingOrder::getId).collect(Collectors.toList());
        chargingOrderIds.add(-1L);
        //上方饼图
         List<Map<String,Object>> maps =   chargingOrderService.getSumByType(chargingOrderIds);
 
        if (statisticsQueryDto.getDayType()==1){
            List<Map<String,Object>> maps1 = chargingOrderService.getDateData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
        }else if (statisticsQueryDto.getDayType()==2){
            List<Map<String,Object>> maps1 = chargingOrderService.getWeekData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
        }else if (statisticsQueryDto.getDayType()==3){
            List<Map<String,Object>> maps1 = chargingOrderService.getMonthData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
        }else  if (statisticsQueryDto.getDayType()==4){
            List<Map<String,Object>> maps1 = chargingOrderService.getYearData(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
        }else if (statisticsQueryDto.getDayType()==5){
            List<Map<String,Object>> maps1 = chargingOrderService.getByDate(chargingOrderIds);
            tCharingOrderMapVO.setMaps1(maps1);
        }
 
 
        tCharingOrderMapVO.setMaps(maps);
 
 
        return R.ok(tCharingOrderMapVO);
 
    }
 
 
    @ResponseBody
    @PostMapping(value = "/charging/power")
    @ApiOperation(value = "功率", tags = {"管理后台-数据分析-充电运营分析"})
    public R<TCharingOrderPowerMapVO> power(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        List<Map<String,Object>> maps1 =  chargingOrderService.queryPower(siteIds);
 
 
        Map<String,Object> map =  chargingOrderService.qureryPowerLevel(siteIds,statisticsQueryDto);
 
        TCharingOrderPowerMapVO tCharingOrderPowerMapVO = new TCharingOrderPowerMapVO();
        tCharingOrderPowerMapVO.setMaps1(map);
        tCharingOrderPowerMapVO.setMaps(maps1);
        return R.ok(tCharingOrderPowerMapVO);
 
    }
 
 
    @ResponseBody
    @PostMapping(value = "/charging/users")
    @ApiOperation(value = "除电站流量外", tags = {"管理后台-数据分析-充电用户分析"})
    public R<TCharingUserMapVO> users(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
 
        TCharingUserMapVO tCharingUserMapVO = new TCharingUserMapVO();
        //上方折现
        if (statisticsQueryDto.getDayType()==1){
        List<Map<String,Object>> map = chargingOrderService.usersDay();
 
            List<Map<String, Object>> charMap = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
            for (int hour = 0; hour < 24; hour++) {
                String time = String.format("%02d:00", hour);
                Map<String, Object> mapWithTimeValue = findMapWithTimeValue(map, time);
                if (mapWithTimeValue!=null){
                    charMap.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("counts", 0);
 
                    charMap.add(timeMap);
                }
            }
 
            List<Map<String,Object>> map1 = chargingOrderService.usersDay1();
 
            List<Map<String, Object>> charMap1 = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
            for (int hour = 0; hour < 24; hour++) {
                String time = String.format("%02d:00", hour);
                Map<String, Object> mapWithTimeValue = findMapWithTimeValue(map1, time);
                if (mapWithTimeValue!=null){
                    charMap1.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("counts", 0);
 
                    charMap1.add(timeMap);
                }
            }
 
 
        tCharingUserMapVO.setMap(charMap);
        tCharingUserMapVO.setMap1(charMap1);
        }else {
            List<Map<String,Object>> map =  chargingOrderService.usersByQuery(statisticsQueryDto);
 
 
            //按日
            // 解析 startTime 和 endTime 为 LocalDate
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
 
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
 
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(map, formattedDate);
 
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("counts", 0);
                    dateRangeStatistics.add(dateMap);
                }
 
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
 
            tCharingUserMapVO.setMap(dateRangeStatistics);
 
 
            List<Map<String,Object>> map1 =  chargingOrderService.usersByQuery1(statisticsQueryDto);
 
 
 
            LocalDate startDate1 = statisticsQueryDto.getStartTime();
            LocalDate endDate1 = statisticsQueryDto.getEndTime();
 
            List<Map<String, Object>> dateRangeStatistics1 = new ArrayList<>();
 
            // 遍历日期范围
            while (!startDate1.isAfter(endDate1)) {
                String formattedDate = startDate1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(map1, formattedDate);
 
                if (dailyStats != null) {
                    dateRangeStatistics1.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("counts", 0);
                    dateRangeStatistics1.add(dateMap);
                }
 
                // 移动到下一天
                startDate1 = startDate1.plusDays(1);
            }
 
            tCharingUserMapVO.setMap1(dateRangeStatistics1);
 
 
 
 
        }
 
        //用户标签
      List<Map<String,Object>> maps =    chargingOrderService.getUserTagCount();
        Map<String,Object> stringObjectMap = new HashMap<>();
        Long noTagCount =  chargingOrderService.countNoTag();
        stringObjectMap.put("count",noTagCount);
        maps.add(stringObjectMap);
 
        //会员标签
        List<Map<String,Object>> maps1 =  chargingOrderService.getVipCount();
 
        //单位消费
        List<Map<String, Object>> untiMap  = chargingOrderService.unitConsumption(statisticsQueryDto);
 
        //车辆用途
        List<Map<String, Object>> carMap = chargingOrderService.carUserMethod();
        //车辆品牌
        List<Map<String, Object>> carBrandMap = chargingOrderService.carUserBrand();
        //本地车数量
        Map<String,Object> localCarMap = chargingOrderService.countLocalCar();
 
 
        tCharingUserMapVO.setUserMaps(maps);
        tCharingUserMapVO.setVipMaps(maps1);
        tCharingUserMapVO.setUntiMap(untiMap);
        tCharingUserMapVO.setCarMap(carMap);
        tCharingUserMapVO.setCarBrandMap(carBrandMap);
        tCharingUserMapVO.setLocalCarMap(localCarMap);
        return R.ok(tCharingUserMapVO);
 
    }
    @ResponseBody
    @PostMapping(value = "/charging/sites")
    @ApiOperation(value = "电站评价", tags = {"管理后台-数据分析-充电用户分析"})
    public R<TCharingUserEvaluateVO> sites(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        }else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        //查询评价分
        Double aver = chargingOrderService.getAver(siteIds);
        //查询各个分数
       List<Map<String,Object>> evaluate =  chargingOrderService.getLevelEvaluate(siteIds);
        //查询差评回复数
        List<Integer> mark = new ArrayList<>();
        mark.add(1);
        mark.add(2);
        Long count = orderEvaluateService.lambdaQuery().in(TOrderEvaluate::getMark, mark).isNotNull(TOrderEvaluate::getResponseTime).count();
        TCharingUserEvaluateVO tCharingUserEvaluateVO = new TCharingUserEvaluateVO();
        tCharingUserEvaluateVO.setAver(aver);
        tCharingUserEvaluateVO.setEvaluate(evaluate);
        tCharingUserEvaluateVO.setBlackCount(count);
 
 
        //好评标签
       List<Map<String,Object>> goodTop = orderEvaluateService.goodTop(siteIds);
       //差评标签
        List<Map<String,Object>> badTop = orderEvaluateService.badTop(siteIds);
 
        //流量分析
        List<Map<String,Object>> sourceMap = chargingOrderService.countBySource(siteIds);
        tCharingUserEvaluateVO.setGoodTop(goodTop);
        tCharingUserEvaluateVO.setBadTop(badTop);
        tCharingUserEvaluateVO.setFlow(sourceMap);
        //流量
        return R.ok(tCharingUserEvaluateVO);
    }
 
    @ResponseBody
    @PostMapping(value = "/charging/equipment")
    @ApiOperation(value = "电站评价", tags = {"管理后台-数据分析-设备运维分析"})
    public R<TCharingUserEquimentVO> equipment(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto){
        List<Integer> siteIds =new ArrayList<>();
        if (statisticsQueryDto.getSiteId()==null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        }else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        //直流可用率
        List<Map<String,Object>> equipmentMap1 = chargingOrderService.equipmentUserType1(siteIds,statisticsQueryDto);
        //交流可用率
        List<Map<String,Object>> equipmentMap2= chargingOrderService.equipmentUserType2(siteIds,statisticsQueryDto);
 
        //取出直流可用率和交流可用率的percent的平均值保留两位小数
 
        double average1 = calculateAveragePercent(equipmentMap1, equipmentMap2);
        System.out.printf("The average percent is: %.2f\n", average1);
 
 
        //直流故障率
        List<Map<String,Object>> equipmentMapbroke1 = chargingOrderService.equipmentMapbroke1(siteIds,statisticsQueryDto);
        //交流故障率
        List<Map<String,Object>> equipmentMapbroke2 = chargingOrderService.equipmentMapbroke2(siteIds,statisticsQueryDto);
 
 
        double average2 = calculateAveragePercent(equipmentMapbroke1, equipmentMapbroke2);
        System.out.printf("The average percent is: %.2f\n", average2);
        //直流离网率
        List<Map<String,Object>> equipmentMapOut1 = chargingOrderService.equipmentMapOut1(siteIds,statisticsQueryDto);
        //交流离网率
        List<Map<String,Object>> equipmentMapOut2 = chargingOrderService.equipmentMapOut2(siteIds,statisticsQueryDto);
 
        double average3 = calculateAveragePercent(equipmentMapOut1, equipmentMapOut2);
        System.out.printf("The average percent is: %.2f\n", average3);
 
        //需求电流满足率
        List<Map<String,Object>>  needElec1 =  chargingOrderService.needElec(siteIds,statisticsQueryDto);
        List<Map<String,Object>>  needElec2 =  chargingOrderService.needElec1(siteIds,statisticsQueryDto);
 
        double average4 = calculateAveragePercent(needElec1, needElec2);
        System.out.printf("The average percent is: %.2f\n", average4);
 
 
 
        TCharingUserEquimentVO tCharingUserEquimentVO = new TCharingUserEquimentVO();
        tCharingUserEquimentVO.setEquipmentMap1(equipmentMap1);
        tCharingUserEquimentVO.setEquipmentMap2(equipmentMap2);
        tCharingUserEquimentVO.setEquipmentMapbroke1(equipmentMapbroke1);
        tCharingUserEquimentVO.setEquipmentMapbroke2(equipmentMapbroke2);
        tCharingUserEquimentVO.setEquipmentMapOut1(equipmentMapOut1);
        tCharingUserEquimentVO.setEquipmentMapOut2(equipmentMapOut2);
        tCharingUserEquimentVO.setNeedElec1(needElec1);
        tCharingUserEquimentVO.setNeedElec2(needElec2);
        tCharingUserEquimentVO.setAverage1(average1);
        tCharingUserEquimentVO.setAverage2(average2);
        tCharingUserEquimentVO.setAverage3(average3);
        tCharingUserEquimentVO.setAverage4(average4);
        return R.ok(tCharingUserEquimentVO);
    }
 
 
    private static double calculateAveragePercent(List<Map<String, Object>> mapList1, List<Map<String, Object>> mapList2) {
        int totalElements = mapList1.size() + mapList2.size();
        double sum = 0.0;
 
        // 累加两个列表中所有元素的 "percent" 值
        for (Map<String, Object> map : mapList1) {
            if (map.containsKey("percent")) {
                sum += Double.parseDouble((String) map.get("percent"));
            }
        }
        for (Map<String, Object> map : mapList2) {
            if (map.containsKey("percent")) {
                sum += Double.parseDouble((String) map.get("percent"));
            }
        }
 
        // 防止除以零错误
        if (totalElements == 0) {
            return 0.0;
        }
 
        // 计算平均值
        return sum / totalElements;
    }
 
    @ResponseBody
    @PostMapping(value = "/work/charge")
    @ApiOperation(value = "上方充电数据统计", tags = {"管理后台-工作台"})
    public R<TCharingWorkVO> workCharge(@RequestBody ChargingStatisticsQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        LocalDateTime selectDate = statisticsQueryDto.getSelectDate();
        LocalDateTime min = selectDate.with(LocalTime.MIN);
        LocalDateTime max = selectDate.with(LocalTime.MAX);
 
 
 
 
 
        List<TChargingOrder> list = chargingOrderService.lambdaQuery().in(!siteIds.isEmpty(), TChargingOrder::getSiteId, siteIds).ge( TChargingOrder::getCreateTime,min).le(BasePojo::getCreateTime,max).eq(statisticsQueryDto.getSiteId() != null, TChargingOrder::getSiteId, statisticsQueryDto.getSiteId()).list();
        //当日的订单总数
        int size = list.size();
        //计算list中paymentAmount的总和
        BigDecimal totalPaymentAmount = list.stream().map(TChargingOrder::getOrderAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        //计算list中electrovalence的总和
        BigDecimal totalElectrovalence = list.stream().map(TChargingOrder::getElectrovalence).reduce(BigDecimal.ZERO, BigDecimal::add);
        //计算list中serviceCharge的总和
        BigDecimal totalServiceCharge = list.stream().map(TChargingOrder::getServiceCharge).reduce(BigDecimal.ZERO, BigDecimal::add);
        //计算list中charging_capacity的总和
        BigDecimal totalChargingCapacity = list.stream().map(TChargingOrder::getChargingCapacity).reduce(BigDecimal.ZERO, BigDecimal::add);
        TCharingWorkVO tCharingWorkVO = new TCharingWorkVO();
        tCharingWorkVO.setCount(size);
        tCharingWorkVO.setTotalPaymentAmount(totalPaymentAmount);
        tCharingWorkVO.setTotalElectrovalence(totalElectrovalence);
        tCharingWorkVO.setTotalServiceCharge(totalServiceCharge);
        tCharingWorkVO.setTotalChargingCapacity(totalChargingCapacity);
        return R.ok(tCharingWorkVO);
    }
 
 
 
    @ResponseBody
    @PostMapping(value = "/work/chargeDetail")
    @ApiOperation(value = "运营情况", tags = {"管理后台-工作台"})
    public R workCharge(@RequestBody ChargingDetailQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
        if (statisticsQueryDto.getDayType()==1) {
          List<Map<String,Object>> charMap1 = chargingOrderService.getHourType(siteIds,statisticsQueryDto);
            List<Map<String, Object>> charMap = new ArrayList<>();
            // 生成从 "00:00" 到 "23:00" 的时间数据
            for (int hour = 0; hour < 24; hour++) {
                String time = String.format("%02d:00", hour);
                 Map<String, Object> mapWithTimeValue = findMapWithTimeValue(charMap1, time);
                if (mapWithTimeValue!=null){
                    charMap.add(mapWithTimeValue);
                }else {
                    Map<String, Object> timeMap = new HashMap<>();
                    timeMap.put("time", time); // 初始化值为 null
                    timeMap.put("electrovalence", 0);
                    timeMap.put("orderCount", 0);
                    timeMap.put("servicecharge", 0);
                    timeMap.put("electricity", 0);
                    charMap.add(timeMap);
                }
            }
          return R.ok(charMap);
        }else if (statisticsQueryDto.getDayType()==2){
            // 假设 chargingOrderService.getDateType() 返回的是按天的数据
            List<Map<String, Object>> charMap1 = chargingOrderService.getDateType(siteIds, statisticsQueryDto);
 
            // 解析 startTime 和 endTime 为 LocalDate
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
 
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
 
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
 
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("servicecharge", 0);
                    dateMap.put("electricity", 0);
                    dateRangeStatistics.add(dateMap);
                }
 
                // 移动到下一天
                startDate = startDate.plusDays(1);
            }
 
//            return dateRangeStatistics;
            return R.ok(dateRangeStatistics);
        }else if (statisticsQueryDto.getDayType()==3){
            List<Map<String,Object>> charMap1 =  chargingOrderService.getMonthType(siteIds,statisticsQueryDto);
            // 解析 startTime 和 endTime 为 LocalDate
            LocalDate startDate = statisticsQueryDto.getStartTime();
            LocalDate endDate = statisticsQueryDto.getEndTime();
 
            List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
 
            // 遍历日期范围
            while (!startDate.isAfter(endDate)) {
                String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                Map<String, Object> dailyStats = findMapWithDateValue(charMap1, formattedDate);
 
                if (dailyStats != null) {
                    dateRangeStatistics.add(dailyStats);
                } else {
                    Map<String, Object> dateMap = new HashMap<>();
                    dateMap.put("time", formattedDate);
                    dateMap.put("electrovalence", 0);
                    dateMap.put("orderCount", 0);
                    dateMap.put("servicecharge", 0);
                    dateMap.put("electricity", 0);
                    dateRangeStatistics.add(dateMap);
                }
 
                // 移动到下一天
                startDate = startDate.plusMonths(1);
            }
            return R.ok(dateRangeStatistics);
 
        }
        return R.ok();
 
 
    }
 
    private static Map<String, Object> findMapWithTimeValue(List<Map<String, Object>> charMap1,String timeValue) {
        for (Map<String, Object> map : charMap1) {
            if (map.containsKey("time") && map.get("time").equals(timeValue)) {
                return map;
            }
        }
        return null; // 如果没有找到,返回 null
    }
 
    private Map<String, Object> findMapWithDateValue(List<Map<String, Object>> list, String date) {
        for (Map<String, Object> map : list) {
            if (date.equals(map.get("time"))) {
                return map;
            }
        }
        return null;
    }
 
 
 
 
    @ResponseBody
    @PostMapping(value = "/work/use")
    @ApiOperation(value = "利用率", tags = {"管理后台-工作台"})
    public R workUse(@RequestBody ChargingDetailQueryDto statisticsQueryDto) {
        List<Integer> siteIds = new ArrayList<>();
        if (statisticsQueryDto.getSiteId() == null) {
            Long userId = SecurityUtils.getUserId();
            //获取当前登录的siteIds
            List<GetSiteListDTO> data = siteClient.getSiteListByUserId(userId).getData();
            for (GetSiteListDTO datum : data) {
                siteIds.add(datum.getId());
            }
        } else {
            siteIds.add(statisticsQueryDto.getSiteId());
        }
       List<Map<String,Object>>   capMap  =   chargingOrderService.getchargingCapacity(siteIds,statisticsQueryDto);
        List<TChargingPile> chargingPiles = chargingPileClient.getChargingPileBySiteIds(siteIds).getData();
        //获取chargingPiles的ratedPower的总和再乘以chargingPiles的数量再乘以24
        BigDecimal totalRatedPower = chargingPiles.stream().map(TChargingPile::getRatedPower).reduce(BigDecimal.ZERO, BigDecimal::add).multiply(new BigDecimal(chargingPiles.size())).multiply(new BigDecimal(24));
 
        //将capMap的chargingCapacity除以totalRatedPower保留两位数
        capMap.forEach(map -> {
            BigDecimal chargingCapacity = (BigDecimal) map.get("chargingCapacity");
            BigDecimal result = chargingCapacity.divide(totalRatedPower, 4, RoundingMode.HALF_UP);
            BigDecimal multiply = result.multiply(new BigDecimal(100));
            map.put("chargingCapacity", multiply);
        });
 
 
 
        //
        // 解析 startTime 和 endTime 为 LocalDate
        LocalDate startDate = statisticsQueryDto.getStartTime();
        LocalDate endDate = statisticsQueryDto.getEndTime();
 
        List<Map<String, Object>> dateRangeStatistics = new ArrayList<>();
 
        // 遍历日期范围
        while (!startDate.isAfter(endDate)) {
            String formattedDate = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Map<String, Object> dailyStats = findMapWithDateValue(capMap, formattedDate);
 
            if (dailyStats != null) {
                dateRangeStatistics.add(dailyStats);
            } else {
                Map<String, Object> dateMap = new HashMap<>();
                dateMap.put("time", formattedDate);
                dateMap.put("chargingCapacity", 0);
                dateRangeStatistics.add(dateMap);
            }
 
            // 移动到下一天
            startDate = startDate.plusDays(1);
        }
        return R.ok(dateRangeStatistics);
 
 
    }
 
    
    @ResponseBody
    @GetMapping(value = "/work/shopOrder")
    @ApiOperation(value = "购物订单统计", tags = {"管理后台-工作台"})
    public R shopOrder() {
        Long count = shoppingOrderService.lambdaQuery().eq(TShoppingOrder::getStatus, 1).count();
        Long count1 = shoppingOrderService.lambdaQuery().eq(TShoppingOrder::getStatus, 2).count();
        List<Long> counts = new ArrayList<>();
        counts.add(count);
        counts.add(count1);
        return R.ok(counts);
    }
 
    @ResponseBody
    @GetMapping(value = "/work/invoice")
    @ApiOperation(value = "开票统计", tags = {"管理后台-工作台"})
    public R invoice() {
        Long count = invoiceService.lambdaQuery().eq(TOrderInvoice::getStatus, 1).count();
        Long count1 = invoiceService.lambdaQuery().eq(TOrderInvoice::getStatus, 3).count();
        List<Long> counts = new ArrayList<>();
        counts.add(count);
        counts.add(count1);
        return R.ok(counts);
    }
 
    @ResponseBody
    @GetMapping(value = "/work/users/count")
    @ApiOperation(value = "用户数量", tags = {"管理后台-工作台"})
    public R usersCount() {
       List<Map<String,Object>>  userMap  =    chargingOrderService.countAllUserData();
            return R.ok(userMap);
 
    }
 
    @GetMapping(value = "/getGunIdsByUserId")
    @ApiOperation(value = "查询当前用户正在充电中的枪id集合", tags = {"小程序-首页-用户充电订单信息"})
    public R<List<Integer>> getGunIdsByUserId() {
        Long userId = tokenService.getLoginUserApplet().getUserId();
        List<TChargingOrder> list = chargingOrderService.list(Wrappers.lambdaQuery(TChargingOrder.class)
                .eq(TChargingOrder::getAppUserId, userId)
                .eq(TChargingOrder::getStatus, 3));
        List<Integer> gunIds = list.stream().map(TChargingOrder::getChargingGunId).collect(Collectors.toList());
        return R.ok(gunIds);
    }
 
 
 
    private static List<TChargingOrder> getSampleData() {
        // 这里可以替换为实际查询逻辑
        List<TChargingOrder> list = new ArrayList<>();
        // 示例数据
        for (int i = 0; i < 24; i++) {
            TChargingOrder order = new TChargingOrder();
            order.setStartTime(LocalDateTime.now().minusHours(23 - i));
            order.setOrderAmount(BigDecimal.valueOf(i + 1));
            list.add(order);
        }
        return list;
    }
 
    private static List<Map<String, BigDecimal>> processData(List<TChargingOrder> list) {
        Map<LocalDateTime, BigDecimal> hourlySum = new HashMap<>();
 
        // 按每个小时分组并求和
        for (TChargingOrder order : list) {
            LocalDateTime hour = order.getStartTime().truncatedTo(ChronoUnit.HOURS);
            BigDecimal amount = order.getOrderAmount();
            hourlySum.merge(hour, amount, BigDecimal::add);
        }
 
        // 创建结果列表
        List<Map<String, BigDecimal>> resultList = new ArrayList<>();
        for (int i = 1; i <= 23; i++) {
            LocalDateTime keyHour = LocalDateTime.now().withHour(i);
            BigDecimal sum = BigDecimal.ZERO;
 
            // 计算键之后的一小时的数据之和
            for (int j = i + 1; j <= 23; j++) {
                LocalDateTime nextHour = LocalDateTime.now().withHour(j);
                sum = sum.add(hourlySum.getOrDefault(nextHour, BigDecimal.ZERO));
            }
 
            Map<String, BigDecimal> entry = new HashMap<>();
            entry.put(String.valueOf(i), sum);
            resultList.add(entry);
        }
 
        return resultList;
    }
 
 
    /**
     * 硬件充电结束后的处理逻辑
     * @param code
     */
    @PostMapping("/endCharge")
    public void endCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电桩自动结束充电-------------------");
        chargingOrderService.endCharge(code, 2);
    }
 
    /**
     * 硬件异常结束充电后的处理逻辑
     * @param code
     */
    @PostMapping("/excelEndCharge")
    public void excelEndCharge(@RequestParam("code") String code){
        log.error(code + ":-------------------充电异常,停止充电-------------------");
        chargingOrderService.excelEndCharge(code);
    }
 
 
    /**
     * 根据车牌号和时间查询有效的充电数据
     * @param query
     * @return
     */
    @PostMapping("/getChargingOrderByLicensePlate")
    public R<TChargingOrder> getChargingOrderByLicensePlate(@RequestBody GetChargingOrderByLicensePlate query){
        TChargingOrder chargingOrder = chargingOrderService.getChargingOrderByLicensePlate(query);
        return R.ok(chargingOrder);
    }
    /**
     * 修改充电订单
     * @param chargingOrder
     * @return
     */
    @PostMapping("/updateChargingOrder")
    public R<String> updateChargingOrder(@RequestBody TChargingOrder chargingOrder){
        chargingOrderService.updateById(chargingOrder);
        return R.ok();
    }
    
    
    @ResponseBody
    @GetMapping(value = "/getEndOfChargePageInfo/{id}")
    @ApiOperation(value = "获取充电结束页面数据", tags = {"小程序-扫一扫"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单id", required = true)
    })
    public AjaxResult<EndOfChargePageInfo> getEndOfChargePageInfo(@PathVariable("id") String id){
        EndOfChargePageInfo endOfChargePageInfo = chargingOrderService.getEndOfChargePageInfo(id);
        return AjaxResult.success(endOfChargePageInfo);
    }
}