RiskAssessmentService.java
48.8 KB
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
package cn.com.glsx.admin.modules.service;
import cn.com.glsx.admin.common.constants.Constants;
import cn.com.glsx.admin.common.enums.RiskAlarmTypeEnum;
import cn.com.glsx.admin.common.enums.StuAlarmTypeEnum;
import cn.com.glsx.admin.common.enums.TypeConverseEnum;
import cn.com.glsx.admin.common.exception.AdminException;
import cn.com.glsx.admin.modules.converter.RiskAssessmentConvert;
import cn.com.glsx.admin.modules.entity.*;
import cn.com.glsx.admin.modules.mapper.*;
import cn.com.glsx.admin.modules.model.dto.BasicDeviceDTO;
import cn.com.glsx.admin.modules.model.dto.BasicInformationDTO;
import cn.com.glsx.admin.modules.model.dto.UserBehaviorDayDTO;
import cn.com.glsx.admin.modules.model.dto.UserBehaviorWeekDTO;
import cn.com.glsx.admin.modules.model.export.FinalPositioningExport;
import cn.com.glsx.admin.modules.model.export.OfflineExport;
import cn.com.glsx.admin.modules.model.param.FinalPositioningSearch;
import cn.com.glsx.admin.modules.model.vo.*;
import cn.com.glsx.admin.modules.remote.*;
import cn.com.glsx.admin.modules.utils.DateUtil;
import cn.com.glsx.alarm.services.model.CommonAlarmDto;
import cn.com.glsx.alarm.services.model.StuJudgeAlarmDto;
import cn.com.glsx.auth.utils.ShieldContextHolder;
import cn.com.glsx.devicemonitor.api.dto.LngLatDTO;
import cn.com.glsx.devicemonitor.api.dto.request.ResidentRequest;
import cn.com.glsx.devicemonitor.api.dto.request.StayPointRequest;
import cn.com.glsx.devicemonitor.api.dto.response.*;
import cn.com.glsx.devicemonitor.api.enums.DeviceStatusEnum;
import cn.hutool.core.date.DateUnit;
import cn.hutool.json.JSONUtil;
import com.glsx.plat.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 风险评估 service
*/
@Slf4j
@Service
public class RiskAssessmentService {
@Autowired
private WorkOrderMapper workOrderMapper;
@Autowired
private VehicleMapper vehicleMapper;
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private VehicleDeviceMapper vehicleDeviceMapper;
@Autowired
private RemoteFeignDeviceService remoteFeignDeviceService;
@Autowired
private RemoteGpsBsService remoteGpsBsService;
@Autowired
private RemoteFeignStayPointService remoteFeignStayPointService;
@Autowired
private RemoteFeignResidentService remoteFeignResidentService;
@Autowired
private RemoteAlarmService remoteAlarmService;
@Autowired
private AlarmWarnAnalyseMapper alarmWarnAnalyseMapper;
@Autowired
private DeviceJourneyMapper deviceJourneyMapper;
@Autowired
private RemoteStuJudgeAlarmService remoteStuJudgeAlarmService;
@Autowired
private FakeOfflineVinMapper fakeOfflineVinMapper;
@Autowired
private FakeOfflineChangeFrequentlyMapper fakeOfflineChangeFrequentlyMapper;
@Autowired
private OrganizationApiService organizationApiService;
@Autowired
private WhitelistSnMapper whitelistSnMapper;
@Autowired
private DeviceStayOftenMapper deviceStayOftenMapper;
@Autowired
private FinalPositioningService finalPositioningService;
@Autowired
private DeviceLocationMapper deviceLocationMapper;
@Autowired
private DeviceJourneyOverviewMapper deviceJourneyOverviewMapper;
/**
* 获取停留点列表
*
* @param vehicleId 车辆ID
* @return
*/
public List<StayPointListVO> getStayPointList(Long vehicleId) {
if (Objects.isNull(vehicleId)) {
log.warn("该车辆ID不存在");
throw new AdminException("该车辆ID不存在");
}
// 通过车辆ID获取设备主有线设备
List<BasicDeviceDTO> basicDeviceDTOList = vehicleDeviceMapper.selectBindDeviceByVehicleIdOrderByCreatedDate(vehicleId);
Optional<BasicDeviceDTO> basicDeviceDTO = basicDeviceDTOList.stream().filter(dto -> TypeConverseEnum.SourceEnum.HAS_SOURCE.getSourceType().equals(dto.getSource())).findFirst();
basicDeviceDTO.orElseGet(() -> {
log.warn("该车辆绑定的主设备不存在");
throw new AdminException("该车辆绑定的主设备不存在");
});
// 通过设备号获取最后定位点
// 通过设备号获取设备类型
String sn = basicDeviceDTO.get().getSn();
Device device = deviceMapper.selectBySn(sn);
if (Objects.isNull(device)) {
log.warn("该设备不存在");
throw new AdminException("该设备不存在");
}
GpsBsData gpsBsData = remoteGpsBsService.getLastGpsBsBySn(device.getSn(), TypeConverseEnum.DeviceTypeEnum.getMiniStrByDeviceType(device.getDeviceType()));
if (Objects.isNull(gpsBsData)) {
log.warn(sn + "暂无定位数据");
throw new AdminException(sn + "暂无定位数据");
}
GpsLocation gpsLocation = gpsBsData.getGpsLocation();
if (Objects.isNull(gpsLocation)) {
log.warn(sn + "暂无GPS定位数据");
throw new AdminException(sn + "暂无GPS定位数据");
}
StayPointRequest request = new StayPointRequest();
request.setSn(sn);
// 查询时间段 全天
request.setPeriodType(0);
request.setBeginTime(DateUtil.getOffsetDayDate(DateUtil.parseDateYmd(gpsLocation.getDateTime()), 30));
request.setEndTime(DateUtil.getOffsetDayDate(DateUtil.parseDateYmd(gpsLocation.getDateTime()), -1));
List<StayPointRecordDTO> stayPointRecordList = remoteFeignStayPointService.getStayPointRecord(request);
if (CollectionUtils.isEmpty(stayPointRecordList)) {
log.warn(sn + "暂设备暂无历史停留点");
throw new AdminException(sn + "暂设备暂无历史停留点");
}
// 组装停留点轨迹数据
// 通过设备号查询车辆信息
List<Vehicle> vehicleInfoList = vehicleMapper.findVehicleInfoBySn(sn);
if (CollectionUtils.isEmpty(vehicleInfoList)) {
log.warn(sn + "暂设备绑定车辆数据不存在");
throw new AdminException(sn + "暂设备绑定车辆数据不存在");
}
Vehicle vehicle = vehicleInfoList.get(0);
//获取地址信息
List<LngLatDTO> lngLats = stayPointRecordList.stream().filter(e -> Objects.nonNull(e.getStayGps())).map(e -> new LngLatDTO(e.getStayGps().getElng(), e.getStayGps().getElat())).collect(Collectors.toList());
LngLatAddressDTO addressDTO = remoteGpsBsService.getAddressMap(lngLats);
Map<String, String> addressMap = Optional.ofNullable(addressDTO).map(LngLatAddressDTO::getAddress).orElse(Maps.newHashMap());
return stayPointRecordList.stream().map(stayPoint -> RiskAssessmentConvert.buildStayPointListVO(stayPoint, vehicle, sn, Optional.ofNullable(stayPoint.getStayGps()).map(e -> e.getElat() + e.getElng()).map(addressMap::get).orElse(Constants.EMPTY_CONTENT_EXCEL))).collect(Collectors.toList());
}
/**
* 获取车辆基础信息
*
* @param vehicleId 车辆ID
* @return 设备基础信息
*/
public BasicInformationVO getBasicInformation(Long vehicleId) {
if (Objects.isNull(vehicleId)) {
log.warn("该车辆ID为空");
throw new AdminException("该车辆ID为空");
}
BasicInformationVO basicInformationVO = new BasicInformationVO();
// 1 通过设备号获取门店以及车辆信息
BasicInformationDTO basicInformationDTO = vehicleMapper.getBasicInformationByVehicleId(vehicleId);
if (Objects.isNull(basicInformationDTO)) {
log.warn("该车辆信息为空");
throw new AdminException(vehicleId + "该车辆信息为空");
}
basicInformationVO.setLesseeName(basicInformationDTO.getLesseeName());
basicInformationVO.setLesseePhone(basicInformationDTO.getLesseePhone());
basicInformationVO.setShopName(basicInformationDTO.getShopName());
// 取组织层级一级名称
basicInformationVO.setUserName(organizationApiService.getFirstLevelOrgName(basicInformationDTO.getCreatedBy()));
basicInformationVO.setWorkOrderNo(basicInformationDTO.getWorkOrderNo());
basicInformationVO.setInstallationCity(basicInformationDTO.getInstallationCity());
basicInformationVO.setVin(basicInformationDTO.getVin());
basicInformationVO.setBrandName(basicInformationDTO.getBrandName());
basicInformationVO.setSeriesName(basicInformationDTO.getSeriesName());
basicInformationVO.setTypeName(basicInformationDTO.getTypeName());
basicInformationVO.setCreateTime(basicInformationDTO.getCreateTime());
// 通过设备号获取设备组合信息
String sns = basicInformationDTO.getSns();
String sources = basicInformationDTO.getSources();
String deviceTypes = basicInformationDTO.getDeviceTypes();
Map<String, Integer> snsMap = Maps.newHashMap();
List<String> snsList = Arrays.stream(sns.split(",")).collect(Collectors.toList());
List<Integer> sourceList = Arrays.stream(sources.split(",")).map(Integer::parseInt).collect(Collectors.toList());
List<Integer> deviceTypeList = Arrays.stream(deviceTypes.split(",")).map(Integer::parseInt).collect(Collectors.toList());
snsList.forEach(s -> snsMap.put(s, Objects.nonNull(deviceTypeList.get(snsList.indexOf(s))) ? deviceTypeList.get(snsList.indexOf(s)) : 8));
// 获取设备号对应的设备状态
Map<String, DeviceStatusModel> deviceStatusMap = remoteFeignDeviceService.getDeviceStatusBySns(snsMap);
// 获取设备号对应的定位信息
Map<String, GpsBsData> lastGpsBsBySnsMap = remoteGpsBsService.getLastGpsBsBySnsMap(snsMap);
List<DeviceInformationVO> deviceInformationVOList = Lists.newArrayList();
snsList.forEach(sn -> {
DeviceInformationVO deviceInformationVO = new DeviceInformationVO();
deviceInformationVO.setSn(sn);
deviceInformationVO.setSource(sourceList.get(snsList.indexOf(sn)));
deviceInformationVO.setSourceStr(TypeConverseEnum.SourceEnum.getStrBySourceType(sourceList.get(snsList.indexOf(sn))));
//设置设备状态
DeviceStatusModel statusModel = deviceStatusMap.get(sn);
if (statusModel != null) {
deviceInformationVO.setDeviceState(statusModel.getStatus());
String deviceStateStr = DeviceStatusEnum.getNameByCode(statusModel.getStatus());
if (StringUtils.isNotEmpty(statusModel.getStatusTime())) {
deviceStateStr = deviceStateStr.concat("(" + statusModel.getStatusTime() + ")");
}
deviceInformationVO.setDeviceStateStr(deviceStateStr);
} else {
deviceInformationVO.setDeviceState(DeviceStatusEnum.OFFLINE.getCode());
deviceInformationVO.setDeviceStateStr(DeviceStatusEnum.OFFLINE.getName());
}
deviceInformationVOList.add(deviceInformationVO);
GpsBsData gpsBsData = lastGpsBsBySnsMap.get(sn);
if (Objects.nonNull(gpsBsData)) {
log.info(sn + "===gpsBsData===" + JSONUtil.toJsonStr(gpsBsData));
GpsLocation gpsLocation = gpsBsData.getGpsLocation();
GpsLocation bsLocation = gpsBsData.getBsLocation();
if (Objects.nonNull(gpsLocation) && Objects.nonNull(bsLocation) && DateUtil.compareDate(gpsLocation.getDateTime(), bsLocation.getDateTime())) {
deviceInformationVO.setLng(gpsBsData.getGpsLocation().getLng());
deviceInformationVO.setLat(gpsBsData.getGpsLocation().getLat());
deviceInformationVO.setAddress(remoteGpsBsService.getAddressByLngAndLat(gpsBsData.getGpsLocation().getLng(), gpsBsData.getGpsLocation().getLat()));
} else if (Objects.nonNull(gpsLocation)) {
deviceInformationVO.setLng(gpsBsData.getGpsLocation().getLng());
deviceInformationVO.setLat(gpsBsData.getGpsLocation().getLat());
deviceInformationVO.setAddress(remoteGpsBsService.getAddressByLngAndLat(gpsBsData.getGpsLocation().getLng(), gpsBsData.getGpsLocation().getLat()));
} else if (Objects.nonNull(bsLocation)) {
deviceInformationVO.setLng(gpsBsData.getBsLocation().getLng());
deviceInformationVO.setLat(gpsBsData.getBsLocation().getLat());
deviceInformationVO.setAddress(remoteGpsBsService.getAddressByLngAndLat(gpsBsData.getBsLocation().getLng(), gpsBsData.getBsLocation().getLat()));
}
}
});
basicInformationVO.setDeviceInformationVOList(deviceInformationVOList);
return basicInformationVO;
}
public ResidentInformationVO getResidentInformation(Long vehicleId) {
if (Objects.isNull(vehicleId)) {
log.warn("该车辆ID不存在");
throw new AdminException("该车辆ID不存在");
}
// 通过车辆ID获取设备主有线设备
List<BasicDeviceDTO> basicDeviceDTOList = vehicleDeviceMapper.selectBindDeviceByVehicleIdOrderByCreatedDate(vehicleId);
log.info("basicDeviceDTOList===" + JSONUtil.toJsonStr(basicDeviceDTOList));
Optional<BasicDeviceDTO> basicDeviceDTO = basicDeviceDTOList.stream().filter(dto -> TypeConverseEnum.SourceEnum.HAS_SOURCE.getSourceType().equals(dto.getSource())).findFirst();
ResidentInformationVO residentInformationVO = new ResidentInformationVO();
boolean present = basicDeviceDTO.isPresent();
if (present) {
BasicDeviceDTO deviceDTO = basicDeviceDTO.get();
log.info("deviceDTO===" + JSONUtil.toJsonStr(deviceDTO));
// 设置常住地
List<ResidentDTO> residentList = remoteFeignResidentService.getResidentList(buildResidentRequest(deviceDTO.getSn()));
log.info(deviceDTO.getSn() + "===residentList===" + JSONUtil.toJsonStr(residentList));
if (CollectionUtils.isNotEmpty(residentList)) {
// 常驻地,是“截止目前”的条件,选驻留次数最多的那个
residentList.stream().min((o1, o2) -> o2.getTotalTimes() - o1.getTotalTimes()).ifPresent(residentDTO -> {
String addressByLngAndLat = remoteGpsBsService.getAddressByLngAndLat(residentDTO.getElng(), residentDTO.getElat());
residentInformationVO.setResidence(addressByLngAndLat);
});
}
// 添加预测家庭地址和预测工作地址
DeviceStayOften deviceStayOften = deviceStayOftenMapper.selectOneBySn(deviceDTO.getSn());
log.info(deviceDTO.getSn() + "===deviceStayOften===" + JSONUtil.toJsonStr(deviceStayOften));
if (Objects.nonNull(deviceStayOften)) {
residentInformationVO.setHomeAddress(deviceStayOften.getHomeAddress());
residentInformationVO.setWorkAddress(deviceStayOften.getWorkAddress());
}
}
return residentInformationVO;
}
/**
* 构建 request
*/
private ResidentRequest buildResidentRequest(String sn) {
//2为无源设备查询基站;1为有源设备查询GPS
Device device = deviceMapper.selectBySn(sn);
VehicleDevice vehicleDevice = vehicleDeviceMapper.selectBindDeviceBySn(sn);
boolean isGps = Objects.isNull(device) || Objects.equals(device.getSource(), 1);
int lacType = isGps ? 1 : 2;
Date deviceActivateTime = Optional.ofNullable(vehicleDevice).map(VehicleDevice::getCreatedDate).orElse(new Date());
//ICE接口查询常驻地列表
return RiskAssessmentConvert.buildResidentRequest(sn, DateUtil.formatDate(deviceActivateTime), DateUtil.getNowDateTimeFormat(), lacType);
}
/**
* 查询设备号警情风控登记数据
*
* @param vehicleId 车辆ID
* @return 风控登记数据
*/
public List<AlarmInformationVO> getAlarmInformation(Long vehicleId) {
// 校验车架号
if (Objects.isNull(vehicleId)) {
log.warn("该车辆ID不存在");
throw new AdminException("该车辆ID不存在");
}
// 通过车辆ID获取设备主有线设备
List<BasicDeviceDTO> basicDeviceDTOList = vehicleDeviceMapper.selectBindDeviceByVehicleIdOrderByCreatedDate(vehicleId);
Optional<BasicDeviceDTO> basicDeviceDTO = basicDeviceDTOList.stream().filter(dto -> TypeConverseEnum.SourceEnum.HAS_SOURCE.getSourceType().equals(dto.getSource())).findFirst();
basicDeviceDTO.orElseGet(() -> {
log.warn("该车辆绑定的主设备不存在");
throw new AdminException("该车辆绑定的主设备不存在");
});
Set<AlarmInformationVO> basicAlarmDTOSet = Sets.newHashSet();
// 防拆报警 需要统计所有设备 只有有一个设备有报警 则报风险等级
List<String> snList = basicDeviceDTOList.stream().map(BasicDeviceDTO::getSn).collect(Collectors.toList());
log.info("snList===" + JSONUtil.toJsonStr(snList));
Integer tearDownAlarmNum = remoteAlarmService.countAlarmRec(snList, Constants.TEAR_DOWN_ALARM_TYPE);
log.info("tearDownAlarmNum===" + tearDownAlarmNum);
if (tearDownAlarmNum > 0) {
basicAlarmDTOSet.add(new AlarmInformationVO("防拆报警", 1, "建议电呼或者家访", RiskAlarmTypeEnum.getAlarmRankByAlarmName("防拆报警")));
}
Integer powerOffAlarmNum = remoteAlarmService.countAlarmRec(snList, Constants.POWER_OFF_ALARM_TYPE);
log.info("powerOffAlarmNum===" + powerOffAlarmNum);
if (powerOffAlarmNum > 0) {
basicAlarmDTOSet.add(new AlarmInformationVO("防拆报警", 1, "建议电呼或者家访", RiskAlarmTypeEnum.getAlarmRankByAlarmName("防拆报警")));
}
// 高危区域内长停 警情中心警情
List<AlarmWarnAnalyse> alarmWarnAnalyseList = alarmWarnAnalyseMapper.selectByVehicleId(vehicleId);
log.info("alarmWarnAnalyseList===" + JSONUtil.toJsonStr(alarmWarnAnalyseList));
alarmWarnAnalyseList.forEach(alarmWarnAnalyse -> basicAlarmDTOSet.add(new AlarmInformationVO(alarmWarnAnalyse.getAlarmExplain(), alarmWarnAnalyse.getAlarmLevel(), alarmWarnAnalyse.getAlarmSuggest(), RiskAlarmTypeEnum.getAlarmRankByAlarmName(alarmWarnAnalyse.getAlarmExplain()))));
// 聚集报警
List<StuJudgeAlarmDto> aggregationAlarmDataList = remoteStuJudgeAlarmService.getStuJudgeAlarmDataList(snList, StuAlarmTypeEnum.ABNORMAL_AGGREGATION.getCode());
log.info("aggregationAlarmDataList===" + JSONUtil.toJsonStr(aggregationAlarmDataList));
if (CollectionUtils.isNotEmpty(aggregationAlarmDataList)) {
basicAlarmDTOSet.add(new AlarmInformationVO("聚集报警", 1, "建议核实用车情况", RiskAlarmTypeEnum.getAlarmRankByAlarmName("聚集报警")));
}
// 黑区报警
List<StuJudgeAlarmDto> blackAreaAlarmDatalist = remoteStuJudgeAlarmService.getStuJudgeAlarmDataList(snList, StuAlarmTypeEnum.BLACK_AREA.getCode());
log.info("blackAreaAlarmDatalist===" + JSONUtil.toJsonStr(blackAreaAlarmDatalist));
if (CollectionUtils.isNotEmpty(blackAreaAlarmDatalist)) {
basicAlarmDTOSet.add(new AlarmInformationVO("黑区报警", 1, "建议核实用车情况", RiskAlarmTypeEnum.getAlarmRankByAlarmName("黑区报警")));
}
// 计算真离线
calculateTrueOffline(vehicleId, snList, basicAlarmDTOSet);
log.info("basicAlarmDTOSet===" + JSONUtil.toJsonStr(blackAreaAlarmDatalist));
Map<Integer, List<AlarmInformationVO>> alarmInformationVOMap = basicAlarmDTOSet.stream().sorted(Comparator.comparingInt(AlarmInformationVO::getAlarmLevel)).collect(Collectors.groupingBy(AlarmInformationVO::getAlarmLevel));
log.info("alarmInformationVOMap===" + JSONUtil.toJsonStr(alarmInformationVOMap));
List<AlarmInformationVO> alarmInformationVOResultList = Lists.newArrayList();
alarmInformationVOMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
List<AlarmInformationVO> valueList = entry.getValue();
log.info("valueList===" + JSONUtil.toJsonStr(valueList));
alarmInformationVOResultList.addAll(valueList.stream().sorted(Comparator.comparingInt(AlarmInformationVO::getAlarmRank)).collect(Collectors.toCollection(LinkedHashSet::new)));
});
return alarmInformationVOResultList;
}
/**
* 计算真离线
*/
private void calculateTrueOffline(Long vehicleId, List<String> snList, Set<AlarmInformationVO> basicAlarmDTOSet) {
// 离线时间计算
String OfflineStartTime = DateUtil.formatDate(DateUtils.addHours(new Date(), -72));
// 判断是否是离线
List<OfflineExport> offlineExportList = vehicleMapper.findOfflineDataByVehicleId(vehicleId, OfflineStartTime);
log.info("offlineExportList===" + JSONUtil.toJsonStr(offlineExportList));
if (CollectionUtils.isEmpty(offlineExportList)) {
// 为空表示没有离线数据
log.info("offlineExportList is null");
return;
}
// 判断是否是假性离线
List<String> vinList = offlineExportList.stream().map(OfflineExport::getVin).collect(Collectors.toList());
// 假性离线的三种情况
Boolean flag = Boolean.TRUE;
// 一 获取设备都离线 最后定位点在家庭围栏或者工作地围栏 获取车架通过权限控制 当存在设备都离线的车辆时才进行计算
log.info("offlineExportList.size() ===" + offlineExportList.size());
log.info("snList.size() ===" + snList.size());
if (offlineExportList.size() == snList.size()) {
List<String> fakeOfflineVinList = fakeOfflineVinMapper.getFakeOfflineVinByFence(vinList);
if (CollectionUtils.isNotEmpty(fakeOfflineVinList)) {
log.info("fakeOfflineVinList is not null" + JSONUtil.toJsonStr(fakeOfflineVinList));
flag = Boolean.FALSE;
}
}
// 二 十日内状态反复变化 假性离线
List<FakeOfflineChangeFrequently> changeFrequentlyList = fakeOfflineChangeFrequentlyMapper.listByVin(vinList);
if (CollectionUtils.isNotEmpty(changeFrequentlyList)) {
log.info("changeFrequentlyList is not null" + JSONUtil.toJsonStr(changeFrequentlyList));
flag = Boolean.FALSE;
}
// 三 获取本部门以及下级部门的白名单
Set<Long> deptIds = organizationApiService.getAllSubOrgIds();
log.info("userId:" + ShieldContextHolder.getUserId() + ";deptIds:" + JSONUtil.toJsonStr(deptIds));
// 从白名单列表获取白名单设备号及其车架号
List<String> writeListVinList = whitelistSnMapper.getWriteListVinListAndDeptIds(deptIds, vinList);
// 白名单不为空 并且白名单包括车架号
if (CollectionUtils.isNotEmpty(writeListVinList) && writeListVinList.containsAll(vinList)) {
log.info("writeListVinList is not null" + JSONUtil.toJsonStr(writeListVinList));
flag = Boolean.FALSE;
}
// 判断是否是真离线
if (flag) {
basicAlarmDTOSet.add(new AlarmInformationVO("离线报警", 3, "建议核实用车情况", RiskAlarmTypeEnum.getAlarmRankByAlarmName("离线报警")));
}
}
/**
* 进行用户行为数据查询
*
* @param vehicleId 车辆ID
* @return
*/
public UserBehaviorInformationVO getUserBehaviorInformation(Long vehicleId) {
// 校验车架号
if (Objects.isNull(vehicleId)) {
log.warn("该车辆ID不存在");
throw new AdminException("该车辆ID不存在");
}
// 通过车辆ID获取设备主有线设备
List<BasicDeviceDTO> basicDeviceDTOList = vehicleDeviceMapper.selectBindDeviceByVehicleIdOrderByCreatedDate(vehicleId);
Optional<BasicDeviceDTO> basicDeviceDTO = basicDeviceDTOList.stream().filter(dto -> TypeConverseEnum.SourceEnum.HAS_SOURCE.getSourceType().equals(dto.getSource())).findFirst();
UserBehaviorInformationVO userBehaviorInformationVO = new UserBehaviorInformationVO();
if (basicDeviceDTO.isPresent()) {
// 获取主设备
String sn = basicDeviceDTO.get().getSn();
List<UserBehaviorWeekDTO> userBehaviorWeekDTOList = deviceJourneyMapper.statisticsDeviceJourneyWithWeek(sn);
// 获取最大的年数
Integer maxYearInt = userBehaviorWeekDTOList.stream().map(UserBehaviorWeekDTO::getYearInt).max(Integer::compareTo).orElse(0);
log.info(sn + "===maxYearInt===" + maxYearInt);
// 获取最小的年份
Integer minYearInt = userBehaviorWeekDTOList.stream().map(UserBehaviorWeekDTO::getYearInt).min(Integer::compareTo).orElse(0);
// 获取最大年数的最大的周数
Integer maxWeekInt = userBehaviorWeekDTOList.stream().filter(item -> Objects.equals(item.getYearInt(), maxYearInt)).map(UserBehaviorWeekDTO::getWeekInt).max(Integer::compareTo).orElse(0);
log.info(sn + "===maxWeekInt===" + maxWeekInt);
// 获取最大年数的最小的周数
Integer minWeekInt = userBehaviorWeekDTOList.stream().filter(item -> Objects.equals(item.getYearInt(), maxYearInt)).map(UserBehaviorWeekDTO::getWeekInt).min(Integer::compareTo).orElse(0);
log.info(sn + "===minWeekInt===" + minWeekInt);
// 如果数据不满一周 则按照每日数量进行统计
if (Objects.equals(maxYearInt, minYearInt) && Objects.equals(maxWeekInt, minWeekInt)) {
userBehaviorInformationVO.setStatisticsType(2);
List<UserBehaviorDayDTO> userBehaviorDayDTOList = deviceJourneyMapper.statisticsDeviceJourneyWithDay(sn);
// 获取最大的天数
Integer maxDayInt = userBehaviorDayDTOList.stream().map(UserBehaviorDayDTO::getDayInt).max(Integer::compareTo).orElse(0);
// 获取最小的天数
Integer minDayInt = userBehaviorDayDTOList.stream().map(UserBehaviorDayDTO::getDayInt).min(Integer::compareTo).orElse(0);
userBehaviorInformationVO.setUserBehaviorDayDTOList(getUserBehaviorDayList(userBehaviorDayDTOList, minDayInt, maxDayInt));
return userBehaviorInformationVO;
}
// 如果最多的周数减去18周 和最小的周进行对比
userBehaviorInformationVO.setStatisticsType(1);
// 用0填充数据
List<UserBehaviorWeekDTO> newUserBehaviorWeekList = Lists.newArrayList();
userBehaviorWeekDTOList.stream().collect(Collectors.groupingBy(UserBehaviorWeekDTO::getYearInt)).forEach((year, tempUserBehaviorWeekList) -> {
int maxWeekOfYear = DateUtil.getMaxWeekOfYear(year);
log.info(sn + "===year===" + year + "===maxWeekOfYear===" + maxWeekOfYear);
Map<Integer, UserBehaviorWeekDTO> tempUserBehaviorWeekMap = tempUserBehaviorWeekList.stream().collect(Collectors.toMap(UserBehaviorWeekDTO::getWeekInt, Function.identity(), (o, n) -> n));
log.info(sn + "===tempUserBehaviorWeekMap===" + JSONUtil.toJsonStr(tempUserBehaviorWeekMap));
// 最大的年 则使用最大的周计算即刻
if (Objects.equals(year, maxYearInt)) {
maxWeekOfYear = maxWeekInt;
}
for (int i = 0; i < maxWeekOfYear + 1; i++) {
UserBehaviorWeekDTO tempUserBehaviorWeekDTO = tempUserBehaviorWeekMap.getOrDefault(i, new UserBehaviorWeekDTO(year, i, 0));
newUserBehaviorWeekList.add(tempUserBehaviorWeekDTO);
}
});
log.info(sn + "===newUserBehaviorWeekList===" + JSONUtil.toJsonStr(newUserBehaviorWeekList));
int size = CollectionUtils.isNotEmpty(newUserBehaviorWeekList) ? newUserBehaviorWeekList.size() : 0;
if (size < 18) {
userBehaviorInformationVO.setUserBehaviorWeekDTOList(getUserBehaviorWeekList(newUserBehaviorWeekList));
} else {
userBehaviorInformationVO.setUserBehaviorWeekDTOList(getUserBehaviorWeekList(newUserBehaviorWeekList.stream().skip(newUserBehaviorWeekList.size() - 18).collect(Collectors.toList())));
}
}
return userBehaviorInformationVO;
}
private List<UserBehaviorWeekDTO> getUserBehaviorWeekList(List<UserBehaviorWeekDTO> userBehaviorWeekDTOList) {
boolean anyMatch = userBehaviorWeekDTOList.stream().anyMatch(item -> item.getWeekNum() > 0);
if (!anyMatch) {
return Lists.newArrayList();
}
return userBehaviorWeekDTOList;
}
private List<UserBehaviorDayDTO> getUserBehaviorDayList(List<UserBehaviorDayDTO> userBehaviorWeekDTOList, Integer minDayInt, Integer maxDayInt) {
List<UserBehaviorDayDTO> userBehaviorDayNewList = Lists.newArrayList();
Integer maxMonthInt = userBehaviorWeekDTOList.stream().map(UserBehaviorDayDTO::getMonthInt).max(Integer::compareTo).orElse(0);
Map<Integer, UserBehaviorDayDTO> userBehaviorDayDTOMap = userBehaviorWeekDTOList.stream().collect(Collectors.toMap(UserBehaviorDayDTO::getDayInt, Function.identity(), (o, n) -> n));
log.info("userBehaviorDayDTOMap===" + JSONUtil.toJsonStr(userBehaviorDayDTOMap));
for (int i = minDayInt; i < maxDayInt + 1; i++) {
UserBehaviorDayDTO userBehaviorDayNum = userBehaviorDayDTOMap.getOrDefault(i, new UserBehaviorDayDTO(0, maxMonthInt, 0, 0));
userBehaviorDayNewList.add(new UserBehaviorDayDTO(userBehaviorDayNum.getYearInt(), userBehaviorDayNum.getMonthInt(), i, userBehaviorDayNum.getDayNum()));
}
// 如果集合全部为0 则返回空数据
boolean anyMatch = userBehaviorDayNewList.stream().anyMatch(item -> item.getDayNum() > 0);
if (!anyMatch) {
return Lists.newArrayList();
}
return userBehaviorDayNewList;
}
/**
* TODO 注意:1、调用所有第三方接口要添加日志记录 2、中间所有警情都取生效中的
*
* @param vehicleId
* @return
*/
public List<AlarmTimeLinePointVo> getAlarmTimeLine(Long vehicleId) {
// 查询工单入库时间
Vehicle vehicle = vehicleMapper.selectById(vehicleId);
if (Objects.isNull(vehicle)) {
throw new AdminException("车辆不存在");
}
List<BasicDeviceDTO> devices = vehicleDeviceMapper.selectBindDeviceByVehicleIdOrderByCreatedDate(vehicleId);
List<String> snList = devices.stream().map(device -> device.getSn()).collect(Collectors.toList());
Map<String, String> snDeviceNameMap = new HashMap<>();
int wireTypeNum = 1;
int wireLessTypeNum = 1;
for (BasicDeviceDTO device : devices) {
Integer type = device.getSource();
String typeName = TypeConverseEnum.SourceEnum.getStrBySourceType(type);
if (type.equals(TypeConverseEnum.SourceEnum.HAS_SOURCE.getSourceType())) {
snDeviceNameMap.put(device.getSn(), typeName + wireTypeNum);
wireTypeNum++;
} else {
snDeviceNameMap.put(device.getSn(), typeName + wireLessTypeNum);
wireLessTypeNum++;
}
}
// 查询大数据研判警情:黑区、聚集
List<AlarmTimeLinePointVo> alarmInfoList = Lists.newArrayList();
log.info("查询大数据研判警情 请求参数:{}", JSONUtil.toJsonStr(snList));
List<StuJudgeAlarmDto> stuJudgeAlarmList = remoteStuJudgeAlarmService.selectLatestAlarmOfEachType(snList);
log.info("查询大数据研判警情 请求结果:{}", JSONUtil.toJsonStr(stuJudgeAlarmList));
stuJudgeAlarmList.forEach(alarm -> {
AlarmTimeLinePointVo pointVo = new AlarmTimeLinePointVo();
pointVo.setAlarmType(TypeConverseEnum.AlarmTypeEnum.getStrByAlarmType(alarm.getAlarmType()));
pointVo.setAlarmTime(alarm.getAlarmEndTime());
pointVo.setDevice(snDeviceNameMap.get(alarm.getSn()));
pointVo.setAlarmLevel(1);
alarmInfoList.add(pointVo);
});
// 查询防拆警情:断电、光感、翻转
// TODO 接口测试,生效中的警情,只有开始时间没有结束时间
log.info("查询防拆警情 请求参数:{}", JSONUtil.toJsonStr(snList));
List<CommonAlarmDto> tearDownAlarmList = remoteAlarmService.selectLatestAlarmOfEachType(snList);
log.info("查询防拆警情 请求结果:{}", JSONUtil.toJsonStr(tearDownAlarmList));
if (CollectionUtils.isNotEmpty(tearDownAlarmList)) {
tearDownAlarmList.forEach(alarm -> {
AlarmTimeLinePointVo pointVo = new AlarmTimeLinePointVo();
pointVo.setAlarmLevel(1);
pointVo.setAlarmTime(alarm.getBeginTime());
pointVo.setDevice(snDeviceNameMap.get(alarm.getSn()));
pointVo.setAlarmType(TypeConverseEnum.AlarmRecTypeEnum.getStrByAlarmType(alarm.getAlarmType()));
alarmInfoList.add(pointVo);
});
}
// 查询离线警情
getOffLinePoint(snList, alarmInfoList, snDeviceNameMap);
// 查询警情研判:多种警情
List<AlarmWarnAnalyse> alarmWarnAnalyseList = alarmWarnAnalyseMapper.selectLatestAlarmOfEachType(vehicleId);
if (CollectionUtils.isNotEmpty(alarmWarnAnalyseList)) {
alarmWarnAnalyseList.forEach(alarm -> {
AlarmTimeLinePointVo pointVo = new AlarmTimeLinePointVo();
pointVo.setAlarmLevel(alarm.getAlarmLevel());
pointVo.setAlarmTime(DateUtil.formatDate(alarm.getAlarmTime()));
pointVo.setAlarmType(alarm.getAlarmExplain());
String[] snArr = alarm.getDeviceNoes().split(";");
for (String sn : snArr) {
if (snDeviceNameMap.containsKey(sn)) {
pointVo.setDevice(snDeviceNameMap.get(sn));
break;
}
}
alarmInfoList.add(pointVo);
});
}
// 警情按触发时间顺序排序,再按等级优先级排序
Comparator<AlarmTimeLinePointVo> comparator = (e1, e2) -> {
Date date1 = DateUtil.parseDate(e1.getAlarmTime());
Date date2 = DateUtil.parseDate(e2.getAlarmTime());
if (date1.equals(date2)) {
return Integer.compare(e1.getAlarmLevel(), e2.getAlarmLevel());
} else {
return date1.compareTo(date2);
}
};
alarmInfoList.sort(comparator);
// 获取录入时间节点
WorkOrder workOrder = workOrderMapper.selectById(vehicle.getWorkOrderId());
AlarmTimeLinePointVo firstPoint = new AlarmTimeLinePointVo();
firstPoint.setAlarmType("录入时间");
firstPoint.setAlarmTime(DateUtil.formatDate(workOrder.getCreatedDate()));
alarmInfoList.add(0, firstPoint);
// 获取最后检测时间节点
getLatestCheckPoint(alarmInfoList, vehicle, snDeviceNameMap);
return alarmInfoList;
}
/**
* 获取最后检测时间节点
*
* @param alarmInfoList
* @param vehicle
*/
private void getLatestCheckPoint(List<AlarmTimeLinePointVo> alarmInfoList, Vehicle vehicle, Map<String, String> snDeviceNameMap) {
FinalPositioningSearch search = new FinalPositioningSearch();
search.setKeywords(vehicle.getVin());
search.setPageNumber(1);
search.setPageSize(10);
List<FinalPositioningExport> finalPositioningList = finalPositioningService.findFinalPositioningList(search);
if (CollectionUtils.isEmpty(finalPositioningList)) {
return;
}
// 时间排序
TreeMap<String, String> sortedMap = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.YMDHMS);
try {
Date time1 = sdf.parse(o1);
Date time2 = sdf.parse(o2);
// 倒序排序
return time2.compareTo(time1);
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid time format", e);
}
}
});
for (FinalPositioningExport position : finalPositioningList) {
String sn = position.getSn();
String lastPoiTime = position.getLastPoiTime();
if (StringUtils.isNotBlank(lastPoiTime)) {
sortedMap.put(lastPoiTime, sn);
}
}
AlarmTimeLinePointVo lastPoint = new AlarmTimeLinePointVo();
lastPoint.setAlarmType("最后检测");
if (sortedMap.size() == 0) {
String sn = finalPositioningList.get(0).getSn();
lastPoint.setDevice(snDeviceNameMap.get(sn));
} else {
Map.Entry<String, String> firstEntry = sortedMap.firstEntry();
String time = firstEntry.getKey();
String sn = firstEntry.getValue();
lastPoint.setAlarmTime(time);
lastPoint.setDevice(snDeviceNameMap.get(sn));
}
alarmInfoList.add(lastPoint);
}
/**
* 获取离线警情
*
* @param snList
* @param alarmInfoList
*/
private void getOffLinePoint(List<String> snList, List<AlarmTimeLinePointVo> alarmInfoList, Map<String, String> snDeviceNameMap) {
List<DeviceLocation> deviceLocationList = deviceLocationMapper.findLocationListBySnList(snList);
if (CollectionUtils.isEmpty(deviceLocationList)) {
return;
}
// 是否离线判断 前三天时间范围内存在上报记录则不算离线
for (DeviceLocation location : deviceLocationList) {
Date date = DateUtils.addDays(new Date(), -3);
Date lastGpsTime = location.getLastGpsTime();
if (Objects.nonNull(lastGpsTime) && lastGpsTime.compareTo(date) > 0) {
return;
}
Date lastBsTime = location.getLastBsTime();
if (Objects.nonNull(lastBsTime) && lastBsTime.compareTo(date) > 0) {
return;
}
}
// 取基准时间
Date latestTime = null;
String alarmSn = null;
for (DeviceLocation location : deviceLocationList) {
Date lastGpsTime = location.getLastGpsTime();
if (Objects.nonNull(lastGpsTime)) {
latestTime = lastGpsTime;
alarmSn = location.getSn();
break;
}
Date lastBsTime = location.getLastBsTime();
if (Objects.nonNull(lastBsTime)) {
latestTime = lastBsTime;
alarmSn = location.getSn();
break;
}
}
// 不存在基准时间则以第一个设备为准
if (Objects.isNull(latestTime)) {
AlarmTimeLinePointVo pointVo = new AlarmTimeLinePointVo();
pointVo.setAlarmLevel(3);
pointVo.setAlarmType("离线报警");
String sn = deviceLocationList.get(0).getSn();
pointVo.setDevice(snDeviceNameMap.get(sn));
alarmInfoList.add(pointVo);
return;
}
// 取最近上报时间点
for (DeviceLocation location : deviceLocationList) {
Date lastGpsTime = location.getLastGpsTime();
if (Objects.nonNull(lastGpsTime) && lastGpsTime.compareTo(latestTime) > 0) {
latestTime = lastGpsTime;
alarmSn = location.getSn();
}
Date lastBsTime = location.getLastBsTime();
if (Objects.nonNull(lastBsTime) && lastBsTime.compareTo(latestTime) > 0) {
latestTime = lastBsTime;
alarmSn = location.getSn();
}
}
AlarmTimeLinePointVo pointVo = new AlarmTimeLinePointVo();
pointVo.setAlarmLevel(3);
pointVo.setAlarmTime(DateUtil.formatDate(latestTime));
pointVo.setAlarmType("离线报警");
pointVo.setDevice(snDeviceNameMap.get(alarmSn));
alarmInfoList.add(pointVo);
}
private static List<FinalPositioningExport> customSort(List<FinalPositioningExport> finalPositioningList) {
return finalPositioningList.stream()
.sorted(Comparator.comparing(
FinalPositioningExport::getLastPoiTime,
(time1, time2) -> {
if (Objects.isNull(time1) && Objects.isNull(time2)) {
return 0;
}
if (Objects.isNull(time1)) {
return -1;
}
if (Objects.isNull(time2)) {
return 1;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1 = LocalDateTime.parse(time1, formatter);
LocalDateTime dateTime2 = LocalDateTime.parse(time2, formatter);
return dateTime2.compareTo(dateTime1);
})
)
.collect(Collectors.toList());
}
public VehicleUsageAnalysisVO usageAnalysis(Long vehicleId) {
VehicleUsageAnalysisVO analysisVO = new VehicleUsageAnalysisVO();
//每日平均里程数
String sn = vehicleDeviceMapper.getEarliestWireDeviceSn(vehicleId);
log.info("sn:{}", sn);
Example overviewExample = new Example.Builder(DeviceJourneyOverview.class).where(WeekendSqls.<DeviceJourneyOverview>custom()
.andEqualTo(DeviceJourneyOverview::getSn, sn).andEqualTo(DeviceJourneyOverview::getDelFlag, 0)).build();
DeviceJourneyOverview overview = deviceJourneyOverviewMapper.selectOneByExample(overviewExample);
//激活日期
Date activeDate =vehicleMapper.getActiveDate(vehicleId);
if (!Objects.isNull(overview)) {
int activeDays = (int) cn.hutool.core.date.DateUtil.between(activeDate, DateUtils.addDays(new Date(), -1), DateUnit.DAY);
Integer distance = overview.getDistance();
double average = distance/1000.0/activeDays;
int tempAverage = (int) (average * 1000);
analysisVO.setAverage(tempAverage/1000.0);
} else {
analysisVO.setAverage(0.000);
}
//超过全平台百分比车主
int percentage = 100;
if (!Objects.isNull(overview)) {
List<Long> vehicleDeviceIds = vehicleDeviceMapper.getVehicleEarliestWireDeviceIdsByPermit();
Example vdExample = new Example.Builder(VehicleDevice.class).where(WeekendSqls.<VehicleDevice>custom()
.andIn(VehicleDevice::getId, vehicleDeviceIds)).build();
List<VehicleDevice> devices = vehicleDeviceMapper.selectByExample(vdExample);
List<String> snList = devices.stream().map(VehicleDevice::getSn).collect(Collectors.toList());
Example allOverviewExample = new Example.Builder(DeviceJourneyOverview.class)
.where(WeekendSqls.<DeviceJourneyOverview>custom()
.andIn(DeviceJourneyOverview::getSn, snList).andEqualTo(DeviceJourneyOverview::getDelFlag, 0))
.orderByDesc("distance").build();
List<DeviceJourneyOverview> overviews = deviceJourneyOverviewMapper.selectByExample(allOverviewExample);
List<Integer> allDistance = overviews.stream().map(DeviceJourneyOverview::getDistance).collect(Collectors.toList());
// TODO 取小数点
percentage = ((allDistance.indexOf(overview.getDistance()) + 1) * 100) / snList.size();
analysisVO.setPercentage(100 - percentage);
} else {
analysisVO.setPercentage(0);
}
//用车活跃度
if (percentage <= 33) {
analysisVO.setLevel(3);
analysisVO.setTips("建议电呼,核实用车行为");
} else if (percentage <= 66) {
analysisVO.setLevel(2);
analysisVO.setTips("重点观察");
} else {
analysisVO.setLevel(1);
analysisVO.setTips("继续观察");
}
//用车天数 最后定位日期-激活日期
Vehicle vehicle = vehicleMapper.selectById(vehicleId);
FinalPositioningSearch search = new FinalPositioningSearch();
search.setKeywords(vehicle.getVin());
search.setPageNumber(1);
search.setPageSize(10);
List<FinalPositioningExport> finalPositioningList = finalPositioningService.findFinalPositioningList(search);
if (CollectionUtils.isNotEmpty(finalPositioningList)) {
Map<String, FinalPositioningExport> snLocationMap = finalPositioningList.stream().collect(Collectors.toMap(FinalPositioningExport::getSn, Function.identity(), (o, n) -> n));
FinalPositioningExport finalPosition = snLocationMap.get(sn);
if (Objects.nonNull(finalPosition) && !StringUtils.isEmpty(finalPosition.getLastPoiTime())) {
int daysOfUsage = (int) cn.hutool.core.date.DateUtil.between(activeDate, DateUtil.parseDate(finalPosition.getLastPoiTime()), DateUnit.DAY);
analysisVO.setDays(daysOfUsage);
}
}
if (Objects.isNull(analysisVO.getDays())) {
analysisVO.setDays(0);
}
//日里程
List<VehicleUsageAnalysisPointVO> mileage = deviceJourneyMapper.statisMileageBySnGroupByDate(sn);
if (CollectionUtils.isNotEmpty(mileage)) {
String firstDateStr = mileage.get(0).getX();
String lastDateStr = mileage.get(mileage.size() - 1).getX();
if (DateUtil.isSameWeek(DateUtil.parseDateYmd(firstDateStr), DateUtil.parseDateYmd(lastDateStr))) {
mileage = fillBlankDate(mileage, DateUtil.getFirstDateOfWeek(DateUtil.parseDateYmd(firstDateStr)), DateUtil.getLastDateOfWeek(DateUtil.parseDateYmd(firstDateStr)), 1);
analysisVO.setMileage(mileage);
return analysisVO;
} else {
mileage = fillBlankDate(mileage, DateUtil.getFirstDateOfWeek(DateUtil.parseDateYmd(firstDateStr)), DateUtil.getLastDateOfWeek(DateUtil.parseDateYmd(lastDateStr)), 1);
analysisVO.setMileage(mileage);
}
// 周用车天数
List<VehicleUsageAnalysisPointVO> usage = deviceJourneyMapper.statisUsageBySnGroupByWeek(sn);
String firstWeek = usage.get(0).getX();
String lastWeek = usage.get(usage.size() - 1).getX();
usage = fillBlankDate(usage, DateUtil.parseDateYmd(firstWeek), DateUtil.parseDateYmd(lastWeek), 7);
analysisVO.setDaysOfVehicle(usage);
} else {
analysisVO.setMileage(Lists.newArrayList());
analysisVO.setDaysOfVehicle(Lists.newArrayList());
}
return analysisVO;
}
/**
* 根据步长填充前后日期之间缺少的数据
*
* @param points
* @param startDate
* @param endDate
* @param factor
* @return
*/
private List<VehicleUsageAnalysisPointVO> fillBlankDate(List<VehicleUsageAnalysisPointVO> points, Date startDate, Date endDate, int factor) {
long between = cn.hutool.core.date.DateUtil.between(startDate, endDate, DateUnit.DAY);
//间隔大于12周则设置开始日期和节数日期间隔为12周,否则不调整
if (between > 12 * 7) {
if (factor == 1) {
startDate = DateUtil.addDays(endDate, -12 * 7 + 1);
} else if (factor == 7) {
startDate = DateUtil.addDays(endDate, -11 * 7);
}
}
List<VehicleUsageAnalysisPointVO> resultList = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
for (; startDate.before(endDate);) {
map.put(DateUtil.formatDateYmd(startDate), 0);
startDate = DateUtils.addDays(startDate, factor);
}
map.put(DateUtil.formatDateYmd(endDate), 0);
Map<String, Integer> mapTemp = points.stream().collect(Collectors.toMap(VehicleUsageAnalysisPointVO::getX, VehicleUsageAnalysisPointVO::getY));
map.forEach((k, v) -> {
if (mapTemp.containsKey(k)) {
resultList.add(new VehicleUsageAnalysisPointVO(k, mapTemp.get(k)));
} else {
resultList.add(new VehicleUsageAnalysisPointVO(k, v));
}
});
resultList.sort(Comparator.comparing(o -> DateUtil.parseDateYmd(o.getX())));
return resultList;
}
}