liujie
2026-07-22 fdd6c6769ee253cd20392383aa52a3d73f933619
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
package com.ruoyi.chargingPile.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.api.dto.SendMessageDTO;
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.TChargingGunDTO;
import com.ruoyi.chargingPile.api.dto.PageChargingPileListDTO;
import com.ruoyi.chargingPile.api.model.*;
import com.ruoyi.chargingPile.api.query.BatchSetAccountingStrategy;
import com.ruoyi.chargingPile.api.query.PageChargingPileList;
import com.ruoyi.chargingPile.api.vo.TChargingPileVO;
import com.ruoyi.chargingPile.api.domain.SiteMenu;
import com.ruoyi.chargingPile.dto.ChargeMonitoring;
import com.ruoyi.chargingPile.dto.ChargingGunCountMonitoring;
import com.ruoyi.chargingPile.dto.ChargingGunMonitoring;
import com.ruoyi.chargingPile.dto.GetChargingGunMonitoring;
import com.ruoyi.chargingPile.dto.ChargingPileBatchBuildDTO;
import com.ruoyi.chargingPile.dto.ChargingPileBatchBuildResultDTO;
import com.ruoyi.chargingPile.dto.ChargingPileImportDTO;
import com.ruoyi.chargingPile.dto.ChargingPileImportErrorDTO;
import com.ruoyi.chargingPile.dto.ChargingPileImportResultDTO;
import com.ruoyi.chargingPile.mapper.TChargingPileMapper;
import com.ruoyi.chargingPile.service.*;
import com.ruoyi.chargingPile.util.mongodb.service.UploadRealTimeMonitoringDataService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.integration.api.feignClient.*;
import com.ruoyi.integration.api.model.QrCodeDelivery;
import com.ruoyi.integration.api.model.UploadRealTimeMonitoringData;
import com.ruoyi.integration.api.vo.AddDevice;
import com.ruoyi.integration.api.vo.AddDeviceResp;
import com.ruoyi.integration.api.vo.DeleteDeviceResp;
import com.ruoyi.integration.api.vo.ShowDeviceResp;
import com.ruoyi.order.api.feignClient.ChargingOrderAccountingStrategyClient;
import com.ruoyi.order.api.feignClient.ChargingOrderClient;
import com.ruoyi.order.api.model.TChargingOrder;
import com.ruoyi.other.api.feignClient.RoleSiteClient;
import com.ruoyi.other.api.feignClient.UserSiteClient;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.feignClient.SysUserRoleClient;
import com.ruoyi.system.api.model.SysUserRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 充电桩 服务实现类
 * </p>
 *
 * @author xiaochen
 * @since 2024-08-06
 */
@Slf4j
@Service
public class TChargingPileServiceImpl extends ServiceImpl<TChargingPileMapper, TChargingPile> implements TChargingPileService {
    
    @Resource
    private TChargingGunService chargingGunService;
    
    @Resource
    private TCECClient tcecClient;
    
    @Resource
    private SysUserClient sysUserClient;
    
    @Resource
    private IPartnerService partnerService;
    
    @Resource
    private UserSiteClient userSiteClient;
    
    @Resource
    private RoleSiteClient roleSiteClient;
    
    @Resource
    private ISiteService siteService;
    
    @Resource
    private ChargingOrderAccountingStrategyClient chargingOrderAccountingStrategyClient;
    
    @Resource
    private ChargingOrderClient chargingOrderClient;
    
    @Resource
    private AppUserCarClient appUserCarClient;
    
    @Resource
    private UploadRealTimeMonitoringDataService uploadRealTimeMonitoringDataService;
 
    @Resource
    private SysUserRoleClient sysUserRoleClient;
    
    @Resource
    private IotInterfaceClient iotInterfaceClient;
    
    @Resource
    private RedisTemplate redisTemplate;
    
    @Resource
    private TFaultMessageService faultMessageService;
    
    @Resource
    private IntegrationClient integrationClient;
    
    @Resource
    private TAccountingStrategyDetailService accountingStrategyDetailService;
    
    @Resource
    private SendMessageClient sendMessageClient;
    @Resource
    private TokenService tokenService;
    @Resource
    private TChargingPileNotificationService chargingPileNotificationService;
 
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private ChengDuJianGuanClient chengDuJianGuanClient;
    @Resource
    private DongFuStationClient dongFuStationClient;
 
    
 
    /**
     * 获取充电桩列表数据
     * @param page
     * @return
     */
    @Override
    public PageInfo<PageChargingPileListDTO> pageChargingPileList(PageChargingPileList page) {
        Set<Integer> siteIds = null;
        //校验合作商权限
        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
        Integer roleType = sysUser.getRoleType();
        Integer objectId = sysUser.getObjectId();
        //合作商
        if(roleType == 2){
            siteIds = partnerService.authSite(objectId, SiteMenu.CHARGING_PILE);
        }else{
            //非管理员需要根据角色和用户配置查询允许的站点数据
            if(!SecurityUtils.isAdmin(tokenService.getLoginUser().getUserid())){
                List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
                List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
                List<Integer> data1 = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                data.addAll(data1);
                siteIds = new HashSet<>(data);
            }
        }
        PageInfo<PageChargingPileListDTO> pageInfo = new PageInfo<>(page.getPageCurr(), page.getPageSize());
        List<PageChargingPileListDTO> list = this.baseMapper.pageChargingPileList(pageInfo, page, siteIds);
        for (PageChargingPileListDTO pageChargingPileListDTO : list) {
            Integer siteId = pageChargingPileListDTO.getSiteId();
            pageChargingPileListDTO.setAuthAddChargingGun(roleType == 1 ? true : partnerService.authMenu(objectId, siteId, SiteMenu.CHARGING_PILE_ADD_CHARGING_GUN));
            pageChargingPileListDTO.setAuthDelete(roleType == 1 ? true : partnerService.authMenu(objectId, siteId, SiteMenu.CHARGING_PILE_DELETE));
            pageChargingPileListDTO.setAuthQueryInfo(roleType == 1 ? true : partnerService.authMenu(objectId, siteId, SiteMenu.CHARGING_PILE_QUERY_INFO));
            pageChargingPileListDTO.setAuthUpdate(roleType == 1 ? true : partnerService.authMenu(objectId, siteId, SiteMenu.CHARGING_PILE_UPDATE));
        }
        return pageInfo.setRecords(list);
    }
    
    
    /**
     * 添加充电桩
     * @param chargingPile
     * @return
     */
 
    @Override
    public List<PageChargingPileListDTO> listChargingPileForExport(PageChargingPileList page) {
        if (page == null) {
            page = new PageChargingPileList();
        }
        page.setPageCurr(1);
        page.setPageSize(100000);
        return pageChargingPileList(page).getRecords();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChargingPileImportResultDTO importChargingPile(MultipartFile file, Boolean cover) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要导入的Excel文件");
        }
        ExcelUtil<ChargingPileImportDTO> util = new ExcelUtil<>(ChargingPileImportDTO.class);
        List<ChargingPileImportDTO> rows = util.importExcel(file.getInputStream(), 0);
        if (rows == null || rows.isEmpty()) {
            throw new ServiceException("导入文件没有数据");
        }
 
        SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
        Integer roleType = sysUser.getRoleType();
        Integer objectId = sysUser.getObjectId();
        Set<Integer> visibleSiteIds = getChargingPileVisibleSiteIds(sysUser);
        Map<String, Site> siteMap = siteService.list(new LambdaQueryWrapper<Site>().eq(Site::getDelFlag, 0)).stream()
                .filter(site -> StringUtils.isNotEmpty(site.getCode()))
                .collect(Collectors.toMap(site -> normalizeImportValue(site.getCode()), site -> site, (a, b) -> a));
        Map<String, Partner> partnerNameMap = partnerService.list(new LambdaQueryWrapper<Partner>().eq(Partner::getDelFlag, 0)).stream()
                .filter(partner -> StringUtils.isNotEmpty(partner.getName()))
                .collect(Collectors.toMap(partner -> normalizeImportValue(partner.getName()), partner -> partner, (a, b) -> a));
 
        ChargingPileImportResultDTO result = new ChargingPileImportResultDTO();
        List<TChargingPile> validRows = new ArrayList<>();
        Set<String> fileCodes = new HashSet<>();
        Set<String> duplicateCodes = new LinkedHashSet<>();
 
        for (int i = 0; i < rows.size(); i++) {
            ChargingPileImportDTO row = rows.get(i);
            int rowNum = i + 2;
            List<String> errors = validateImportRow(row, siteMap, partnerNameMap, roleType, objectId, visibleSiteIds, fileCodes);
            String code = row == null ? null : normalizeImportValue(row.getCode());
            if (!errors.isEmpty()) {
                result.getErrorMessage().add(new ChargingPileImportErrorDTO(rowNum, code, String.join(";", errors)));
                continue;
            }
            TChargingPile chargingPile = buildImportChargingPile(row, siteMap, partnerNameMap, roleType, objectId);
            TChargingPile exists = this.getOne(new LambdaQueryWrapper<TChargingPile>()
                    .eq(TChargingPile::getCode, chargingPile.getCode())
                    .eq(TChargingPile::getDelFlag, 0));
            if (exists != null) {
                duplicateCodes.add(chargingPile.getCode());
                chargingPile.setId(exists.getId());
                chargingPile.setStatus(exists.getStatus());
                chargingPile.setIotdDeviceId(exists.getIotdDeviceId());
            } else if (chargingPile.getStatus() == null) {
                chargingPile.setStatus(2);
            }
            validRows.add(chargingPile);
        }
 
        result.setErrorCount(result.getErrorMessage().size());
        if (result.getErrorCount() > 0) {
            return result;
        }
        if (!duplicateCodes.isEmpty() && !Boolean.TRUE.equals(cover)) {
            result.setNeedConfirm(true);
            result.setDuplicateCodes(new ArrayList<>(duplicateCodes));
            return result;
        }
        for (TChargingPile chargingPile : validRows) {
            chargingPile.setDelFlag(false);
            if (chargingPile.getId() == null) {
                this.save(chargingPile);
                result.setSuccessCount(result.getSuccessCount() + 1);
            } else {
                this.updateById(chargingPile);
                result.setUpdateCount(result.getUpdateCount() + 1);
            }
        }
        return result;
    }
 
    private List<String> validateImportRow(ChargingPileImportDTO row, Map<String, Site> siteMap,
            Map<String, Partner> partnerNameMap, Integer roleType, Integer objectId,
            Set<Integer> visibleSiteIds, Set<String> fileCodes) {
        List<String> errors = new ArrayList<>();
        if (row == null) {
            errors.add("数据为空");
            return errors;
        }
        String siteCode = normalizeImportValue(row.getSiteCode());
        String code = normalizeImportValue(row.getCode());
        String name = normalizeImportValue(row.getName());
        String partnerName = normalizeImportValue(row.getPartnerName());
        if (StringUtils.isEmpty(siteCode)) {
            errors.add("归属电站编码不能为空");
        } else if (!siteMap.containsKey(siteCode)) {
            errors.add("归属电站不存在");
        }
        if (StringUtils.isEmpty(code)) {
            errors.add("设备编码不能为空");
        } else if (!fileCodes.add(code)) {
            errors.add("导入文件内设备编码重复");
        }
        if (StringUtils.isEmpty(name)) {
            errors.add("充电设备名称不能为空");
        }
        if (row.getNumber() == null) {
            errors.add("桩号不能为空");
        }
        if (row.getType() == null) {
            errors.add("设备类型不能为空");
        }
        if (row.getRatedPower() == null) {
            errors.add("额定功率不能为空");
        }
        Site site = siteMap.get(siteCode);
        if (site != null) {
            if (visibleSiteIds != null && !visibleSiteIds.contains(site.getId())) {
                errors.add("无权操作该电站");
            }
            Integer partnerId = resolveImportPartnerId(partnerName, site, partnerNameMap, roleType, objectId);
            if (partnerId == null) {
                errors.add("归属合作商不存在");
            } else if (Objects.equals(roleType, 2) && !Objects.equals(partnerId, objectId)) {
                errors.add("无权导入其他合作商设备");
            }
        }
        return errors;
    }
 
    private TChargingPile buildImportChargingPile(ChargingPileImportDTO row, Map<String, Site> siteMap,
            Map<String, Partner> partnerNameMap, Integer roleType, Integer objectId) {
        String partnerName = normalizeImportValue(row.getPartnerName());
        Site site = siteMap.get(normalizeImportValue(row.getSiteCode()));
        TChargingPile chargingPile = new TChargingPile();
        chargingPile.setSiteId(site.getId());
        chargingPile.setPartnerId(resolveImportPartnerId(partnerName, site, partnerNameMap, roleType, objectId));
        chargingPile.setCode(normalizeImportValue(row.getCode()));
        chargingPile.setName(normalizeImportValue(row.getName()));
        chargingPile.setNumber(row.getNumber());
        chargingPile.setType(row.getType());
        chargingPile.setManufacturerCode(normalizeImportValue(row.getManufacturerCode()));
        chargingPile.setManufacturer(normalizeImportValue(row.getManufacturer()));
        chargingPile.setEquipmentType(normalizeImportValue(row.getEquipmentType()));
        chargingPile.setProductionDate(row.getProductionDate());
        chargingPile.setRatedPower(row.getRatedPower());
        chargingPile.setChargingStationNumber(normalizeImportValue(row.getChargingStationNumber()));
        chargingPile.setEquipmentClassification(row.getEquipmentClassification());
        chargingPile.setEquipmentUniqueNumber(normalizeImportValue(row.getEquipmentUniqueNumber()));
        chargingPile.setEquipmentLng(normalizeImportValue(row.getEquipmentLng()));
        chargingPile.setEquipmentLat(normalizeImportValue(row.getEquipmentLat()));
        chargingPile.setEquipmentProductCode(normalizeImportValue(row.getEquipmentProductCode()));
        chargingPile.setEquipmentPurpose(row.getEquipmentPurpose());
        chargingPile.setNewNationalStandard(row.getNewNationalStandard());
        chargingPile.setVinFlag(row.getVinFlag());
        return chargingPile;
    }
 
    private Integer resolveImportPartnerId(String partnerName, Site site, Map<String, Partner> partnerNameMap, Integer roleType, Integer objectId) {
        if (Objects.equals(roleType, 2) && StringUtils.isEmpty(partnerName)) {
            return objectId;
        }
        if (StringUtils.isNotEmpty(partnerName)) {
            Partner partner = partnerNameMap.get(partnerName);
            return partner == null ? null : partner.getId();
        }
        return site == null ? null : site.getPartnerId();
    }
 
    private Set<Integer> getChargingPileVisibleSiteIds(SysUser sysUser) {
        Integer roleType = sysUser.getRoleType();
        Integer objectId = sysUser.getObjectId();
        if (Objects.equals(roleType, 2)) {
            return partnerService.authSite(objectId, SiteMenu.CHARGING_PILE);
        }
        if (!SecurityUtils.isAdmin(tokenService.getLoginUser().getUserid())) {
            List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
            List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
            if (data == null) {
                data = new ArrayList<>();
            }
            if (data2 != null && !data2.isEmpty()) {
                List<Integer> roleSiteIds = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                if (roleSiteIds != null) {
                    data.addAll(roleSiteIds);
                }
            }
            return new HashSet<>(data);
        }
        return null;
    }
 
    private String normalizeImportValue(String value) {
        return value == null ? null : value.trim();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChargingPileBatchBuildResultDTO batchBuildChargingPile(ChargingPileBatchBuildDTO dto) {
        if (dto == null || dto.getChargingPile() == null || dto.getChargingGun() == null) {
            throw new ServiceException("批量建桩参数不能为空");
        }
        if (dto.getCodes() == null || dto.getCodes().isEmpty()) {
            throw new ServiceException("设备编码不能为空");
        }
        if (dto.getNumberStart() == null) {
            throw new ServiceException("桩号起始值不能为空");
        }
        if (dto.getGunCount() == null || dto.getGunCount() <= 0) {
            throw new ServiceException("单桩接口数必须大于0");
        }
        List<String> codes = dto.getCodes().stream()
                .filter(StringUtils::isNotEmpty)
                .map(String::trim)
                .collect(Collectors.toList());
        if (codes.isEmpty()) {
            throw new ServiceException("设备编码不能为空");
        }
        Set<String> distinctCodes = new LinkedHashSet<>(codes);
        if (distinctCodes.size() != codes.size()) {
            throw new ServiceException("设备编码存在重复");
        }
 
        ChargingPileBatchBuildResultDTO result = new ChargingPileBatchBuildResultDTO();
        TChargingPile pileTemplate = dto.getChargingPile();
        TChargingGunDTO gunTemplate = dto.getChargingGun();
        if (gunTemplate.getAuxPower() == null) {
            throw new ServiceException("辅助电源不能为空");
        }
        if (gunTemplate.getOpreateStatus() == null) {
            throw new ServiceException("运营状态不能为空");
        }
        String namePrefix = StringUtils.isEmpty(dto.getNamePrefix()) ? "" : dto.getNamePrefix().trim();
        for (int i = 0; i < codes.size(); i++) {
            TChargingPile chargingPile = new TChargingPile();
            BeanUtils.copyProperties(pileTemplate, chargingPile);
            chargingPile.setId(null);
            chargingPile.setCode(codes.get(i));
            chargingPile.setNumber(dto.getNumberStart() + i);
            chargingPile.setName(namePrefix + chargingPile.getNumber() + "号桩");
            AjaxResult pileResult = addChargingPile(chargingPile);
            if (pileResult.isError()) {
                throw new ServiceException("设备" + chargingPile.getCode() + "创建失败:" + getAjaxMessage(pileResult));
            }
            result.setPileCount(result.getPileCount() + 1);
 
            for (int j = 1; j <= dto.getGunCount(); j++) {
                TChargingGunDTO chargingGun = new TChargingGunDTO();
                BeanUtils.copyProperties(gunTemplate, chargingGun);
                String gunCode = String.format("%02d", j);
                chargingGun.setId(null);
                chargingGun.setCode(gunCode);
                chargingGun.setName(chargingPile.getName() + gunCode + "枪");
                chargingGun.setChargingPileId(chargingPile.getId());
                chargingGun.setSiteId(chargingPile.getSiteId());
                chargingGun.setPartnerId(chargingPile.getPartnerId());
                AjaxResult gunResult = chargingGunService.add(chargingGun);
                if (gunResult.isError()) {
                    throw new ServiceException("设备" + chargingPile.getCode() + "接口" + gunCode + "创建失败:" + getAjaxMessage(gunResult));
                }
                result.setGunCount(result.getGunCount() + 1);
            }
        }
        return result;
    }
 
    private String getAjaxMessage(AjaxResult ajaxResult) {
        Object msg = ajaxResult.get("msg");
        return msg == null ? "未知错误" : msg.toString();
    }
    @Override
    public AjaxResult addChargingPile(TChargingPile chargingPile) {
        AjaxResult ajaxResult = addChargingPileVerify(chargingPile);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        long count = this.count(new LambdaQueryWrapper<TChargingPile>().eq(TChargingPile::getCode, chargingPile.getCode())
                .eq(TChargingPile::getDelFlag, 0));
        if(count > 0){
            return AjaxResult.error("设备编号已存在");
        }
        //调用华为Iot创建设备
        ShowDeviceResp showDeviceResp = iotInterfaceClient.showDeviceRequest(chargingPile.getCode()).getData();
        if(null == showDeviceResp){
            //调用华为Iot创建设备
            AddDevice addDevice = new AddDevice();
            addDevice.setProductId("66da68d21837002b28b34ec0");
            addDevice.setNodeId(chargingPile.getCode());
            addDevice.setDeviceName(chargingPile.getName());
            addDevice.setDescription(chargingPile.getNumber().toString());
            AddDeviceResp deviceResp = iotInterfaceClient.addDevice(addDevice).getData();
            if(null != deviceResp){
                int httpStatusCode = deviceResp.getHttpStatusCode();
                if(httpStatusCode == 201){
                    chargingPile.setIotdDeviceId(deviceResp.getDeviceId());
                }else{
                    log.error("华为创建设备失败" + JSON.toJSONString(deviceResp));
                    return AjaxResult.error("华为创建设备失败");
                }
            }else{
                log.error("华为创建设备失败" + JSON.toJSONString(deviceResp));
                return AjaxResult.error("华为创建设备失败");
            }
        }else{
            chargingPile.setIotdDeviceId(showDeviceResp.getDeviceId());
        }
        this.save(chargingPile);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        threadPoolExecutor.execute(()->{
            //推送成都监管
            chengDuJianGuanClient.notificationStationInfo(chargingPile.getSiteId());
            // TODO 东涪推送
            dongFuStationClient.pushChargingPile();
        });
        return AjaxResult.success();
    }
    
    
    /**
     * 校验必填项
     * @param chargingPile
     * @return
     */
    AjaxResult addChargingPileVerify(TChargingPile chargingPile){
        if(StringUtils.isEmpty(chargingPile.getCode())){
            return AjaxResult.error("设备编号不能为空");
        }
        if(StringUtils.isEmpty(chargingPile.getName())){
            return AjaxResult.error("充电设备名称不能为空");
        }
        if(null == chargingPile.getNumber()){
            return AjaxResult.error("桩号不能为空");
        }
        if(null == chargingPile.getType()){
            return AjaxResult.error("设备类型不能为空");
        }
        if(null == chargingPile.getSiteId()){
            return AjaxResult.error("归属电站不能为空");
        }
        if(null == chargingPile.getPartnerId()){
            return AjaxResult.error("归属合作商不能为空");
        }
        if(null == chargingPile.getRatedPower()){
            return AjaxResult.error("额定功率不能为空");
        }
        return AjaxResult.success();
    }
    
    
    /**
     * 获取充电桩详情
     * @param id 充电桩id
     * @return
     */
    @Override
    public TChargingPile getChargingPile(Integer id) {
        return this.baseMapper.getChargingPile(id);
    }
    
    
    /**
     * 编辑充电桩
     * @param chargingPile
     * @return
     */
    @Override
    public AjaxResult editChargingPile(TChargingPile chargingPile) {
        AjaxResult ajaxResult = addChargingPileVerify(chargingPile);
        if(ajaxResult.isError()){
            return ajaxResult;
        }
        TChargingPile one = this.getOne(new LambdaQueryWrapper<TChargingPile>().eq(TChargingPile::getCode, chargingPile.getCode())
                .eq(TChargingPile::getDelFlag, 0));
        if(null != one && !one.getId().equals(chargingPile.getId())){
            return AjaxResult.error("设备编号已存在");
        }
        TChargingPile tChargingPile = this.getById(chargingPile.getId());
        //桩号不相同,需要重新绑定设备
        if(!tChargingPile.getCode().equals(chargingPile.getCode())){
            ShowDeviceResp showDeviceResp = iotInterfaceClient.showDeviceRequest(tChargingPile.getCode()).getData();
            if(null != showDeviceResp){
                DeleteDeviceResp deleteDeviceResp = iotInterfaceClient.deleteDevice(tChargingPile.getCode()).getData();
                if(null == deleteDeviceResp){
                    return AjaxResult.error("删除设备异常,请查看华为设备管理");
                }
            }
        }
        
        ShowDeviceResp showDeviceResp = iotInterfaceClient.showDeviceRequest(tChargingPile.getCode()).getData();
        if(null == showDeviceResp){
            //调用华为Iot创建设备
            AddDevice addDevice = new AddDevice();
            addDevice.setProductId("66da68d21837002b28b34ec0");
            addDevice.setNodeId(chargingPile.getCode());
            addDevice.setDeviceName(chargingPile.getName());
            addDevice.setDescription(chargingPile.getNumber().toString());
            AddDeviceResp deviceResp = iotInterfaceClient.addDevice(addDevice).getData();
            if(null != deviceResp){
                int httpStatusCode = deviceResp.getHttpStatusCode();
                if(httpStatusCode == 201){
                    chargingPile.setIotdDeviceId(deviceResp.getDeviceId());
                }else{
                    log.error("华为创建设备失败" + JSON.toJSONString(deviceResp));
                    return AjaxResult.error("华为创建设备失败");
                }
            }else{
                return AjaxResult.error("华为创建设备失败");
            }
        }
        this.updateById(chargingPile);
        
        List<TChargingGun> list = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().eq(TChargingGun::getChargingPileId, chargingPile.getId()).eq(TChargingGun::getDelFlag, 0));
        for (TChargingGun chargingGun : list) {
            TChargingGun chargingGun1 = new TChargingGun();
            chargingGun1.setId(chargingGun.getId());
            String stableFullNumber = StringUtils.isNotEmpty(chargingGun.getFullNumber()) ? chargingGun.getFullNumber() : chargingPile.getCode() + chargingGun.getCode();
            chargingGun1.setFullNumber(stableFullNumber);
            chargingGun1.setSiteId(chargingPile.getSiteId());
            chargingGunService.updateById(chargingGun1);
            
            //下发硬件充电二维码
            String code_prefix = "https://mxcd.zhinenganguan.com?No=";
            QrCodeDelivery qrCodeDelivery = new QrCodeDelivery();
            qrCodeDelivery.setCharging_pile_code(chargingPile.getCode());
            qrCodeDelivery.setCharging_gun_code(chargingGun.getCode());
            qrCodeDelivery.setCode_format(1);
            qrCodeDelivery.setPrefix_length(code_prefix.length());
            qrCodeDelivery.setCode_prefix(code_prefix);
            qrCodeDelivery.setQr_code(code_prefix + stableFullNumber);
            qrCodeDelivery.setCreate_time(new Date());
            qrCodeDelivery.setLast_time(new Date());
            sendMessageClient.qrCodeDelivery(qrCodeDelivery);
        }
        tcecClient.superviseNotificationStationInfo(chargingPile.getSiteId());
 
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        threadPoolExecutor.execute(()->{
            //推送成都监管
            chengDuJianGuanClient.notificationStationInfo(chargingPile.getSiteId());
            // TODO 东涪推送
            dongFuStationClient.pushChargingPile();
        });
        return AjaxResult.success();
    }
    
    
    /**
     * 删除充电桩
     * @param ids
     * @return
     */
    @Override
    public AjaxResult delChargingPile(Integer[] ids) {
        //检查是否有关联数据
        long count = chargingGunService.count(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getChargingPileId, Arrays.asList(ids))
                .eq(TChargingGun::getDelFlag, 0));
        if(count > 0){
            return AjaxResult.error("该充电桩已添加接口,不可删除。");
        }
        for (Integer id : ids) {
            TChargingPile chargingPile = this.getById(id);
            //调用华为Iot删除设备
            if(StringUtils.isNotEmpty(chargingPile.getIotdDeviceId())){
                ShowDeviceResp showDeviceResp = iotInterfaceClient.showDeviceRequest(chargingPile.getCode()).getData();
                if(null != showDeviceResp){
                    DeleteDeviceResp deleteDeviceResp = iotInterfaceClient.deleteDevice(chargingPile.getCode()).getData();
                    if(null == deleteDeviceResp || (deleteDeviceResp.getHttpStatusCode() != 200 && deleteDeviceResp.getHttpStatusCode() != 201 && deleteDeviceResp.getHttpStatusCode() != 204)){
                        return AjaxResult.error("删除设备异常,请查看华为设备管理");
                    }
                    chargingPile.setIotdDeviceId("");
                }
 
            }
            this.removeById(chargingPile);
        }
        return AjaxResult.success();
    }
    
    /**
     * 批量设置计费策略
     * @param setAccountingStrategy
     */
    @Override
    public void batchSetAccountingStrategy(BatchSetAccountingStrategy setAccountingStrategy) {
        List<Integer> id = setAccountingStrategy.getId();
        List<TChargingGun> list = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getChargingPileId, id).eq(TChargingGun::getDelFlag, 0));
        for (TChargingGun tChargingGun : list) {
            TChargingGun tChargingGun1 = new TChargingGun();
            tChargingGun1.setId(tChargingGun.getId());
            tChargingGun1.setAccountingStrategyId(setAccountingStrategy.getAccountingStrategyId());
            chargingGunService.updateById(tChargingGun1);
        }
        Integer accountingStrategyId = setAccountingStrategy.getAccountingStrategyId();
        List<TAccountingStrategyDetail> accountingStrategyDetails = accountingStrategyDetailService.list(new LambdaQueryWrapper<TAccountingStrategyDetail>()
                .eq(TAccountingStrategyDetail::getAccountingStrategyId, accountingStrategyId).orderByAsc(TAccountingStrategyDetail::getStartTime));
        //下发硬件更新计费模板
        List<TChargingPile> tChargingPiles = this.listByIds(id);
        for (TChargingPile chargingPile : tChargingPiles) {
            integrationClient.setupBillingModel1(chargingPile.getCode(), JSON.toJSONString(accountingStrategyDetails));
        }
        
    }
 
    @Override
    public List<TChargingPileVO> getChargingGunList(Integer siteId,Integer type) {
        LambdaQueryWrapper<TChargingGun> wrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(type)){
            wrapper.eq(TChargingGun::getChargeMode, type);
        }
        wrapper.eq(TChargingGun::getSiteId, siteId);
        List<TChargingGun> chargingGuns = chargingGunService.list(wrapper);
        Set<Integer> collect = chargingGuns.stream().map(TChargingGun::getChargingPileId).collect(Collectors.toSet());
        List<TChargingPileVO> chargingPileVOS = new ArrayList<>();
        if(collect.size() > 0){
            List<TChargingPile> tChargingPiles = this.baseMapper.selectBatchIds(collect);
            for (TChargingPile tChargingPile : tChargingPiles) {
                TChargingPileVO vo = new TChargingPileVO();
                List<TChargingGun> chargingGunList = chargingGuns.stream().filter(gun -> gun.getChargingPileId().equals(tChargingPile.getId())).collect(Collectors.toList());
                for (TChargingGun chargingGun : chargingGunList) {
                    if(chargingGun.getStatus().equals(4)){
                        // 查询正在充电的单子的实时记录
                        TChargingOrder chargingOrder = chargingOrderClient.getOrderDetailByGunId(chargingGun.getId()).getData();
                        if(Objects.nonNull(chargingOrder)){
                            UploadRealTimeMonitoringData uploadRealTimeMonitoringData = uploadRealTimeMonitoringDataService.getLastDataById(chargingOrder.getCode());
                            if(null != uploadRealTimeMonitoringData){
                                chargingGun.setSoc(uploadRealTimeMonitoringData.getSoc());
                            }else{
                                chargingGun.setSoc(0);
                            }
                        }else {
                            chargingGun.setSoc(100);
                        }
                    }
                    if(chargingGun.getStatus().equals(5)){
                        chargingGun.setSoc(100);
                    }
                }
                vo.setChargingGunList(chargingGunList);
                vo.setId(tChargingPile.getId());
                vo.setCode(tChargingPile.getCode());
                vo.setName(tChargingPile.getName());
                vo.setNumber(tChargingPile.getNumber());
                chargingPileVOS.add(vo);
                
            }
        }
        return chargingPileVOS;
    }
    
    
    /**
     * 获取监控设备监控数据
     * @param siteId
     * @return
     */
    @Override
    public ChargeMonitoring chargeMonitoring(Integer siteId) {
        //获取当前登录账户的站点权限数据
        Set<Integer> siteIds = new HashSet<>();
        if(0 == siteId){
            SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
            Integer roleType = sysUser.getRoleType();
            Integer objectId = sysUser.getObjectId();
            if(2 == roleType){
                siteIds = partnerService.authSite(objectId, SiteMenu.CHARGING_FACILITY_MONITORING);
            }else{
                //非管理员需要根据角色和用户配置查询允许的站点数据
                if(!SecurityUtils.isAdmin(tokenService.getLoginUser().getUserid())){
                    List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
                    List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
                    List<Integer> data1 = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                    data.addAll(data1);
                    siteIds = new HashSet<>(data);
                }else{
                    siteIds = null;
                }
            }
        }else{
            siteIds.add(siteId);
        }
        List<Site> sites = null;
        if(null == siteIds){
            sites = siteService.list(new LambdaQueryWrapper<Site>().eq(Site::getDelFlag, 0));
            siteIds = sites.stream().map(Site::getId).collect(Collectors.toSet());
        }else{
            sites = siteService.listByIds(siteIds);
        }
        List<TChargingGun> total = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getSiteId, siteIds).eq(TChargingGun::getDelFlag, 0));
        List<TChargingGun> charging = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getSiteId, siteIds).eq(TChargingGun::getStatus, 4).eq(TChargingGun::getDelFlag, 0));
        BigDecimal ratedPower = sites.stream().map(Site::getRatedPower).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal realTimePower = charging.stream().map(TChargingGun::getChargingPower).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        
        ChargeMonitoring chargeMonitoring = new ChargeMonitoring();
        chargeMonitoring.setPhone(sites.size() == 1 ? sites.get(0).getPhone() : "");
        chargeMonitoring.setAddress(sites.size() == 1 ? sites.get(0).getAddress() : "");
        chargeMonitoring.setTerminalTotal(total.size());
        chargeMonitoring.setCharging(charging.size());
        chargeMonitoring.setNotCharged(total.size() - charging.size());
        chargeMonitoring.setRatedPower(ratedPower.setScale(4, RoundingMode.HALF_EVEN));
        chargeMonitoring.setRealTimePower(realTimePower.setScale(4, RoundingMode.HALF_EVEN));
        if(ratedPower.compareTo(BigDecimal.ZERO) == 0){
            chargeMonitoring.setDemandPowerSatisfactionRate(BigDecimal.ZERO);
        }else{
            chargeMonitoring.setDemandPowerSatisfactionRate(realTimePower.divide(ratedPower, new MathContext(2, RoundingMode.HALF_EVEN))
                    .multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_EVEN));
        }
 
        List<String> dates = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 6; i >= 0; i--) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
            dates.add(sdf.format(calendar.getTime()));
        }
        List<List<Map<String, Object>>> value1 = chargingOrderAccountingStrategyClient.getTotalElectricQuantity(6, siteIds).getData();
        Map<String, Object> chargeTrend = new HashMap<>();
        chargeTrend.put("date", dates);
        chargeTrend.put("value", value1);
        chargeMonitoring.setChargeTrend(chargeTrend);
        
        // 每日利用率=当日充电度数/(站点变压器额定功率*24小时)
        List<Double> data = chargingOrderAccountingStrategyClient.getDailyChargingDegree(6, siteIds).getData();
        List<Double> value2 = new ArrayList<>();
        BigDecimal multiply = ratedPower.multiply(new BigDecimal(24));
        for (Double datum : data) {
            if(multiply.compareTo(BigDecimal.ZERO) == 0){
                value2.add(0D);
            }else{
                Double datum1 = new BigDecimal(datum).divide(multiply, new MathContext(4, RoundingMode.HALF_EVEN))
                        .multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
                value2.add(datum1);
            }
        }
        Map<String, Object> utilizationTrend = new HashMap<>();
        utilizationTrend.put("date", dates);
        utilizationTrend.put("value", value2);
        chargeMonitoring.setUtilizationTrend(utilizationTrend);
        return chargeMonitoring;
    }
 
 
 
    /**
     * 获取充电枪各种状态汇总
     * @param siteId 站点id
     * @return
     */
    @Override
    public ChargingGunCountMonitoring getChargingGunCountMonitoring(Integer siteId) {
        //获取当前登录账户的站点权限数据
        Set<Integer> siteIds = new HashSet<>();
        if(0 == siteId){
            SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
            Integer roleType = sysUser.getRoleType();
            Integer objectId = sysUser.getObjectId();
            if(2 == roleType){
                siteIds = partnerService.authSite(objectId, SiteMenu.CHARGING_FACILITY_MONITORING);
            }else{
                //非管理员需要根据角色和用户配置查询允许的站点数据
                if(!SecurityUtils.isAdmin(tokenService.getLoginUser().getUserid())){
                    List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
                    List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
                    List<Integer> data1 = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                    data.addAll(data1);
                    siteIds = new HashSet<>(data);
                }else{
                    List<Site> list = siteService.list(new LambdaQueryWrapper<Site>().eq(Site::getDelFlag, 0));
                    siteIds = list.stream().map(Site::getId).collect(Collectors.toSet());
                }
            }
        }else{
            siteIds.add(siteId);
        }
        List<TChargingGun> list = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getSiteId, siteIds).eq(TChargingGun::getDelFlag, 0));
        //空闲
        long leisure = list.stream().filter(s -> s.getStatus().equals(2)).count();
        //已插枪
        long loaded = list.stream().filter(s -> Arrays.asList(3, 5, 6).contains(s.getStatus())).count();
        //充电中
        long charging = list.stream().filter(s -> s.getStatus().equals(4)).count();
        //离网
        long offline = list.stream().filter(s -> s.getStatus().equals(1)).count();
        //故障
        long breakdown = list.stream().filter(s -> s.getStatus().equals(7)).count();
        ChargingGunCountMonitoring chargingGunCountMonitoring = new ChargingGunCountMonitoring();
        chargingGunCountMonitoring.setLeisure(leisure);
        chargingGunCountMonitoring.setLoaded(loaded);
        chargingGunCountMonitoring.setCharging(charging);
        chargingGunCountMonitoring.setOffline(offline);
        chargingGunCountMonitoring.setBreakdown(breakdown);
        return chargingGunCountMonitoring;
    }
    
    /**
     * 获取充电枪监控数据
     * @param query
     * @return
     */
    @Override
    public PageInfo<ChargingGunMonitoring> getChargingGunMonitoring(GetChargingGunMonitoring query) {
        //获取当前登录账户的站点权限数据
        Set<Integer> siteIds = new HashSet<>();
        if(0 == query.getSiteId()){
            SysUser sysUser = sysUserClient.getSysUser(tokenService.getLoginUser().getUserid()).getData();
            R<Integer> admin = sysUserClient.isAdmin(tokenService.getLoginUser().getUserid());
            Integer roleType = sysUser.getRoleType();
            Integer objectId = sysUser.getObjectId();
            if(2 == roleType){
                siteIds = partnerService.authSite(objectId, SiteMenu.CHARGING_FACILITY_MONITORING);
            }else{
                //非管理员需要根据角色和用户配置查询允许的站点数据
                if(admin.getData()!=1){
                    List<Integer> data = userSiteClient.getSiteIds(sysUser.getUserId()).getData();
                    List<SysUserRoleVo> data2 = sysUserRoleClient.getRoleByUserId(sysUser.getUserId()).getData();
                    List<Integer> data1 = roleSiteClient.getSiteIds(data2.get(0).getRoleId()).getData();
                    data.addAll(data1);
                    siteIds = new HashSet<>(data);
                }else{
                    List<Site> list = siteService.list(new LambdaQueryWrapper<Site>().eq(Site::getDelFlag, 0));
                    siteIds = list.stream().map(Site::getId).collect(Collectors.toSet());
                }
            }
        }else{
            siteIds.add(query.getSiteId());
        }
        
        if(null != query.getStatus() && 0 < query.getStatus().size()){
            if(query.getStatus().contains(3)){
                query.getStatus().add(5);
                query.getStatus().add(6);
            }
        }
        PageInfo<ChargingGunMonitoring> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        List<ChargingGunMonitoring> chargingGunMonitoring = this.baseMapper.getChargingGunMonitoring(pageInfo, siteIds, query);
        for (ChargingGunMonitoring gunMonitoring : chargingGunMonitoring) {
            Integer status = gunMonitoring.getStatus();
            if(status == 5 || status == 6){
                gunMonitoring.setStatus(3);
            }
            if(status == 4 || status == 7){
                Integer id = gunMonitoring.getId();
                TChargingOrder chargingOrder = chargingOrderClient.getOrderDetailByGunId(id).getData();
                if(null != chargingOrder){
                    Long appUserCarId = chargingOrder.getAppUserCarId();
                    if(null != appUserCarId){
                        TAppUserCar tAppUserCar = appUserCarClient.getCarByIds(Arrays.asList(appUserCarId)).getData().get(0);
                        gunMonitoring.setLicensePlate(tAppUserCar.getLicensePlate());
                    }else{
                        gunMonitoring.setLicensePlate(chargingOrder.getPlateNum());
                    }
 
                    UploadRealTimeMonitoringData data = uploadRealTimeMonitoringDataService.getLastDataById(chargingOrder.getCode());
                    gunMonitoring.setChargingRatio(BigDecimal.valueOf(data.getSoc()));
                    gunMonitoring.setElectricQuantity(data.getCharging_degree().toString());
                    gunMonitoring.setSoc(data.getSoc().toString());
                    gunMonitoring.setElectricCurrent(data.getOutput_current().toString());
                    gunMonitoring.setVoltage(data.getOutput_voltage().toString());
                    switch (data.getHardware_fault()){
                        case 1:
                            gunMonitoring.setFaultCause("急停按钮动作故障");
                            break;
                        case 2:
                            gunMonitoring.setFaultCause("无可用整流模块");
                            break;
                        case 3:
                            gunMonitoring.setFaultCause("出风口温度过高");
                            break;
                        case 4:
                            gunMonitoring.setFaultCause("交流防雷故障");
                            break;
                        case 5:
                            gunMonitoring.setFaultCause("交直流模块 DC20 通信中断");
                            break;
                        case 6:
                            gunMonitoring.setFaultCause("绝缘检测模块 FC08 通信中断");
                            break;
                        case 7:
                            gunMonitoring.setFaultCause("电度表通信中断");
                            break;
                        case 8:
                            gunMonitoring.setFaultCause("读卡器通信中断");
                            break;
                        case 9:
                            gunMonitoring.setFaultCause("RC10 通信中断");
                            break;
                        case 10:
                            gunMonitoring.setFaultCause("风扇调速板故障");
                            break;
                        case 11:
                            gunMonitoring.setFaultCause("直流熔断器故障");
                            break;
                        case 12:
                            gunMonitoring.setFaultCause("高压接触器故障");
                            break;
                        case 13:
                            gunMonitoring.setFaultCause("门打开");
                            break;
                    }
                }
            }
            //test
//            if (status==1||status==7){
//                TFaultMessage one = faultMessageService.lambdaQuery().eq(TFaultMessage::getChargingGunId, gunMonitoring.getId()).orderByDesc(TFaultMessage::getCreateTime).last("limit 1").one();
//                if (one!=null) {
//                    gunMonitoring.setFaultCause(one.getContent());
//                }
//            }
        }
        return pageInfo.setRecords(chargingGunMonitoring);
    }
    
    
    /**
     * 定时任务修改充电桩状态
     */
    @Override
    public void updateStatus() {
        //查询出redis集合汇总符合条件的数据
        Set keys = redisTemplate.opsForHash().keys("charging_gun_online");
        List<String> fullNumbers = new ArrayList<>();
        keys.forEach(key -> {
                        Long time = (Long) redisTemplate.opsForHash().get("charging_gun_online", key);
                        if(null != time && System.currentTimeMillis() - time > 300000){
                            log.info("设备编号:{} 已离线", key);
                            log.info("间隔时间:{}", System.currentTimeMillis() - time);
                            fullNumbers.add(key.toString());
                        }
        });
        if(fullNumbers.size() == 0){
            return;
        }
        
        //处理符合条件的数据,修改设备状态
        List<TChargingGun> list = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().in(TChargingGun::getFullNumber, fullNumbers).eq(TChargingGun::getDelFlag, 0));
        for (TChargingGun chargingGun : list) {
            TChargingGun chargingGun1 = new TChargingGun();
            chargingGun1.setId(chargingGun.getId());
            chargingGun1.setStatus(1);
            chargingGunService.updateById(chargingGun1);
            Site site = siteService.getById(chargingGun.getSiteId());
            if(1 == site.getIsOpenSynchronization()){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //推送状态给三方平台
                        tcecClient.pushChargingGunStatus(chargingGun.getFullNumber(), 1);
                    }
                }).start();
            }
            
            //桩处于正常,桩所属的枪都处于非正常,修改桩状态为异常
            TChargingPile chargingPile = this.getById(chargingGun.getChargingPileId());
            List<TChargingGun> list1 = chargingGunService.list(new LambdaQueryWrapper<TChargingGun>().eq(TChargingGun::getChargingPileId, chargingPile.getId()).eq(TChargingGun::getDelFlag, 0));
            int size = list1.stream().filter(s -> s.getStatus() == 1 || s.getStatus() == 7).collect(Collectors.toList()).size();
            if(chargingPile.getStatus() == 1 && list1.size() == size){
                TChargingPile chargingPile1 = new TChargingPile();
                chargingPile1.setId(chargingGun.getChargingPileId());
                chargingPile1.setStatus(2);
                this.updateById(chargingPile1);
            }
            
            //添加记录
            TFaultMessage faultMessage = faultMessageService.getOne(new LambdaQueryWrapper<TFaultMessage>().eq(TFaultMessage::getChargingPileId, chargingGun.getChargingPileId())
                    .eq(TFaultMessage::getChargingGunId, chargingGun.getId()).eq(TFaultMessage::getStatus, 1).eq(TFaultMessage::getDelFlag, 0).isNull(TFaultMessage::getEndTime));
            if(null == faultMessage){
                faultMessage = new TFaultMessage();
                faultMessage.setSiteId(chargingGun.getSiteId());
                faultMessage.setChargingPileId(chargingGun.getChargingPileId());
                faultMessage.setChargingGunId(chargingGun.getId());
                faultMessage.setStatus(1);
                faultMessage.setDownTime(LocalDateTime.now());
                faultMessage.setCreateTime(LocalDateTime.now());
                faultMessage.setDelFlag(false);
                faultMessage.setContent("设备离线");
                faultMessageService.save(faultMessage);
                
                // 发送故障短信
                String siteName = site.getName();
                SendMessageDTO sendMessageDTO = new SendMessageDTO();
                sendMessageDTO.setPhone(site.getPhone());
                sendMessageDTO.setSite(site.getName());
                sendMessageDTO.setChargeGun(chargingPile.getNumber() + "");
                sendMessageDTO.setType(3);
                String result = appUserClient.sendMessage(sendMessageDTO).getData();
                if(siteName.length()>10){
                    siteName = siteName.substring(0,10);
                }
                chargingPileNotificationService.saveData(4,faultMessage.getSiteId(),faultMessage.getChargingPileId(),site.getPhone(),"检测到"+siteName+"..."+chargingPile.getNumber()+"号桩设备离线,请及时查看处理!");
            }
        }
    }
}