“mitao”
2026-05-08 c5a4bbfbe2e7858446cc54c7b474af0d1380944b
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
package com.ruoyi.order.util.task;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.ruoyi.account.api.feignClient.AppCouponClient;
import com.ruoyi.account.api.feignClient.AppUserClient;
import com.ruoyi.account.api.feignClient.AppUserIntegralChangeClient;
import com.ruoyi.account.api.model.TAppCoupon;
import com.ruoyi.account.api.model.TAppUser;
import com.ruoyi.account.api.model.TAppUserIntegralChange;
import com.ruoyi.chargingPile.api.feignClient.ChargingGunClient;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.chargingPile.api.model.TChargingGun;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.integration.api.feignClient.ChargingMessageClient;
import com.ruoyi.integration.api.feignClient.ChengDuJianGuanClient;
import com.ruoyi.integration.api.feignClient.TCECClient;
import com.ruoyi.integration.api.model.TransactionRecord;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringData;
import com.ruoyi.integration.api.vo.ChargingOrderVo;
import com.ruoyi.integration.api.vo.NotificationConnectorChargeStatusVo;
import com.ruoyi.order.api.model.*;
import com.ruoyi.order.api.vo.TransactionRecordMessageVO;
import com.ruoyi.order.service.*;
import com.ruoyi.order.util.mongodb.service.TransactionRecordService;
import com.ruoyi.order.util.mongodb.service.UploadRealTimeMonitoringDataService;
import com.ruoyi.other.api.domain.TCoupon;
import com.ruoyi.other.api.domain.TIntegralRule;
import com.ruoyi.other.api.domain.TVip;
import com.ruoyi.other.api.dto.ExchangeCodeConsumeDTO;
import com.ruoyi.other.api.feignClient.IntegralRuleClient;
import com.ruoyi.other.api.feignClient.OtherClient;
import com.ruoyi.other.api.feignClient.VipClient;
import com.ruoyi.other.api.vo.ExchangeCodeConsumeResultVO;
import com.ruoyi.payment.api.feignClient.AliPaymentClient;
import com.ruoyi.payment.api.feignClient.H5AliPaymentClient;
import com.ruoyi.payment.api.feignClient.WxPaymentClient;
import com.ruoyi.payment.api.model.RefundReq;
import com.ruoyi.payment.api.model.RefundResp;
import com.ruoyi.payment.api.model.WxPaymentRefundModel;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * @author zhibing.pu
 * @date 2023/7/11 8:39
 */
@Slf4j
@Component
public class TaskUtil implements ApplicationListener<WebServerInitializedEvent> {
 
    @Resource
    private TChargingBillService chargingBillService;
 
    @Resource
    private ITChargingSettlementBillService chargingSettlementBillService;
 
    @Resource
    private ITAccountSettlementStatementService accountSettlementStatementService;
    @Resource
    private SiteClient siteClient;
    @Resource
    private TChargingOrderService chargingOrderService;
    
    @Resource
    private TChargingOrderRefundService chargingOrderRefundService;
    
    @Resource
    private UploadRealTimeMonitoringDataService uploadRealTimeMonitoringDataService;
    
    @Resource
    private TransactionRecordService transactionRecordService;
    
    @Resource
    private ChargingMessageClient chargingMessageClient;
    
    private Integer port = null;
    @Resource
    private AccountingStrategyDetailOrderService accountingStrategyDetailOrderService;
 
    @Resource
    private TChargingOrderAccountingStrategyService chargingOrderAccountingStrategyService;
 
    @Resource
    private AppCouponClient appCouponClient;
 
    @Resource
    private TCECClient tcecClient;
 
    @Resource
    private VipClient vipClient;
 
    @Resource
    private ChargingGunClient chargingGunClient;
 
    @Resource
    private IntegralRuleClient integralRuleClient;
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private AppUserIntegralChangeClient appUserIntegralChangeClient;
 
    @Resource
    private OtherClient otherClient;
 
    @Resource
    private WxPaymentClient wxPaymentClient;
 
    @Resource
    private AliPaymentClient aliPaymentClient;
    @Resource
    private H5AliPaymentClient h5AliPaymentClient;
 
    @Resource
    private ITChargingOrderSummaryDataService chargingOrderSummaryDataService;
 
    @Resource
    private ChengDuJianGuanClient chengDuJianGuanClient;
 
    @Resource
    private RedissonClient redissonClient;
 
 
 
    private boolean isBalancePayMode(Integer payMethod) {
        return payMethod != null && (payMethod == 1 || payMethod == 2);
    }
 
    private BigDecimal money(BigDecimal amount) {
        return amount == null ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP) : amount.setScale(2, RoundingMode.HALF_UP);
    }
 
    private void recordBalanceRefund(TChargingOrder order, BigDecimal refundAmount, String refundNo) {
        if (order == null || order.getAppUserId() == null || order.getId() == null
                || refundAmount == null || refundAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        ExchangeCodeConsumeDTO refundDTO = new ExchangeCodeConsumeDTO();
        refundDTO.setUserId(order.getAppUserId());
        refundDTO.setOrderId(order.getId());
        refundDTO.setAmount(refundAmount);
        refundDTO.setRefundNo(refundNo);
        R<ExchangeCodeConsumeResultVO> result = otherClient.refundExchangeCodeBalance(refundDTO);
        if (result == null || result.getCode() != 200) {
            throw new RuntimeException("退还兑换码余额失败");
        }
    }
 
    @Scheduled(fixedRate = 1000 * 60)
    public void taskOneMinutes() {
        if(null != port && port == 5400){
            List<TChargingOrder> upStatusChargingOrder = chargingOrderService.findUpStatusChargingOrder();
            log.info("定时任务执行,查询需要手动修改状态的订单数量:{}", upStatusChargingOrder.size());
            for (TChargingOrder order : upStatusChargingOrder) {
                if(2 == order.getStatus()){
                    order.setStatus(-1);
                }else{
                    order.setStatus(5);
                }
                chargingOrderService.updateById(order);
            }
        }
    }
 
 
    //十分钟循环执行的定时任务
    @Scheduled(fixedRate = 1000 * 60 * 10)
    public void taskTenMinutes() {
        if(null != port && port == 5400){
            List<TChargingOrder> failedStartupOrder = chargingOrderService.findFailedStartupOrder();
            log.info("定时任务执行,查询到启动失败的订单数量:{}", failedStartupOrder.size());
            for (TChargingOrder order : failedStartupOrder) {
                log.info("定时任务执行,查询到启动失败的订单:{}", order.getCode());
                //查询是否有充电信息
                List<UploadRealTimeMonitoringData> dataByOrderCode = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode());
                log.info("充电实时数据:{}", dataByOrderCode.size());
                //没有充电数据,则执行退款
                if(null == dataByOrderCode || dataByOrderCode.isEmpty()){
                    log.info("定时任务执行,查询到启动失败的订单,执行退款:{}", order.getCode());
                    if(1 == order.getOrderSource()){
                        chargingOrderService.refund(order.getCode());
                        int num = 0;
                        while (true){
                            TChargingOrderRefund one = chargingOrderRefundService.getOne(new LambdaQueryWrapper<TChargingOrderRefund>().eq(TChargingOrderRefund::getChargingOrderId, order.getId()));
                            if(null != one && 2 == one.getRefundStatus()){
                                order.setStatus(-1);
                                chargingOrderService.updateById(order);
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            num++;
                            if(num > 30){
                                break;
                            }
                        }
                    }else{
                        order.setStatus(-1);
                        chargingOrderService.updateById(order);
                    }
                }
            }
 
            //处理退款中的数据
            List<TChargingOrder> stoppedOrder = chargingOrderService.findStoppedOrder();
            log.info("定时任务执行,查询到停止中的订单数量:{}", stoppedOrder.size());
            for (TChargingOrder order : stoppedOrder) {
                log.info("定时任务执行,查询到停止中的订单:{}", order.getCode());
                TransactionRecord one = transactionRecordService.findOne(order.getCode());
                if(null != one){
                    log.info("定时任务执行,查询到停止中的订单账单数据:{}", JSON.toJSONString(one));
                    if(null == order.getStartTime()){
                        List<UploadRealTimeMonitoringData> dataList = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if(dataList.isEmpty()){
                            order.setStartTime(LocalDateTime.parse(one.getStart_time(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS").withZone(ZoneId.systemDefault())));
                        }else{
                            order.setStartTime(LocalDateTime.parse(sdf.format(dataList.get(dataList.size() - 1).getCreate_time()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault())));
                        }
                    }
                    if(null == order.getEndTime()){
                        order.setEndTime(LocalDateTime.parse(one.getEnd_time(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS").withZone(ZoneId.systemDefault())));
                    }
                    chargingOrderService.updateById(order);
                    TransactionRecordMessageVO vo = new TransactionRecordMessageVO();
                    BeanUtils.copyProperties(one, vo);
                    R r = chargingOrderService.endChargeBillingCharge(vo);
                    log.info("定时任务执行,停止中的订单处理结果:{}", JSON.toJSONString(r));
                }else{
                    endOrder(order);
                }
            }
 
 
            //处理状态为充电中,但硬件已完成的订单
            List<TChargingOrder> chargingOrder = chargingOrderService.findChargingOrder();
            log.info("定时任务执行,查询到充电中的订单数量:{}", chargingOrder.size());
            for (TChargingOrder order : chargingOrder) {
                log.info("定时任务执行,查询到充电中的订单:{}", order.getCode());
                TransactionRecord one = transactionRecordService.findOne(order.getCode());
                if(null != one && StringUtils.isNotEmpty(one.getResult())){
                    log.info("定时任务执行,查询到充电中的订单账单数据:{}", JSON.toJSONString(one));
                    if(null == order.getStartTime()){
                        List<UploadRealTimeMonitoringData> dataList = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if(dataList.isEmpty()){
                            order.setStartTime(LocalDateTime.parse(one.getStart_time(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS").withZone(ZoneId.systemDefault())));
                        }else{
                            order.setStartTime(LocalDateTime.parse(sdf.format(dataList.get(dataList.size() - 1).getCreate_time()), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault())));
                        }
                    }
                    if(null == order.getEndTime()){
                        order.setEndTime(LocalDateTime.parse(one.getEnd_time(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS").withZone(ZoneId.systemDefault())));
                    }
                    chargingOrderService.updateById(order);
                    TransactionRecordMessageVO vo = new TransactionRecordMessageVO();
                    BeanUtils.copyProperties(one, vo);
                    R r = chargingOrderService.endChargeBillingCharge(vo);
                    log.info("定时任务执行,充电中的订单处理结果:{}", JSON.toJSONString(r));
                }else{
                    //判断充电流水超过15分钟没有更新,则判定为充电结束
                    List<UploadRealTimeMonitoringData> dataList = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode());
                    if(!dataList.isEmpty()){
                        UploadRealTimeMonitoringData uploadRealTimeMonitoringData = dataList.get(0);
                        Date createTime = uploadRealTimeMonitoringData.getCreate_time();
                        if(System.currentTimeMillis() - createTime.getTime() - (8 * 60 * 60 * 1000) > 1000 * 60 * 30){
                            endOrder(order);
                        }
                    }
                }
            }
 
            //处理还未退款,但是订单状态已结束的数据
            List<TChargingOrder> endChargingOrder = chargingOrderService.findEndChargingOrder();
            log.info("定时任务执行,查询到已结束未退款的订单数量:{}", endChargingOrder.size());
            for (TChargingOrder order : endChargingOrder) {
                if(-1 == order.getStatus()){
                    order.setStatus(2);
                }
                if(5 == order.getStatus()){
                    order.setStatus(4);
                }
                chargingOrderService.updateById(order);
            }
 
        }
    }
 
 
    //定时任务添加结算账单汇总数据
    @Scheduled(cron = "0 30 0 * * ?")
    public void taskMonth() {
        if(null != port && port == 5400){
            //添加充电算账单汇总数据
            addChargingSettlementBill();
            //添加账户结算账单数据
            addAccountSettlementStatement();
        }
    }
 
    // 每个月最后一天23点执行的定时任务
    @Scheduled(cron = "0 0 23 * * ?")
    public void taskLastDay() {
        if(null != port && port == 5400){
            try {
                int dayOfMonth = LocalDate.now().getDayOfMonth();
                int lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
                //当月最后一天
                if(dayOfMonth == lastDayOfMonth){
                    //修改充电结算账单为已出账
                    chargingSettlementBillService.update(new UpdateWrapper<TChargingSettlementBill>().set("status", 2).set("create_time", LocalDateTime.now()).eq("status", 1));
                    //修改账户结算账单为已出账
                    accountSettlementStatementService.update(new UpdateWrapper<TAccountSettlementStatement>().set("status", 2).set("create_time", LocalDateTime.now()).eq("status", 1));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
 
 
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        port = event.getWebServer().getPort();
        System.out.println("端口号:" + port);
    }
 
 
 
    @Transactional
    public void endOrder(TChargingOrder order){
        RLock lock = redissonClient.getLock("endOrder:" + order.getCode());
        try {
            boolean tryLock = lock.tryLock(60, 60, TimeUnit.SECONDS);
            if(tryLock){
                List<UploadRealTimeMonitoringData> dataList = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode());
                if(!dataList.isEmpty()){
                    //获取当前订单的计费规则,然后分段计算总的度数和充电金额
                    List<AccountingStrategyDetailOrder> detailOrders = accountingStrategyDetailOrderService.list(new LambdaQueryWrapper<AccountingStrategyDetailOrder>()
                            .eq(AccountingStrategyDetailOrder::getChargingOrderId, order.getId()).last(" order by start_time"));
                    detailOrders.get(detailOrders.size() - 1).setEndTime("23:59");
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                    //开始解析每个时段的充电度数
                    BigDecimal decimal = BigDecimal.ZERO;
                    //如果使用优惠券需要判断优惠券是否满足使用条件
                    //退款金额=优惠券金额+剩余充电金额
                    BigDecimal periodElectricPrice_total = BigDecimal.ZERO;
                    BigDecimal periodServicePrice_total = BigDecimal.ZERO;
                    BigDecimal vipDiscountAmount_total = BigDecimal.ZERO;
                    BigDecimal serviceCharge_total = BigDecimal.ZERO;
                    BigDecimal total = BigDecimal.ZERO;
                    //判断实时数据是否跨天
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    Date end_time = dataList.get(0).getCreate_time();
                    String end = sdf2.format(end_time);
                    Date start_time = dataList.get(dataList.size() - 1).getCreate_time();
                    String start = sdf2.format(start_time);
                    if(!end.equals(start)){
                        List<AccountingStrategyDetailOrder> list = detailOrders.stream().map(s->{
                            AccountingStrategyDetailOrder accountingStrategyDetailOrder = new AccountingStrategyDetailOrder();
                            BeanUtils.copyProperties(s, accountingStrategyDetailOrder);
                            return accountingStrategyDetailOrder;
                        }).collect(Collectors.toList());
                        for (AccountingStrategyDetailOrder detailOrder : detailOrders) {
                            detailOrder.setStartTime(start + " " + detailOrder.getStartTime());
                            detailOrder.setEndTime(start + " " + detailOrder.getEndTime());
                        }
                        for (AccountingStrategyDetailOrder detailOrder : list) {
                            detailOrder.setStartTime(end + " " + detailOrder.getStartTime());
                            detailOrder.setEndTime(end + " " + detailOrder.getEndTime());
                        }
                        detailOrders.addAll(list);
                    }else{
                        for (AccountingStrategyDetailOrder detailOrder : detailOrders) {
                            detailOrder.setStartTime(start + " " + detailOrder.getStartTime());
                            detailOrder.setEndTime(start + " " + detailOrder.getEndTime());
                        }
                    }
 
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmm");
                    List<TChargingOrderAccountingStrategy> list = new ArrayList<>();
                    for (AccountingStrategyDetailOrder detailOrder : detailOrders) {
                        long startTime = Long.parseLong(detailOrder.getStartTime().replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""));
                        long endTime = Long.parseLong(detailOrder.getEndTime().replaceAll("-", "").replaceAll(" ", "").replaceAll(":", ""));
                        List<UploadRealTimeMonitoringData> collect = dataList.stream().filter(s -> Long.parseLong(sdf1.format(s.getCreate_time())) > startTime && Long.parseLong(sdf1.format(s.getCreate_time())) <= endTime).collect(Collectors.toList());
 
                        if(!collect.isEmpty()){
                            //升序排序
                            collect.sort(new Comparator<UploadRealTimeMonitoringData>(){
                                @Override
                                public int compare(UploadRealTimeMonitoringData o1, UploadRealTimeMonitoringData o2) {
                                    return o1.getCharging_degree().compareTo(o2.getCharging_degree());
                                }
                            });
                            UploadRealTimeMonitoringData uploadRealTimeMonitoringData = collect.get(collect.size() - 1);
                            BigDecimal chargingDegree = uploadRealTimeMonitoringData.getCharging_degree();
                            BigDecimal subtract = chargingDegree.subtract(decimal);
                            decimal = chargingDegree;
                            if(subtract.compareTo(BigDecimal.ZERO) > 0){
                                //组装充电明细数据
                                TChargingOrderAccountingStrategy chargingOrderAccountingStrategy = new TChargingOrderAccountingStrategy();
                                chargingOrderAccountingStrategy.setChargingOrderId(order.getId());
                                chargingOrderAccountingStrategy.setAccountingStrategyDetailId(detailOrder.getId());
                                chargingOrderAccountingStrategy.setType(detailOrder.getType());
                                chargingOrderAccountingStrategy.setElectrovalence(detailOrder.getElectrovalence());
                                chargingOrderAccountingStrategy.setServiceCharge(detailOrder.getServiceCharge());
                                chargingOrderAccountingStrategy.setCostServiceCharge(detailOrder.getCostServiceCharge());
                                chargingOrderAccountingStrategy.setChargingCapacity(subtract);
                                chargingOrderAccountingStrategy.setCreateTime(LocalDateTime.now());
 
                                if (list.size() == 0) {
                                    String time = sdf.format(collect.get(0).getCreate_time());
                                    chargingOrderAccountingStrategy.setStartTime(time);
                                } else {
                                    chargingOrderAccountingStrategy.setStartTime(detailOrder.getStartTime().split(" ")[1]);
                                }
                                chargingOrderAccountingStrategy.setEndTime(detailOrder.getEndTime().split(" ")[1]);
 
                                //已充电总度数
                                BigDecimal electrovalenc = detailOrder.getElectrovalence().multiply(subtract);
                                BigDecimal originalServicePrice = detailOrder.getServiceCharge().multiply(subtract);
                                BigDecimal serviceCharge = originalServicePrice;
                                BigDecimal vipDiscountAmount = BigDecimal.ZERO;
                                //计算优惠金额
                                if (null != order.getVipDiscount()) {
                                    //0.58折
                                    vipDiscountAmount = serviceCharge.multiply(new BigDecimal(1).subtract(order.getVipDiscount()));
                                    serviceCharge = serviceCharge.multiply(order.getVipDiscount());
                                }
                                chargingOrderAccountingStrategy.setPeriodElectricPrice(electrovalenc.setScale(4, RoundingMode.HALF_EVEN));
                                chargingOrderAccountingStrategy.setPeriodServicePrice(serviceCharge.setScale(4, RoundingMode.HALF_EVEN));
                                chargingOrderAccountingStrategy.setPeriodOriginalServicePrice(originalServicePrice.setScale(4, RoundingMode.HALF_EVEN));
                                chargingOrderAccountingStrategy.setVipDiscountAmount(vipDiscountAmount.setScale(4, RoundingMode.HALF_EVEN));
                                chargingOrderAccountingStrategy.setCreateTime(LocalDateTime.now());
                                list.add(chargingOrderAccountingStrategy);
                                //电费
                                periodElectricPrice_total = periodElectricPrice_total.add(electrovalenc);
                                //服务费(含折扣)
                                serviceCharge_total = serviceCharge_total.add(serviceCharge);
                                //服务费(不含折扣)
                                periodServicePrice_total = periodServicePrice_total.add(originalServicePrice);
                                //会员折扣优惠金额
                                vipDiscountAmount_total = vipDiscountAmount_total.add(vipDiscountAmount);
                                //原始总金额(不含折扣)
                                total = total.add(electrovalenc.add(originalServicePrice));
                            }
                        }
 
                    }
                    list.get(list.size() - 1).setEndTime(sdf.format(dataList.get(0).getCreate_time()));
                    chargingOrderAccountingStrategyService.saveBatch(list);
 
                    BigDecimal orderAmount = BigDecimal.valueOf(total.doubleValue());
                    //原金额
                    BigDecimal rechargeAmount = order.getRechargeAmount();
                    //支付金额
                    BigDecimal payAmount = periodElectricPrice_total.add(serviceCharge_total);
                    //退款金额=充值金额-实际支付金额
                    BigDecimal refundAmount = rechargeAmount.subtract(payAmount);
 
                    UploadRealTimeMonitoringData uploadRealTimeMonitoringData = uploadRealTimeMonitoringDataService.getLastDataById(order.getCode());
                    if (null != uploadRealTimeMonitoringData && null == order.getEndMode()) {
                        Integer soc = uploadRealTimeMonitoringData.getSoc();
                        if (soc >= 98) {
                            order.setEndMode(2);
                        } else if (null != order.getResidualAmount() && order.getResidualAmount().compareTo(new BigDecimal(1)) <= 0) {
                            order.setEndMode(3);
                        } else {
                            order.setEndMode(1);
                        }
                    }
 
                    order.setResidualAmount(rechargeAmount.subtract(total).setScale(2, RoundingMode.HALF_EVEN));
                    order.setStartTime(list.get(0).getCreateTime());
                    order.setEndTime(list.get(list.size() - 1).getCreateTime());
                    order.setStatus(5);
                    order.setOrderAmount(orderAmount.setScale(2, RoundingMode.HALF_EVEN));
                    order.setElectrovalence(periodElectricPrice_total.setScale(2, RoundingMode.HALF_EVEN));
                    order.setChargingCapacity(list.get(list.size() - 1).getChargingCapacity());
                    order.setElectricity(list.get(list.size() - 1).getChargingCapacity());
                    order.setVipDiscountAmount(vipDiscountAmount_total);
                    if (vipDiscountAmount_total.compareTo(BigDecimal.ZERO) == 0) {
                        order.setVipDiscount(BigDecimal.valueOf(1));
                    }
 
                    //计算优惠券
                    BigDecimal couponDiscount = BigDecimal.ZERO;
                    if (null != order.getAppCouponId()) {
                        //判断实际充电金额是否满足优惠券使用条件,如果不满足则不适用优惠券。
                        TAppCoupon appCoupon = appCouponClient.getAppCouponById(order.getAppCouponId()).getData();
                        String couponJson = appCoupon.getCouponJson();
                        TCoupon tCoupon = com.alibaba.fastjson2.JSON.parseObject(couponJson, TCoupon.class);
                        Integer preferentialMode = tCoupon.getPreferentialMode();
                        if (1 == preferentialMode) {
                            //满减
                            if (payAmount.compareTo(tCoupon.getMeetTheConditions()) >= 0) {
                                BigDecimal couponDiscountAmount = tCoupon.getDiscountAmount();
                                //如果优惠金额大于服务费金额,以服务费作为最大限制
                                if (serviceCharge_total.compareTo(couponDiscountAmount) < 0) {
                                    couponDiscount = serviceCharge_total;
                                    serviceCharge_total = BigDecimal.ZERO;
                                } else {
                                    couponDiscount = couponDiscountAmount;
                                }
                                appCoupon.setStatus(2);
                                appCouponClient.updateAppCoupon(appCoupon);
                            } else {
                                appCouponClient.refund(order.getAppCouponId().toString());
                                order.setAppCouponId(null);
                                order.setCouponDiscountAmount(BigDecimal.ZERO);
                            }
                        }
                        if (2 == preferentialMode) {
                            //抵扣
                            if (payAmount.compareTo(tCoupon.getMeetTheConditions()) >= 0) {
                                //折扣金额
                                BigDecimal divide = payAmount.multiply(new BigDecimal(10).subtract(tCoupon.getDiscount())).divide(new BigDecimal(10));
                                divide = divide.compareTo(tCoupon.getMaximumDiscountAmount()) > 0 ? tCoupon.getMaximumDiscountAmount() : divide;
                                //如果优惠金额大于服务费金额,以服务费作为最大限制
                                if (serviceCharge_total.compareTo(divide) < 0) {
                                    couponDiscount = serviceCharge_total;
                                    serviceCharge_total = BigDecimal.ZERO;
                                } else {
                                    couponDiscount = divide;
                                }
 
                                appCoupon.setStatus(2);
                                appCouponClient.updateAppCoupon(appCoupon);
                            } else {
                                order.setAppCouponId(null);
                                order.setCouponDiscountAmount(BigDecimal.ZERO);
                                appCouponClient.refund(order.getAppCouponId().toString());
                            }
                        }
                    }
                    //优惠券优惠金额
                    couponDiscount = couponDiscount.setScale(4, RoundingMode.HALF_EVEN);
                    //退款金额+优惠券
                    refundAmount = refundAmount.add(couponDiscount);
                    //实际支付金额-优惠券
                    payAmount = payAmount.subtract(couponDiscount);
                    if (serviceCharge_total.compareTo(BigDecimal.ZERO) > 0) {
                        serviceCharge_total = serviceCharge_total.subtract(couponDiscount);
                    }
                    order.setCouponDiscountAmount(couponDiscount.setScale(2, RoundingMode.HALF_EVEN));
                    order.setServiceCharge(serviceCharge_total.setScale(2, RoundingMode.HALF_EVEN));
                    order.setPaymentAmount(payAmount.setScale(2, RoundingMode.HALF_EVEN));
                    order.setRefundAmount(refundAmount.setScale(2, RoundingMode.HALF_EVEN));
                    order.setRefundStatus(1);
                    UploadRealTimeMonitoringData asc = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode(), "asc");
                    UploadRealTimeMonitoringData desc = uploadRealTimeMonitoringDataService.getDataByOrderCode(order.getCode(), "desc");
                    if(null != asc){
                        order.setStartSoc(new BigDecimal(asc.getSoc()));
                    }
                    if(null != desc){
                        order.setEndSoc(new BigDecimal(desc.getSoc()));
                    }
                    chargingOrderService.updateById(order);
 
                    order = chargingOrderService.getById(order.getId());
                    Site site = siteClient.getSiteByIds(Arrays.asList(order.getSiteId())).getData().get(0);
                    //推送三方平台
                    if (2 == order.getOrderSource() && 1 == site.getIsOpenSynchronization()) {
                        TChargingOrder finalChargingOrder = order;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                tcecClient.notificationEquipChargeStatus(finalChargingOrder.getStartChargeSeq(), finalChargingOrder.getOperatorId());
                                tcecClient.notificationStopChargeResult(finalChargingOrder.getStartChargeSeq(), finalChargingOrder.getChargingGunId().toString(),
                                        finalChargingOrder.getOperatorId());
                                tcecClient.notificationChargeOrderInfo(finalChargingOrder.getStartChargeSeq(), finalChargingOrder.getOperatorId());
                            }
                        }).start();
                    }
 
                    //开始将优惠券优惠的金额添加到明细中
                    BigDecimal couponDiscountAmount = order.getCouponDiscountAmount();
                    if (null != couponDiscountAmount && couponDiscountAmount.compareTo(BigDecimal.ZERO) > 0) {
                        List<TChargingOrderAccountingStrategy> list1 = chargingOrderAccountingStrategyService.list(new LambdaQueryWrapper<TChargingOrderAccountingStrategy>().eq(TChargingOrderAccountingStrategy::getChargingOrderId, order.getId()));
                        BigDecimal reduce = list1.stream().map(TChargingOrderAccountingStrategy::getPeriodServicePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                        for (TChargingOrderAccountingStrategy chargingOrderAccountingStrategy : list1) {
                            BigDecimal periodServicePrice = chargingOrderAccountingStrategy.getPeriodServicePrice();
                            BigDecimal multiply = couponDiscountAmount.multiply(periodServicePrice.divide(reduce, new MathContext(4, RoundingMode.HALF_EVEN)));
                            periodServicePrice = periodServicePrice.subtract(multiply);
                            chargingOrderAccountingStrategy.setPeriodServicePrice(periodServicePrice.setScale(2, RoundingMode.HALF_EVEN));
                            chargingOrderAccountingStrategy.setCouponDiscountAmount(multiply.setScale(2, RoundingMode.HALF_EVEN));
                        }
                        chargingOrderAccountingStrategyService.updateBatchById(list1);
                    }
 
                    // 将枪状态重置为空闲
                    TChargingGun chargingGun = new TChargingGun();
                    chargingGun.setId(order.getChargingGunId());
                    chargingGun.setStatus(2);
                    chargingGun.setChargingPower(BigDecimal.ZERO);
                    chargingGunClient.updateChargingGunById(chargingGun);
                    chargingGun = chargingGunClient.getChargingGunById(order.getChargingGunId()).getData();
                    //推送状态给三方平台
                    if (2 == order.getOrderSource() && 1 == site.getIsOpenSynchronization()) {
                        tcecClient.pushChargingGunStatus(chargingGun.getFullNumber(), 2);
                    }
                    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
                    TChargingOrder finalOrder = order;
                    threadPoolExecutor.execute(()->{
                        //推送成都监管
                        NotificationConnectorChargeStatusVo statusVo = new NotificationConnectorChargeStatusVo();
                        statusVo.setOrderCode(finalOrder.getCode());
                        statusVo.setChargingGunId(finalOrder.getChargingGunId());
                        chengDuJianGuanClient.notificationConnectorChargeStatus(statusVo);
                        chengDuJianGuanClient.notificationOrderInfo(statusVo);
                    });
 
 
                    //添加积分
                    if (1 == order.getOrderSource()) {
                        TIntegralRule integralRule = integralRuleClient.getSet().getData();
                        if (null != integralRule) {
                            TAppUser appUser = appUserClient.getUserById(order.getAppUserId()).getData();
                            Integer num1 = com.alibaba.fastjson2.JSON.parseObject(integralRule.getChargeCredit()).getInteger("num1");
                            Integer integral = order.getServiceCharge().intValue() * num1;
                            if (null != appUser.getVipId()) {
                                TVip vip = vipClient.getInfo1(appUser.getVipId()).getData();
                                Integer doubleIntegration = vip.getDoubleIntegration();
                                //双倍积分
                                if (1 == doubleIntegration) {
                                    integral *= 2;
                                }
                            }
 
                            if (integral > 0) {
                                TAppUserIntegralChange appUserIntegralChange = new TAppUserIntegralChange();
                                appUserIntegralChange.setAppUserId(appUser.getId());
                                appUserIntegralChange.setChangeType(2);
                                appUserIntegralChange.setHistoricalIntegral(appUser.getPoints());
                                appUser.setPoints(appUser.getPoints() + integral);
                                appUserIntegralChange.setCurrentIntegral(appUser.getPoints());
                                appUserIntegralChange.setCreateTime(LocalDateTime.now());
                                appUserIntegralChange.setOrderCode(order.getCode());
                                appUserIntegralChange.setExtension(order.getId().toString());
                                appUserClient.updateAppUser(appUser);
                                appUserIntegralChangeClient.addAppUserIntegralChange(appUserIntegralChange);
                            }
                        }
 
                        //计算用户标签
                        chargingOrderService.editUserTag(order);
                        //用户推荐奖励
                        chargingOrderService.referralReward(order);
 
                         //开始构建退款费用
                        refundAmount = refundAmount.setScale(2, RoundingMode.HALF_EVEN);
                        if (refundAmount.compareTo(BigDecimal.ZERO) > 0) {
                            Integer rechargePaymentType = order.getRechargePaymentType();
                            Integer payMethod = order.getPayMethod();
                            BigDecimal thirdRefundAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
                            BigDecimal balanceRefundAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
                            if (Integer.valueOf(1).equals(payMethod)) {
                                balanceRefundAmount = refundAmount.min(money(order.getBalancePayAmount())).setScale(2, RoundingMode.HALF_UP);
                            } else if (Integer.valueOf(2).equals(payMethod)) {
                                thirdRefundAmount = refundAmount.min(money(order.getThirdPayAmount())).setScale(2, RoundingMode.HALF_UP);
                                balanceRefundAmount = refundAmount.subtract(thirdRefundAmount).min(money(order.getBalancePayAmount())).setScale(2, RoundingMode.HALF_UP);
                            } else {
                                thirdRefundAmount = refundAmount;
                            }
                            refundAmount = thirdRefundAmount.add(balanceRefundAmount).setScale(2, RoundingMode.HALF_UP);
                            order.setThirdRefundAmount(thirdRefundAmount);
                            order.setBalanceRefundAmount(balanceRefundAmount);
                            order.setRefundAmount(refundAmount);
                            order.setRefundStatus(refundAmount.compareTo(BigDecimal.ZERO) > 0 ? 1 : 2);
                            chargingOrderService.updateById(order);
                            //构建退款明细
                            TChargingOrderRefund chargingOrderRefund = new TChargingOrderRefund();
                            chargingOrderRefund.setChargingOrderId(order.getId());
                            SimpleDateFormat sdfaa = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                            chargingOrderRefund.setRefundCode("CDF" + sdfaa.format(new Date()) + (Double.valueOf(Math.random() * 1000).intValue()));
                            chargingOrderRefund.setRefundAmount(refundAmount);
                            chargingOrderRefund.setRefundStatus(1);
                            chargingOrderRefund.setPayType(rechargePaymentType);
                            chargingOrderRefund.setCode(order.getCode());
                            chargingOrderRefund.setRefundTitle("充电完成退款");
                            chargingOrderRefund.setRefundContent("充电完成退款");
                            chargingOrderRefund.setRefundReason("充电完成退款");
                            chargingOrderRefund.setRefundRemark("实际充电消费金额:" + order.getPaymentAmount());
                            chargingOrderRefund.setRefundTotalAmount(refundAmount);
                            chargingOrderRefund.setPayAmount(rechargeAmount);
                            if (thirdRefundAmount.compareTo(BigDecimal.ZERO) == 0) {
                                chargingOrderRefund.setRefundStatus(2);
                                chargingOrderRefund.setRefundSerialNumber("BALANCE");
                                chargingOrderRefund.setRefundTime(LocalDateTime.now());
                                chargingOrderRefundService.save(chargingOrderRefund);
                                if (balanceRefundAmount.compareTo(BigDecimal.ZERO) > 0) {
                                    recordBalanceRefund(order, balanceRefundAmount, chargingOrderRefund.getRefundCode());
                                }
                                order.setRefundStatus(2);
                                order.setRefundTime(LocalDateTime.now());
                                chargingOrderService.updateById(order);
                            } else if (1 == rechargePaymentType) {
                                WxPaymentRefundModel model = new WxPaymentRefundModel();
                                model.setOut_trade_no(order.getCode());
                                model.setOut_refund_no(chargingOrderRefund.getRefundCode());
                                model.setReason("充电完成退款");
                                model.setNotify_url("/payment/wx/refund/notify");
                                WxPaymentRefundModel.RefundAmount amount = new WxPaymentRefundModel.RefundAmount();
                                amount.setRefund(thirdRefundAmount.multiply(new BigDecimal(100)).intValue());
                                amount.setTotal((isBalancePayMode(order.getPayMethod()) ? money(order.getThirdPayAmount()) : rechargeAmount).multiply(new BigDecimal(100)).intValue());
                                amount.setCurrency("CNY");
                                model.setAmount(amount);
                                R<Map<String, Object>> result = wxPaymentClient.refundOrderR(model);
                                if (200 == result.getCode()) {
                                    chargingOrderRefundService.save(chargingOrderRefund);
                                    //???
                                    Map<String, Object> amount1 = (Map<String, Object>) result.getData().get("amount");
                                    Object refund_fee1 = amount1.get("refund_fee");
                                    BigDecimal refund_fee = new BigDecimal(null == refund_fee1 ? "0" : refund_fee1.toString()).divide(new BigDecimal(100));
                                    chargingOrderRefund.setRefundFee(refund_fee);
                                    chargingOrderRefundService.updateById(chargingOrderRefund);
                                }
                            }
                            else if (2 == rechargePaymentType) {
                                RefundReq dto = new RefundReq();
                                dto.setOutTradeNo(order.getCode());
                                dto.setOutRequestNo(chargingOrderRefund.getRefundCode());
                                dto.setRefundAmount(thirdRefundAmount.toString());
                                dto.setRefundReason("充电完成退款");
                                RefundResp resp = aliPaymentClient.refund(dto).getData();
                                if (null != resp) {
                                    chargingOrderRefundService.save(chargingOrderRefund);
                                    chargingOrderService.chargingOrderStartupFailureWxRefund(chargingOrderRefund.getRefundCode(), resp.getTradeNo(), "SUCCESS", null);
                                }
                            }
                            else if (3 == rechargePaymentType) {
                                RefundReq dto = new RefundReq();
                                dto.setOutTradeNo(order.getRechargeSerialNumber());
                                dto.setOutRequestNo(chargingOrderRefund.getRefundCode());
                                dto.setRefundAmount(thirdRefundAmount.toString());
                                dto.setRefundReason("充电完成退款");
                                RefundResp resp = h5AliPaymentClient.refund(dto).getData();
                                if (null != resp && "10000".equals(resp.getCode())) {
                                    chargingOrderRefundService.save(chargingOrderRefund);
                                    chargingOrderService.chargingOrderStartupFailureWxRefund(chargingOrderRefund.getRefundCode(), resp.getTradeNo(), "SUCCESS", null);
                                }
                            }
                        }
                    }
 
                    //添加汇总统计数据
                    List<TChargingOrderAccountingStrategy> list4 = chargingOrderAccountingStrategyService.list(new QueryWrapper<TChargingOrderAccountingStrategy>().eq("charging_order_id", order.getId()));
                    BigDecimal electronic_reduce = list4.stream().map(TChargingOrderAccountingStrategy::getPeriodElectricPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal service_reduce = list4.stream().map(TChargingOrderAccountingStrategy::getPeriodServicePrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal chargingCapacity = list4.stream().map(TChargingOrderAccountingStrategy::getChargingCapacity).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal serviceMoney = BigDecimal.ZERO;
                    BigDecimal paymentMoney = BigDecimal.ZERO;
                    long time = 0;
                    if (!order.getOrderSource().equals(2)) {
                        serviceMoney = serviceMoney.add(service_reduce);
                        paymentMoney = paymentMoney.add(electronic_reduce).add(service_reduce);
                    } else {
                        serviceMoney = serviceMoney.add(service_reduce.multiply(new BigDecimal("0.8")));
                        paymentMoney = paymentMoney.add(electronic_reduce).add(service_reduce.multiply(new BigDecimal("0.8")));
                    }
                    if (order.getStartTime() != null && order.getEndTime() != null) {
                        time = ChronoUnit.SECONDS.between(order.getStartTime(), order.getEndTime());
                    }
                    TChargingOrderSummaryData summaryData = new TChargingOrderSummaryData();
                    summaryData.setChargingOrderId(order.getId());
                    summaryData.setChargingCapacity(chargingCapacity.setScale(6, RoundingMode.HALF_EVEN));
                    summaryData.setChargingDuration(time);
                    summaryData.setIncome(paymentMoney.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    summaryData.setElectricPrice(electronic_reduce.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    summaryData.setServicePrice(serviceMoney.setScale(2, BigDecimal.ROUND_HALF_EVEN));
                    chargingOrderSummaryDataService.save(summaryData);
 
                    //推送监管平台订单状态和订单详情
                    ChargingOrderVo chargingOrderVo = new ChargingOrderVo();
                    BeanUtils.copyProperties(order, chargingOrderVo);
                    chargingMessageClient.pushOrderInfo(chargingOrderVo);
                    chargingMessageClient.pushOrderStatus(chargingOrderVo);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
 
 
    /**
     * 添加充电算账单汇总数据
     */
    public void addChargingSettlementBill(){
        try {
            int day = LocalDate.now().getDayOfMonth();
            int lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
            //时间在当月的2号到当月的最后一天才执行汇总数据和生成新的汇总数据(中间有修改数据的情况)
            if(2 <= day && day <= lastDay){
                // 获取上个月的开始和结束日期
                LocalDate firstDayOfLastMonth = LocalDate.now().minusMonths(1).
                        withDayOfMonth(2);
                String string = firstDayOfLastMonth.toString();
                // 将-替换为空字符串
                string = string.replace("-", "");
 
                //上个月
                String lastMonth = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
                //统计数据的开始时间
                String startTime = lastMonth + "-01 00:00:00";
                //统计数据的结束时间
                int lasDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
                String endTime = lastMonth + "-" + String.format("%02d", lasDay) + " 23:59:59";
                LocalDateTime createTime = LocalDateTime.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")) + "-02 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
 
                //删除之前生成的汇总数据,在添加最新的汇总数据
                String format = firstDayOfLastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                chargingSettlementBillService.remove(new QueryWrapper<TChargingSettlementBill>().eq("status", 1).last(" and DATE_FORMAT(billing_cycle, '%Y-%m') = '" + format + "'"));
 
                //循环生成按照开始时间和结束时间分别统计的汇总数据
                for (int i = 1; i < 3; i++) {
                    TChargingSettlementBill chargingSettlementBill = new TChargingSettlementBill();
                    // 订单生成规则JSD+20231201(账单所属月份)+1131304205(随机10位数)+001(当月账单序号,每月重置)
                    Random random = new Random();
                    String randomDigits = random.ints(10, 0, 10) // 生成10个随机数字,范围在0-9
                            .mapToObj(String::valueOf)
                            .collect(Collectors.joining()); // 将其连接成一个字符串
                    chargingSettlementBill.setSiteId(0);
                    chargingSettlementBill.setStatisticalDateType(i);
                    chargingSettlementBill.setBillingCycle(firstDayOfLastMonth);
                    chargingSettlementBill.setStatus(1);
                    chargingSettlementBill.setCode("JSD"+string+randomDigits);
 
                    //根据业务订单查询汇总数据
                    List<Map<String, Object>> mapList = chargingOrderService.getChargingSettlementBill(startTime, endTime, i);
                    Long chargingDuration = 0L;
                    Integer orderNumber = 0;
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    BigDecimal platformFee = BigDecimal.ZERO;
                    BigDecimal tripartiteCommission = BigDecimal.ZERO;
                    BigDecimal fundsReceived = BigDecimal.ZERO;
                    BigDecimal totalElectricity = BigDecimal.ZERO;
                    BigDecimal totalElectricityCharge = BigDecimal.ZERO;
                    BigDecimal totalServiceFee = BigDecimal.ZERO;
                    BigDecimal couponDeduction = BigDecimal.ZERO;
                    List<TChargingSettlementBill> list = new ArrayList<>();
                    for (Map<String, Object> map : mapList) {
                        Long charging_duration = null == map.get("chargingDuration") ? 0L : Long.valueOf(map.get("chargingDuration").toString());
                        Integer order_number = null == map.get("orderNum") ? 0 : Integer.valueOf(map.get("orderNum").toString());
                        BigDecimal total_amount = null == map.get("totalAmount") ? BigDecimal.ZERO : new BigDecimal(map.get("totalAmount").toString());
                        BigDecimal platform_fee = null == map.get("platformFee") ? BigDecimal.ZERO : new BigDecimal(map.get("platformFee").toString());
                        BigDecimal tripartite_commission = null == map.get("tripartiteCommission") ? BigDecimal.ZERO : new BigDecimal(map.get("tripartiteCommission").toString());
                        BigDecimal funds_received = total_amount.subtract(platform_fee).subtract(tripartite_commission);
                        BigDecimal total_electricity = null == map.get("totalElectricity") ? BigDecimal.ZERO : new BigDecimal(map.get("totalElectricity").toString());
                        BigDecimal total_electricity_charge = null == map.get("totalElectricityCharge") ? BigDecimal.ZERO : new BigDecimal(map.get("totalElectricityCharge").toString());
                        BigDecimal total_service_fee = null == map.get("totalServiceFee") ? BigDecimal.ZERO : new BigDecimal(map.get("totalServiceFee").toString());
                        BigDecimal coupon_deduction = null == map.get("couponDeduction") ? BigDecimal.ZERO : new BigDecimal(map.get("couponDeduction").toString());
                        //构建每个站点的汇总数据
                        TChargingSettlementBill chargingSettlementBill1 = new TChargingSettlementBill();
                        String randomDigits1 = random.ints(10, 0, 10) // 生成10个随机数字,范围在0-9
                                .mapToObj(String::valueOf)
                                .collect(Collectors.joining()); // 将其连接成一个字符串
                        chargingSettlementBill1.setSiteId(Integer.valueOf(map.get("siteId").toString()));
                        chargingSettlementBill1.setStatisticalDateType(i);
                        chargingSettlementBill1.setBillingCycle(firstDayOfLastMonth);
                        chargingSettlementBill1.setStatus(1);
                        chargingSettlementBill1.setCode("JSD"+string+randomDigits1);
                        chargingSettlementBill1.setChargingDuration(charging_duration);
                        chargingSettlementBill1.setOrderNumber(order_number);
                        chargingSettlementBill1.setTotalAmount(total_amount.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setCouponDeduction(coupon_deduction.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setPlatformFee(platform_fee.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setTripartiteCommission(tripartite_commission.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setFundsReceived(funds_received.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setTotalElectricity(total_electricity.setScale(4, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setTotalElectricityCharge(total_electricity_charge.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setTotalServiceFee(total_service_fee.setScale(2, RoundingMode.HALF_EVEN));
                        chargingSettlementBill1.setCreateTime(createTime);
                        list.add(chargingSettlementBill1);
                        //计算全站汇总数据
                        chargingDuration = chargingDuration + charging_duration;
                        orderNumber = orderNumber + order_number;
                        totalAmount = totalAmount.add(total_amount);
                        platformFee = platformFee.add(platform_fee);
                        tripartiteCommission = tripartiteCommission.add(tripartite_commission);
                        fundsReceived = fundsReceived.add(funds_received);
                        totalElectricity = totalElectricity.add(total_electricity);
                        totalElectricityCharge = totalElectricityCharge.add(total_electricity_charge);
                        totalServiceFee = totalServiceFee.add(total_service_fee);
                        couponDeduction = couponDeduction.add(coupon_deduction);
                    }
 
                    chargingSettlementBill.setChargingDuration(chargingDuration);
                    chargingSettlementBill.setOrderNumber(orderNumber);
                    chargingSettlementBill.setTotalAmount(totalAmount.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setCouponDeduction(couponDeduction.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setPlatformFee(platformFee.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setTripartiteCommission(tripartiteCommission.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setFundsReceived(fundsReceived.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setTotalElectricity(totalElectricity.setScale(4, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setTotalElectricityCharge(totalElectricityCharge.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setTotalServiceFee(totalServiceFee.setScale(2, RoundingMode.HALF_EVEN));
                    chargingSettlementBill.setCreateTime(createTime);
                    chargingSettlementBillService.save(chargingSettlementBill);
                    chargingSettlementBillService.saveBatch(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
 
    /**
     * 添加账户结算账单数据
     */
    public void addAccountSettlementStatement(){
        try {
            int day = LocalDate.now().getDayOfMonth();
            int lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
            //时间在当月的2号到当月的最后一天才执行汇总数据和生成新的汇总数据(中间有修改数据的情况)
            if(2 <= day && day <= lastDay){
                // 获取上个月的开始和结束日期
                LocalDate firstDayOfLastMonth = LocalDate.now().minusMonths(1).
                        withDayOfMonth(2);
                String string = firstDayOfLastMonth.toString();
                // 将-替换为空字符串
                string = string.replace("-", "");
 
                //上个月
                String lastMonth = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
                //统计数据的开始时间
                String startTime = lastMonth + "-01 00:00:00";
                //统计数据的结束时间
                int lasDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
                String endTime = lastMonth + "-" + String.format("%02d", lasDay) + " 23:59:59";
                LocalDateTime createTime = LocalDateTime.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")) + "-02 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
 
                //删除之前生成的汇总数据,在添加最新的汇总数据
                String format = firstDayOfLastMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                accountSettlementStatementService.remove(new QueryWrapper<TAccountSettlementStatement>().eq("status", 1).last(" and DATE_FORMAT(billing_cycle, '%Y-%m') = '" + format + "'"));
 
                //循环生成账户类型分别统计的汇总数据
                for (int i = 1; i < 3; i++) {
                    TAccountSettlementStatement accountSettlementStatement = new TAccountSettlementStatement();
                    // 订单生成规则JSD+20231201(账单所属月份)+1131304205(随机10位数)+001(当月账单序号,每月重置)
                    Random random = new Random();
                    String randomDigits = random.ints(10, 0, 10) // 生成10个随机数字,范围在0-9
                            .mapToObj(String::valueOf)
                            .collect(Collectors.joining()); // 将其连接成一个字符串
                    accountSettlementStatement.setSiteId(0);
                    accountSettlementStatement.setAccountType(i);
                    accountSettlementStatement.setBillingCycle(firstDayOfLastMonth);
                    accountSettlementStatement.setStatus(1);
                    accountSettlementStatement.setCode("JSD"+string+randomDigits);
 
                    //根据业务订单查询汇总数据
                    List<Map<String, Object>> mapList = chargingOrderService.getAccountSettlementStatement(startTime, endTime, i);
                    BigDecimal rechargeAmount = BigDecimal.ZERO;
                    BigDecimal refundAmount = BigDecimal.ZERO;
                    BigDecimal platformFee = BigDecimal.ZERO;
                    BigDecimal tripartiteCommission = BigDecimal.ZERO;
                    BigDecimal recordedAmount = BigDecimal.ZERO;
                    List<TAccountSettlementStatement> list = new ArrayList<>();
                    for (Map<String, Object> map : mapList) {
                        BigDecimal recharge_amount = null == map.get("rechargeAmount") ? BigDecimal.ZERO : new BigDecimal(map.get("rechargeAmount").toString());
                        BigDecimal refund_amount = null == map.get("refundAmount") ? BigDecimal.ZERO : new BigDecimal(map.get("refundAmount").toString());
                        BigDecimal platform_fee = null == map.get("platformFee") ? BigDecimal.ZERO : new BigDecimal(map.get("platformFee").toString());
                        BigDecimal tripartite_commission = null == map.get("tripartiteCommission") ? BigDecimal.ZERO : new BigDecimal(map.get("tripartiteCommission").toString());
                        BigDecimal recorded_amount = recharge_amount.subtract(refund_amount).subtract(platform_fee).subtract(tripartite_commission);
                        //构建每个站点的汇总数据
                        TAccountSettlementStatement accountSettlementStatement1 = new TAccountSettlementStatement();
                        String randomDigits1 = random.ints(10, 0, 10) // 生成10个随机数字,范围在0-9
                                .mapToObj(String::valueOf)
                                .collect(Collectors.joining()); // 将其连接成一个字符串
                        accountSettlementStatement1.setSiteId(Integer.valueOf(map.get("siteId").toString()));
                        accountSettlementStatement1.setAccountType(i);
                        accountSettlementStatement1.setBillingCycle(firstDayOfLastMonth);
                        accountSettlementStatement1.setStatus(1);
                        accountSettlementStatement1.setCode("JSD"+string+randomDigits1);
                        accountSettlementStatement1.setRechargeAmount(recharge_amount.setScale(2, RoundingMode.HALF_EVEN));
                        accountSettlementStatement1.setRefundAmount(refund_amount.setScale(2, RoundingMode.HALF_EVEN));
                        accountSettlementStatement1.setPlatformFee(platform_fee.setScale(2, RoundingMode.HALF_EVEN));
                        accountSettlementStatement1.setTripartiteCommission(tripartite_commission.setScale(2, RoundingMode.HALF_EVEN));
                        accountSettlementStatement1.setRecordedAmount(recorded_amount.setScale(2, RoundingMode.HALF_EVEN));
                        accountSettlementStatement1.setCreateTime(createTime);
                        list.add(accountSettlementStatement1);
                        //计算全站汇总数据
                        rechargeAmount = rechargeAmount.add(recharge_amount);
                        refundAmount = refundAmount.add(refund_amount);
                        platformFee = platformFee.add(platform_fee);
                        tripartiteCommission = tripartiteCommission.add(tripartite_commission);
                        recordedAmount = recordedAmount.add(recorded_amount);
                    }
 
                    accountSettlementStatement.setRechargeAmount(rechargeAmount.setScale(2, RoundingMode.HALF_EVEN));
                    accountSettlementStatement.setRefundAmount(refundAmount.setScale(2, RoundingMode.HALF_EVEN));
                    accountSettlementStatement.setPlatformFee(platformFee.setScale(2, RoundingMode.HALF_EVEN));
                    accountSettlementStatement.setTripartiteCommission(tripartiteCommission.setScale(2, RoundingMode.HALF_EVEN));
                    accountSettlementStatement.setRecordedAmount(recordedAmount.setScale(2, RoundingMode.HALF_EVEN));
                    accountSettlementStatement.setCreateTime(createTime);
                    accountSettlementStatementService.save(accountSettlementStatement);
                    accountSettlementStatementService.saveBatch(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}