jinpengyong
2022-01-17 3ddfa12fbc43e80e99e4959fbac8881eaa8e3ca3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
package com.moral.api.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moral.api.config.properties.SpecialCitiesProperties;
import com.moral.api.entity.CityAqi;
import com.moral.api.entity.CityAqiDaily;
import com.moral.api.entity.CityAqiMonthly;
import com.moral.api.entity.CityAqiYearly;
import com.moral.api.entity.Forecast;
import com.moral.api.entity.Organization;
import com.moral.api.entity.SysArea;
import com.moral.api.mapper.CityAqiMapper;
import com.moral.api.mapper.ForecastMapper;
import com.moral.api.pojo.dto.cityAQI.CityPollutionLevel;
import com.moral.api.pojo.dto.cityAQI.ConcentrationAndPercent;
import com.moral.api.pojo.form.aqi.AirQualityComparisonForm;
import com.moral.api.pojo.vo.cityAQI.AirQualityComparisonVO;
import com.moral.api.service.CityAqiDailyService;
import com.moral.api.service.CityAqiMonthlyService;
import com.moral.api.service.CityAqiService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moral.api.service.CityAqiYearlyService;
import com.moral.api.service.OrganizationService;
import com.moral.api.service.SysAreaService;
import com.moral.constant.Constants;
import com.moral.constant.RedisConstants;
import com.moral.pojo.AQI;
import com.moral.util.AQIUtils;
import com.moral.util.AmendUtils;
import com.moral.util.ComprehensiveIndexUtils;
import com.moral.util.DateUtils;
 
import com.moral.util.MathUtils;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
 
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
 
/**
 * <p>
 * 城市aqi实测小时数据表 服务实现类
 * </p>
 *
 * @author moral
 * @since 2021-09-28
 */
@Service
public class CityAqiServiceImpl extends ServiceImpl<CityAqiMapper, CityAqi> implements CityAqiService {
 
    @Autowired
    private CityAqiMapper cityAqiMapper;
 
    @Autowired
    private ForecastMapper forecastMapper;
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Autowired
    private SysAreaService sysAreaService;
 
    @Autowired
    private CityAqiDailyService cityAqiDailyService;
 
    @Autowired
    private CityAqiMonthlyService cityAqiMonthlyService;
 
    @Autowired
    private CityAqiYearlyService cityAqiYearlyService;
 
    @Autowired
    private SpecialCitiesProperties specialCitiesProperties;
 
    @Override
    public List<Map<String, Object>> measuredCompareForecastOfO3(Map<String, Object> params) {
        String regionCode = params.get("regionCode").toString();
        String time = params.get("time").toString();
        //预测数据
        QueryWrapper<Forecast> forecastQueryWrapper = new QueryWrapper<>();
        forecastQueryWrapper.select("time", "value")
                .eq("city_code", regionCode)
                .likeRight("time", time);
        List<Map<String, Object>> forecastData = forecastMapper.selectMaps(forecastQueryWrapper);
        //实测数据
        QueryWrapper<CityAqi> cityAqiQueryWrapper = new QueryWrapper<>();
        cityAqiQueryWrapper.select("time", "value")
                .eq("city_code", regionCode)
                .likeRight("time", time);
        List<Map<String, Object>> measuredData = cityAqiMapper.selectMaps(cityAqiQueryWrapper);
 
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 0; i < 48; i++) {
            Map<String, Object> map = new HashMap<>();
            if (i % 2 == 0) {
                map.put("type", "预测");
                Date d = DateUtils.addHours(DateUtils.getDate(time), i / 2);
                map.put("time", DateUtils.dateToDateString(d, DateUtils.yyyy_MM_dd_HH_EN));
                for (Map<String, Object> forecastDatum : forecastData) {
                    Date date = (Date) forecastDatum.get("time");
                    String value = forecastDatum.get("value").toString();
                    Map<String, Object> data = JSONObject.parseObject(value, Map.class);
                    Object o3 = data.get("O3");
                    if (i == DateUtils.getHour(date) * 2) {
                        if (!ObjectUtils.isEmpty(o3)) {
                            map.put("O3", o3);
                        }
                    }
                }
            } else {
                map.put("type", "实测");
                Date d = DateUtils.addHours(DateUtils.getDate(time), (i - 1) / 2);
                map.put("time", DateUtils.dateToDateString(d, DateUtils.yyyy_MM_dd_HH_EN));
                for (Map<String, Object> measuredDatum : measuredData) {
                    Date date = (Date) measuredDatum.get("time");
                    String value = measuredDatum.get("value").toString();
                    Map<String, Object> data = JSONObject.parseObject(value, Map.class);
                    Object o3 = data.get("O3");
                    if (i == (DateUtils.getHour(date) * 2 + 1)) {
                        if (!ObjectUtils.isEmpty(o3)) {
                            map.put("O3", o3);
                        }
                    }
                }
            }
            result.add(map);
        }
        return result;
    }
 
    @Override
    public Map<String, Object> queryCityAqiByRegionCode(Integer regionCode) {
        Map<String, Object> value = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.CITY_AQI, String.valueOf(regionCode));
        if (value == null)
            value = queryCityAqiByRegionCodeFromDB(regionCode);
        //如果地区码是县级市则转换到市级在进行查询
        if (value == null) {
            String regionCodeStr = String.valueOf(regionCode);
            String end = regionCodeStr.substring(regionCodeStr.length() - 2, regionCodeStr.length());
            if (!end.equals(00)) {
                regionCodeStr = regionCodeStr.substring(0, regionCodeStr.length() - 2);
                regionCodeStr += "00";
                regionCode = Integer.parseInt(regionCodeStr);
                value = (Map<String, Object>) redisTemplate.opsForHash().get(RedisConstants.CITY_AQI, String.valueOf(regionCode));
                if (value == null)
                    value = queryCityAqiByRegionCodeFromDB(regionCode);
            } else {
                return null;
            }
        }
        //根据AQI计算污染等级
        if (value == null || value.get("AQI") == null)
            return null;
        Integer aqi = Integer.parseInt(value.get("AQI").toString());
        String category = AQIUtils.classOfPollutionByAqi(aqi);
        value.put("category", category);
        return value;
    }
 
    @Override
    public Map<String, Object> query24HoursAqiByRegionCode(Integer regionCode) {
        //查询最新一条数据,用于获取最新的时间
        QueryWrapper<CityAqi> lastDataWrapper = new QueryWrapper<>();
        lastDataWrapper.eq("city_code", regionCode);
        lastDataWrapper.orderByDesc("time");
        lastDataWrapper.last(true, "limit 1");
        CityAqi cityAqi = cityAqiMapper.selectOne(lastDataWrapper);
        if (cityAqi == null)
            return null;
        //算出前24小时的时间点
        Date endDate = cityAqi.getTime();
        Date startDate = DateUtils.addHours(endDate, -23);
        //查询数据
        QueryWrapper<CityAqi> wrapper = new QueryWrapper<>();
        wrapper.between("time", startDate, endDate);
        wrapper.eq("city_code", regionCode);
        List<CityAqi> cityAqis = cityAqiMapper.selectList(wrapper);
        //如果数据不足24小时则补全
        if (cityAqis.size() != 24) {
            Map<Date, CityAqi> dateCityAqiMap = new HashMap<>();
            cityAqis.forEach(value -> dateCityAqiMap.put(value.getTime(), value));
            for (int i = 0; i < 24; i++) {
                Date date = DateUtils.addHours(startDate, i);
                CityAqi cityAqi1 = dateCityAqiMap.get(date);
                if (cityAqi1 == null) {
                    CityAqi newCityAqi = new CityAqi();
                    newCityAqi.setTime(date);
                    cityAqis.add(newCityAqi);
                }
            }
            //按照时间进行排序
            cityAqis.sort(Comparator.comparing(CityAqi::getTime));
        }
        //封装返回数据,map的key为yyyy-MM-dd HH:mm格式的时间,value为aqi的数值
        Map<String, Object> result = new LinkedHashMap<>();
        for (CityAqi aqi : cityAqis) {
            String key = DateUtils.dateToDateString(aqi.getTime(), "yyyy-MM-dd HH:mm");
            String allDataJson = aqi.getValue();
            if (allDataJson == null) {
                result.put(key, "");
                continue;
            }
            Map<String, Object> allDataMap = JSON.parseObject(allDataJson, Map.class);
            Object aqiData = allDataMap.get("AQI");
            if (aqiData == null)
                result.put(key, "");
            else
                result.put(key, aqiData);
        }
        return result;
    }
 
    @Override
    public Map<String, Object> queryTodayAqiAndPollutant(Integer regionCode) {
        //获取今天的9点时间
        Date startDate = new Date(DateUtils.getTodayTime());
        Date endDate = new Date();
        //查询当天数据
        QueryWrapper<CityAqi> wrapper = new QueryWrapper<>();
        wrapper.between("time", startDate, endDate);
        wrapper.eq("city_code", regionCode);
        wrapper.select("DISTINCT city_code,time,value");
        List<CityAqi> cityAqis = cityAqiMapper.selectList(wrapper);
        //计算平均数
        Map<String, Object> sixParamAvg = calculate6ParamAvg(cityAqis);
        //计算累计aqi和首要污染物
        Map<String, Object> result = new HashMap<>();
        AQI aqi = AQIUtils.hourlyAQI(sixParamAvg);
        result.put("aqi", aqi.getAQIValue());
        result.put("pollutant", aqi.getPrimaryPollutantNames());
        //结果集添加时间
        CityAqi lastCityAqi = cityAqis.get(cityAqis.size() - 1);
        String time = DateUtils.dateToDateString(lastCityAqi.getTime(), "HH:mm");
        result.put("time", time);
        return result;
    }
 
    @Override
    public List<Map<String, Object>> rankingDetails(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<>();
        int regionCode = Integer.parseInt(params.get("regionCode").toString());
        String type = params.get("type").toString();
        String time = null;
        if (!ObjectUtils.isEmpty(params.get("time"))) {
            time = params.get("time").toString();
        }
        String start = null;
        String end = null;
        if (!ObjectUtils.isEmpty(params.get("start")) || !ObjectUtils.isEmpty(params.get("end"))) {
            start = params.get("start").toString();
            end = params.get("end").toString();
        }
        String cityType = params.get("cityType").toString();
 
        String s = String.valueOf(regionCode);
        //获取当前省,市code
        Integer curProvinceCode = Integer.parseInt(s.substring(0, 2) + "0000");
        Integer curCityCode = Integer.parseInt(s.substring(0, 4) + "00");
 
        QueryWrapper<SysArea> areaWrapper = new QueryWrapper<>();
 
        List<SysArea> sysAreas;
        if ("28".equals(cityType)) {
            //获取2+26城市
            sysAreas = specialCitiesProperties.getTwentyEightCities();
        } else {
            if ("province".equals(cityType)) {
                //获取省内所有市
                areaWrapper.select("area_code", "area_name").eq("parent_code", curProvinceCode);
            } else {
                //获取市内所有县区
                areaWrapper.select("area_code", "area_name").eq("parent_code", curCityCode);
            }
            sysAreas = sysAreaService.list(areaWrapper);
        }
 
        switch (type) {
            case "today":
                result = accumulatedTodayRank(sysAreas);
                break;
            case "hour":
                time = new StringBuilder(time).replace(10, 11, " ").toString() + ":00:00";
                result = hourRank(sysAreas, time);
                break;
            case "day":
                time = time + " 00:00:00";
                result = dayRank(sysAreas, time);
                break;
            case "month":
                time = time + "-01 00:00:00";
                result = monthRank(sysAreas, time);
                break;
            case "year":
                time = time + "-01-01 00:00:00";
                result = yearRank(sysAreas, time);
                break;
            case "custom":
                start = start + " 00:00:00";
                end = end + " :00:00";
                result = customRank(sysAreas, start, end);
                break;
            default:
                break;
        }
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @return 功能:今日累计排名
     */
    private List<Map<String, Object>> accumulatedTodayRank(List<SysArea> sysAreas) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        List<Map<String, Object>> result = new ArrayList<>();
        List<String> sensors = Arrays.asList("PM2_5", "PM10", "SO2", "NO2", "CO", "O3");
        Date now = new Date();
        String today = DateUtils.dateToDateString(now, DateUtils.yyyy_MM_dd_EN);
        QueryWrapper<CityAqi> wrapper = new QueryWrapper<>();
        wrapper.select("city_code", "value")
                .ge("time", today)
                .in("city_code", regionCodes);
        List<Map<String, Object>> cumulativeData = cityAqiMapper.selectMaps(wrapper);
        //按city_code分组
        Map<Integer, List<Map<String, Object>>> data = cumulativeData.parallelStream().collect(Collectors.groupingBy(o -> Integer.parseInt(o.get("city_code").toString())));
        data.forEach((cityCode, value) -> {
            List<Double> doubles = new ArrayList<>();
            for (Map<String, Object> objectMap : value) {
                Object o = JSONObject.parseObject((String) objectMap.get("value"), Map.class).get("O3_8H");
                if (!ObjectUtils.isEmpty(o)) {
                    double v = Double.parseDouble(o.toString());
                    doubles.add(v);
                }
            }
 
            Map<String, Object> dataMap = new HashMap<>();
            sensors.forEach(sensor -> {
                OptionalDouble optionalDouble = value.parallelStream().flatMapToDouble(v -> {
                    Map<String, Object> sensorValue = JSONObject.parseObject((String) v.get("value"), Map.class);
                    Object o = sensorValue.get(sensor);
                    if (ObjectUtils.isEmpty(o)) {
                        return null;
                    }
                    double aDouble = Double.parseDouble(o.toString());
                    return DoubleStream.of(aDouble);
                }).average();
 
                if (optionalDouble.isPresent()) {
                    //银行家算法修约
                    double sciCal = AmendUtils.sciCal(optionalDouble.getAsDouble(), 0);
                    if ("CO".equals(sensor)) {
                        sciCal = AmendUtils.sciCal(optionalDouble.getAsDouble(), 1);
                    }
                    dataMap.put(sensor, sciCal);
                }
            });
 
            //今日累计O3_8H计算,取每小时O3——8H最大值
            if (!ObjectUtils.isEmpty(doubles)) {
                dataMap.put("O3_8H", Collections.max(doubles));
            }
 
            //今日累计aqi,首要污染物计算
            Map<String, Object> sixParamMap = new HashMap<>();
            sixParamMap.put(Constants.SENSOR_CODE_PM25, dataMap.get("PM2_5"));
            sixParamMap.put(Constants.SENSOR_CODE_PM10, dataMap.get("PM10"));
            sixParamMap.put(Constants.SENSOR_CODE_SO2, dataMap.get("SO2"));
            sixParamMap.put(Constants.SENSOR_CODE_NO2, dataMap.get("NO2"));
            sixParamMap.put(Constants.SENSOR_CODE_CO, dataMap.get("CO"));
            sixParamMap.put(Constants.SENSOR_CODE_O3, dataMap.get("O3"));
            AQI aqi = AQIUtils.dailyAQI(sixParamMap);
            dataMap.put("AQI", aqi.getAQIValue());
            List<String> primaryPollutantNames = aqi.getPrimaryPollutantNames();
            String primaryPollutant = "";
            if (!ObjectUtils.isEmpty(primaryPollutantNames)) {
                primaryPollutant = primaryPollutantNames.stream().map(String::valueOf).collect(Collectors.joining(","));
            }
            dataMap.put("primaryPollutant", primaryPollutant);
 
            //今日累计综合指数计算,O3分综指用O3_8H计算
            Map<String, Object> compositeIndexMap = new HashMap<>(dataMap);
            compositeIndexMap.put("O3", compositeIndexMap.get("O3_8H"));
            Double compositeIndex = ComprehensiveIndexUtils.dailyData(compositeIndexMap);
            dataMap.put("compositeIndex", compositeIndex);
 
            //城市名
            for (SysArea sysArea : sysAreas) {
                if (cityCode.equals(sysArea.getAreaCode())) {
                    dataMap.put("cityName", sysArea.getAreaName());
                    break;
                }
            }
            result.add(dataMap);
        });
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @param time     所要获取数据的时间 2021-11-04 13:00:00
     * @return 功能:小时排名
     */
    private List<Map<String, Object>> hourRank(List<SysArea> sysAreas, String time) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<CityAqi> wrapper = new QueryWrapper<>();
        wrapper.select("value")
                .eq("time", time)
                .in("city_code", regionCodes);
        List<Map<String, Object>> hourData = cityAqiMapper.selectMaps(wrapper);
        for (Map<String, Object> hourDatum : hourData) {
            Map<String, Object> value = JSONObject.parseObject((String) hourDatum.get("value"), Map.class);
            List<String> primaryPollutantNames = (List<String>) value.get("primaryPollutant");
            String primaryPollutant = "";
            if (!ObjectUtils.isEmpty(primaryPollutantNames)) {
                primaryPollutant = primaryPollutantNames.stream().map(String::valueOf).collect(Collectors.joining(","));
            }
            value.put("primaryPollutant", primaryPollutant);
            value.remove("pubtime");
            value.remove("rank");
            result.add(value);
        }
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @param time     所要获取数据的时间 2021-11-04 00:00:00
     * @return 功能:日排名
     */
    private List<Map<String, Object>> dayRank(List<SysArea> sysAreas, String time) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<CityAqiDaily> wrapper = new QueryWrapper<>();
        wrapper.select("city_code", "value")
                .eq("time", time)
                .in("city_code", regionCodes);
        List<Map<String, Object>> dayData = cityAqiDailyService.listMaps(wrapper);
        for (Map<String, Object> dayDatum : dayData) {
            Map<String, Object> value = JSONObject.parseObject((String) dayDatum.get("value"), Map.class);
            List<String> primaryPollutantNames = (List<String>) value.get("primaryPollutant");
            String primaryPollutant = "";
            if (!ObjectUtils.isEmpty(primaryPollutantNames)) {
                primaryPollutant = primaryPollutantNames.stream().map(String::valueOf).collect(Collectors.joining(","));
            }
            value.put("primaryPollutant", primaryPollutant);
 
 
            //城市名
            for (SysArea sysArea : sysAreas) {
                if (dayDatum.get("city_code").equals(sysArea.getAreaCode())) {
                    value.put("cityName", sysArea.getAreaName());
                    break;
                }
            }
            result.add(value);
        }
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @param time     所要获取数据的时间 2021-11-01 00:00:00 每月1号
     * @return 功能:月排名
     */
    private List<Map<String, Object>> monthRank(List<SysArea> sysAreas, String time) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        //需要均值计算的因子
        List<String> sensors = Arrays.asList("PM2_5", "PM10", "SO2", "NO2");
        List<Map<String, Object>> result = new ArrayList<>();
        //如果部是本月,实时计算,其他直接从city_aqi_monthly获取
        if (!time.substring(0, 7).equals(DateUtils.dateToDateString(new Date(), DateUtils.yyyy_MM_EN))) {
            QueryWrapper<CityAqiMonthly> cityAqiMonthlyQueryWrapper = new QueryWrapper<>();
            for (Integer regionCode : regionCodes) {
                cityAqiMonthlyQueryWrapper.clear();
                cityAqiMonthlyQueryWrapper.select("value")
                        .eq("city_code", regionCode)
                        .eq("time", time);
                CityAqiMonthly cityAqiMonthly = cityAqiMonthlyService.getOne(cityAqiMonthlyQueryWrapper);
                if (cityAqiMonthly == null) {
                    continue;
                }
                String value = cityAqiMonthly.getValue();
                Map<String, Object> resultMap = JSONObject.parseObject(value, Map.class);
 
 
                //城市名
                for (SysArea sysArea : sysAreas) {
                    if (regionCode.equals(sysArea.getAreaCode())) {
                        resultMap.put("cityName", sysArea.getAreaName());
                        break;
                    }
                }
            }
            return result;
        }
 
        QueryWrapper<CityAqiDaily> cityAqiDailyQueryWrapper = new QueryWrapper<>();
        cityAqiDailyQueryWrapper.select("city_code", "value")
                .ge("time", time)
                .in("city_code", regionCodes);
        List<Map<String, Object>> thisMonthData = cityAqiDailyService.listMaps(cityAqiDailyQueryWrapper);
        //按city_code分组
        Map<Integer, List<Map<String, Object>>> thisMonthMap = thisMonthData.parallelStream()
                .collect(Collectors.groupingBy(o -> Integer.parseInt(o.get("city_code").toString())));
 
        thisMonthMap.forEach((cityCode, value) -> {
            Map<String, Object> resultMap = new HashMap<>();
 
            Map<String, Object> params = new HashMap<>();
            List<Map<String, Object>> temp = new ArrayList<>();
            for (Map<String, Object> map : value) {
                Map<String, Object> sensorsValue = JSONObject.parseObject(map.get("value").toString(), Map.class);
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put(Constants.SENSOR_CODE_CO, sensorsValue.get("CO"));
                tempMap.put(Constants.SENSOR_CODE_O3, sensorsValue.get("O3"));
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", JSONObject.toJSONString(tempMap));
                temp.add(hashMap);
            }
            params.put("data", temp);
            //1. CO 95百分位计算并修约
            Map<String, Object> coAvgOfWeekOrMonth = AmendUtils.getCOAvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(coAvgOfWeekOrMonth)) {
                resultMap.put("CO", coAvgOfWeekOrMonth.get(Constants.SENSOR_CODE_CO));
            }
 
            //2. O3 90百分位计算并修约
            Map<String, Object> o3AvgOfWeekOrMonth = AmendUtils.getO3AvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(o3AvgOfWeekOrMonth)) {
                resultMap.put("O3", o3AvgOfWeekOrMonth.get(Constants.SENSOR_CODE_O3));
            }
 
            sensors.forEach(sensor -> {
                OptionalDouble optionalDouble = value.parallelStream().flatMapToDouble(v -> {
                    Map<String, Object> sensorValue = JSONObject.parseObject((String) v.get("value"), Map.class);
                    Object o = sensorValue.get(sensor);
                    if (ObjectUtils.isEmpty(o)) {
                        return null;
                    }
                    double aDouble = Double.parseDouble(o.toString());
                    return DoubleStream.of(aDouble);
                }).average();
 
                if (optionalDouble.isPresent()) {
                    //银行家算法修约
                    double sciCal = AmendUtils.sciCal(optionalDouble.getAsDouble(), 0);
                    resultMap.put(sensor, sciCal);
                }
            });
 
            //本月综指计算
            Double compositeIndex = ComprehensiveIndexUtils.dailyData(resultMap);
            resultMap.put("compositeIndex", compositeIndex);
 
            //前端O3用O3_8H显示
            resultMap.put("O3_8H", resultMap.remove("O3"));
 
            //本月综指同上月对比
            Date lastMonth = DateUtils.addMonths(DateUtils.getDate(time), -1);
            QueryWrapper<CityAqiMonthly> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("value")
                    .eq("city_code", cityCode)
                    .eq("time", DateUtils.dateToDateString(lastMonth));
            //获取上月数据
            CityAqiMonthly lastCityAqiMonthly = cityAqiMonthlyService.getOne(queryWrapper);
            String monthContrast = "";
            if (lastCityAqiMonthly != null) {
                Map<String, Object> map = JSONObject.parseObject(lastCityAqiMonthly.getValue(), Map.class);
                double lastCompositeIndex = Double.parseDouble(map.get("compositeIndex").toString());
                DecimalFormat decimalFormat = new DecimalFormat("0.00%");
                monthContrast = decimalFormat.format((compositeIndex - lastCompositeIndex) / lastCompositeIndex);
            }
            resultMap.put("monthContrast", monthContrast);
 
            //城市名
            for (SysArea sysArea : sysAreas) {
                if (cityCode.equals(sysArea.getAreaCode())) {
                    resultMap.put("cityName", sysArea.getAreaName());
                    break;
                }
            }
            result.add(resultMap);
        });
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @param time     所要获取数据的时间 2021-11-01 00:00:00 每年1月1号
     * @return 功能:年排名
     */
    private List<Map<String, Object>> yearRank(List<SysArea> sysAreas, String time) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        //需要均值计算的因子
        List<String> sensors = Arrays.asList("PM2_5", "PM10", "SO2", "NO2");
        List<Map<String, Object>> result = new ArrayList<>();
        //如果是本月,实时计算,其他直接从city_aqi_monthly获取
        if (!time.substring(0, 4).equals(DateUtils.dateToDateString(new Date(), DateUtils.yyyy))) {
            QueryWrapper<CityAqiYearly> cityAqiYearlyQueryWrapper = new QueryWrapper<>();
            for (Integer regionCode : regionCodes) {
                cityAqiYearlyQueryWrapper.clear();
                cityAqiYearlyQueryWrapper.select("value")
                        .eq("city_code", regionCode)
                        .eq("time", time);
                CityAqiYearly cityAqiYearly = cityAqiYearlyService.getOne(cityAqiYearlyQueryWrapper);
                if (cityAqiYearly == null) {
                    continue;
                }
                String value = cityAqiYearly.getValue();
                Map<String, Object> resultMap = JSONObject.parseObject(value, Map.class);
 
 
                //城市名
                for (SysArea sysArea : sysAreas) {
                    if (regionCode.equals(sysArea.getAreaCode())) {
                        resultMap.put("cityName", sysArea.getAreaName());
                        break;
                    }
                }
                result.add(resultMap);
            }
            return result;
        }
 
        QueryWrapper<CityAqiDaily> cityAqiDailyQueryWrapper = new QueryWrapper<>();
        cityAqiDailyQueryWrapper.select("city_code", "value")
                .ge("time", time)
                .in("city_code", regionCodes);
        List<Map<String, Object>> thisMonthData = cityAqiDailyService.listMaps(cityAqiDailyQueryWrapper);
        //按city_code分组
        Map<Integer, List<Map<String, Object>>> thisYearMap = thisMonthData.parallelStream()
                .collect(Collectors.groupingBy(o -> Integer.parseInt(o.get("city_code").toString())));
        thisYearMap.forEach((cityCode, value) -> {
            Map<String, Object> resultMap = new HashMap<>();
 
            Map<String, Object> params = new HashMap<>();
            List<Map<String, Object>> temp = new ArrayList<>();
            for (Map<String, Object> map : value) {
                Map<String, Object> sensorsValue = JSONObject.parseObject(map.get("value").toString(), Map.class);
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put(Constants.SENSOR_CODE_CO, sensorsValue.get("CO"));
                tempMap.put(Constants.SENSOR_CODE_O3, sensorsValue.get("O3"));
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", JSONObject.toJSONString(tempMap));
                temp.add(hashMap);
            }
            params.put("data", temp);
            //1. CO 95百分位计算并修约
            Map<String, Object> coAvgOfWeekOrMonth = AmendUtils.getCOAvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(coAvgOfWeekOrMonth)) {
                resultMap.put("CO", coAvgOfWeekOrMonth.get(Constants.SENSOR_CODE_CO));
            }
 
            //2. O3 90百分位计算并修约
            Map<String, Object> o3AvgOfWeekOrMonth = AmendUtils.getO3AvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(o3AvgOfWeekOrMonth)) {
                resultMap.put("O3", o3AvgOfWeekOrMonth.get(Constants.SENSOR_CODE_O3));
            }
 
            sensors.forEach(sensor -> {
                OptionalDouble optionalDouble = value.parallelStream().flatMapToDouble(v -> {
                    Map<String, Object> sensorValue = JSONObject.parseObject((String) v.get("value"), Map.class);
                    Object o = sensorValue.get(sensor);
                    if (ObjectUtils.isEmpty(o)) {
                        return null;
                    }
                    double aDouble = Double.parseDouble(o.toString());
                    return DoubleStream.of(aDouble);
                }).average();
 
                if (optionalDouble.isPresent()) {
                    //银行家算法修约
                    double sciCal = AmendUtils.sciCal(optionalDouble.getAsDouble(), 0);
                    resultMap.put(sensor, sciCal);
                }
            });
 
            //本年综指计算
            Double compositeIndex = ComprehensiveIndexUtils.dailyData(resultMap);
            resultMap.put("compositeIndex", compositeIndex);
 
            //前端O3用O3_8H显示
            resultMap.put("O3_8H", resultMap.remove("O3"));
 
            //本年综指同去年对比
            String lastYear = DateUtils.getDateAddYear(time.substring(0, 4), -1);
            QueryWrapper<CityAqiYearly> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("value")
                    .eq("city_code", cityCode)
                    .eq("time", lastYear);
            //获取去年数据
            CityAqiYearly lastCityAqiYearly = cityAqiYearlyService.getOne(queryWrapper);
            String yearContrast = "";
            if (lastCityAqiYearly != null) {
                Map<String, Object> map = JSONObject.parseObject(lastCityAqiYearly.getValue(), Map.class);
                double lastCompositeIndex = Double.parseDouble(map.get("compositeIndex").toString());
                DecimalFormat decimalFormat = new DecimalFormat("0.00%");
                yearContrast = decimalFormat.format((compositeIndex - lastCompositeIndex) / lastCompositeIndex);
            }
            resultMap.put("yearContrast", yearContrast);
 
 
            //城市名
            for (SysArea sysArea : sysAreas) {
                if (cityCode.equals(sysArea.getAreaCode())) {
                    resultMap.put("cityName", sysArea.getAreaName());
                    break;
                }
            }
            result.add(resultMap);
        });
        return result;
    }
 
    /**
     * @param sysAreas 所要获取城市集合
     * @param start    所要获取数据的开始时间,精确到日,2021-11-03 00:00:00
     * @param end      所要获取数据的结束时间,精确到日,2021-11-25 00:00:00
     * @return 功能:自定义排名
     */
    private List<Map<String, Object>> customRank(List<SysArea> sysAreas, String start, String end) {
        List<Integer> regionCodes = sysAreas.stream()
                .map(SysArea::getAreaCode)
                .collect(Collectors.toList());
 
        //需要均值计算的因子
        List<String> sensors = Arrays.asList("PM2_5", "PM10", "SO2", "NO2");
        List<Map<String, Object>> result = new ArrayList<>();
        QueryWrapper<CityAqiDaily> cityAqiDailyQueryWrapper = new QueryWrapper<>();
        cityAqiDailyQueryWrapper.select("city_code", "value")
                .ge("time", start)
                .le("time", end)
                .in("city_code", regionCodes);
        List<Map<String, Object>> thisMonthData = cityAqiDailyService.listMaps(cityAqiDailyQueryWrapper);
        //按city_code分组
        Map<Integer, List<Map<String, Object>>> customMap = thisMonthData.parallelStream()
                .collect(Collectors.groupingBy(o -> Integer.parseInt(o.get("city_code").toString())));
        customMap.forEach((cityCode, value) -> {
            Map<String, Object> resultMap = new HashMap<>();
 
            Map<String, Object> params = new HashMap<>();
            List<Map<String, Object>> temp = new ArrayList<>();
            for (Map<String, Object> map : value) {
                Map<String, Object> sensorsValue = JSONObject.parseObject(map.get("value").toString(), Map.class);
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put(Constants.SENSOR_CODE_CO, sensorsValue.get("CO"));
                tempMap.put(Constants.SENSOR_CODE_O3, sensorsValue.get("O3"));
                Map<String, Object> hashMap = new HashMap<>();
                hashMap.put("value", JSONObject.toJSONString(tempMap));
                temp.add(hashMap);
            }
            params.put("data", temp);
            //1. CO 95百分位计算并修约
            Map<String, Object> coAvgOfWeekOrMonth = AmendUtils.getCOAvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(coAvgOfWeekOrMonth)) {
                resultMap.put("CO", coAvgOfWeekOrMonth.get(Constants.SENSOR_CODE_CO));
            }
 
            //2. O3 90百分位计算并修约
            Map<String, Object> o3AvgOfWeekOrMonth = AmendUtils.getO3AvgOfWeekOrMonth(params);
            if (!ObjectUtils.isEmpty(o3AvgOfWeekOrMonth)) {
                resultMap.put("O3", o3AvgOfWeekOrMonth.get(Constants.SENSOR_CODE_O3));
            }
 
            sensors.forEach(sensor -> {
                OptionalDouble optionalDouble = value.parallelStream().flatMapToDouble(v -> {
                    Map<String, Object> sensorValue = JSONObject.parseObject((String) v.get("value"), Map.class);
                    Object o = sensorValue.get(sensor);
                    if (ObjectUtils.isEmpty(o)) {
                        return null;
                    }
                    double aDouble = Double.parseDouble(o.toString());
                    return DoubleStream.of(aDouble);
                }).average();
 
                if (optionalDouble.isPresent()) {
                    //银行家算法修约
                    double sciCal = AmendUtils.sciCal(optionalDouble.getAsDouble(), 0);
                    resultMap.put(sensor, sciCal);
                }
            });
 
            //自定义综指计算
            Double compositeIndex = ComprehensiveIndexUtils.dailyData(resultMap);
            resultMap.put("compositeIndex", compositeIndex);
 
            //前端O3用O3_8H显示
            resultMap.put("O3_8H", resultMap.remove("O3"));
 
            //城市名
            for (SysArea sysArea : sysAreas) {
                if (cityCode.equals(sysArea.getAreaCode())) {
                    resultMap.put("cityName", sysArea.getAreaName());
                    break;
                }
            }
            result.add(resultMap);
        });
        return result;
    }
 
 
    /**
     * @Description: 从数据库查询数据
     * @Param: [regionCode]
     * @return: java.util.Map<java.lang.String                                                               ,                                                                                                                               java.lang.Object>
     * @Author: 陈凯裕
     * @Date: 2021/10/28
     */
    private Map<String, Object> queryCityAqiByRegionCodeFromDB(Integer regionCode) {
        QueryWrapper<CityAqi> wrapper = new QueryWrapper();
        wrapper.eq("city_code", regionCode);
        wrapper.orderByDesc("time");
        wrapper.last(true, "limit 1");
        CityAqi cityAqi = cityAqiMapper.selectOne(wrapper);
        if (cityAqi == null)
            return null;
        String value = cityAqi.getValue();
        redisTemplate.opsForHash().put(RedisConstants.CITY_AQI, regionCode, value);
        return JSON.parseObject(value, Map.class);
    }
 
    @Override
    public Map<String, Object> provincialRanking(Integer regionCode) {
        //结果集
        Map<String, Object> result = new HashMap<>();
 
        Date now = new Date();
        //昨日
        Date yesterday = DateUtils.dataToTimeStampTime(DateUtils.getDateOfDay(now, -1), DateUtils.yyyy_MM_dd_EN);
        String dateString = DateUtils.dateToDateString(yesterday, DateUtils.yyyy_MM_dd_HH_mm_ss_EN);
 
        String s = String.valueOf(regionCode);
        //获取省,市code
        Integer provinceCode = Integer.parseInt(s.substring(0, 2) + "0000");
        Integer cityCode = Integer.parseInt(s.substring(0, 4) + "00");
        //获取省内所有city_code
        QueryWrapper<SysArea> wrapper = new QueryWrapper<>();
        wrapper.select("area_code").eq("parent_code", provinceCode);
        List<Object> cityCodes = sysAreaService.listObjs(wrapper);
 
        List<Map<String, Object>> ranks = new ArrayList<>();
        for (Object code : cityCodes) {
            Map<String, Object> rankMap = new HashMap<>();
            rankMap.put("cityCode", code);
            QueryWrapper<CityAqiDaily> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("value").eq("city_code", code).eq("time", dateString);
 
            //1.昨日数据
            CityAqiDaily one = cityAqiDailyService.getOne(queryWrapper);
            if (!ObjectUtils.isEmpty(one)) {
                String value = one.getValue();
                Map<String, Object> valueMap = JSONObject.parseObject(value, Map.class);
                rankMap.put("AQI", valueMap.get("AQI"));
            }
 
            //2.本月累计综合指数计算,截止到昨日
            queryWrapper.clear();
            //开始时间:本月1号,结束时间:昨日
            Date start = DateUtils.addMonths(DateUtils.getFirstDayOfLastMonth(), 1);
            queryWrapper.select("value").eq("city_code", code).ge("time", start).le("time", yesterday);
            List<CityAqiDaily> listMonth = cityAqiDailyService.list(queryWrapper);
            OptionalDouble averageMonth = listMonth.parallelStream().flatMapToDouble(v -> {
                Map<String, Object> dataValue = JSONObject.parseObject(v.getValue(), Map.class);
                Double compositeIndex = Double.parseDouble(dataValue.get("compositeIndex").toString());
                return DoubleStream.of(compositeIndex);
            }).average();
            if (averageMonth.isPresent()) {
                //银行家算法修约
                double compositeIndexAvgMonth = AmendUtils.sciCal(averageMonth.getAsDouble(), 2);
                rankMap.put("compositeIndexMonth", compositeIndexAvgMonth);
            }
 
            //3.本年累计综合指数计算,截止到昨日
            queryWrapper.clear();
            //开始时间:本年1.1号,结束时间:昨日
            String yearStart = DateUtils.dateToDateString(now, DateUtils.yyyy);
            queryWrapper.select("value").eq("city_code", code).ge("time", yearStart).le("time", yesterday);
            List<CityAqiDaily> listYear = cityAqiDailyService.list(queryWrapper);
            OptionalDouble averageYear = listYear.parallelStream().flatMapToDouble(v -> {
                Map<String, Object> dataValue = JSONObject.parseObject(v.getValue(), Map.class);
                Double compositeIndex = Double.parseDouble(dataValue.get("compositeIndex").toString());
                return DoubleStream.of(compositeIndex);
            }).average();
            if (averageYear.isPresent()) {
                //银行家算法修约
                double compositeIndexAvgYear = AmendUtils.sciCal(averageYear.getAsDouble(), 2);
                rankMap.put("compositeIndexYear", compositeIndexAvgYear);
            }
            ranks.add(rankMap);
        }
 
        //日排名,按aqi排序
        ranks.removeIf(o -> o.get("AQI") == null);
        sortByField(ranks, "AQI");
        //日排名结果
        Map<String, Object> dayMap = rankByField(ranks, cityCode, "AQI", cityCodes.size());
        if (ObjectUtils.isEmpty(dayMap)) {
            dayMap.put("rank", null);
            dayMap.put("size", null);
        }
        dayMap.put("AQI", dayMap.remove("value"));
        result.put("day", dayMap);
 
        //月排名,按累计综指排
        ranks.removeIf(o -> o.get("compositeIndexMonth") == null);
        sortByField(ranks, "compositeIndexMonth");
        //月排名结果
        Map<String, Object> monthMap = rankByField(ranks, cityCode, "compositeIndexMonth", cityCodes.size());
        if (ObjectUtils.isEmpty(monthMap)) {
            monthMap.put("rank", null);
            monthMap.put("size", null);
        }
        monthMap.put("compositeIndex", monthMap.remove("value"));
        result.put("month", monthMap);
 
        //年排名,按累计综指排
        sortByField(ranks, "compositeIndexYear");
        Map<String, Object> yearMap = rankByField(ranks, cityCode, "compositeIndexYear", cityCodes.size());
        if (ObjectUtils.isEmpty(yearMap)) {
            yearMap.put("rank", null);
            yearMap.put("size", null);
        }
        yearMap.put("compositeIndex", yearMap.remove("value"));
        result.put("year", yearMap);
 
        //时间,昨日
        result.put("time", DateUtils.dateToDateString(yesterday, DateUtils.yyyy_MM_dd_EN));
        return result;
    }
 
    @Override
    public List<AirQualityComparisonVO> queryAirQualityComparison(AirQualityComparisonForm form) {
        //取参
        Integer regionCode = form.getRegionCode();
        String regionType = form.getRegionType();
        Date startDate = form.getStartDate();
        Date endDate = form.getEndDate();
        Date comparisonStartDate = form.getComparisonStartDate();
        Date comparisonEndDate = form.getComparisonEndDate();
        String dateType = form.getDateType();
        //获取城市/区县
        List<SysArea> areas = getSysAreasByRegionType(regionType, regionCode);
        if (ObjectUtils.isEmpty(areas))
            return null;
        List<AirQualityComparisonVO> vos = new ArrayList<>();
        for (SysArea area : areas) {
            //获取查询时间和对比时间的6参和综合指数
            Map<String, Object> data = getDataByTimeTypeAndRegionCode(dateType, startDate, endDate, area.getAreaCode());
            Map<String, Object> comparisonData = getDataByTimeTypeAndRegionCode(dateType, comparisonStartDate, comparisonEndDate, area.getAreaCode());
            if (ObjectUtils.isEmpty(data) || ObjectUtils.isEmpty(comparisonData))
                continue;
            //查询优良天数以及重污染天数
            CityPollutionLevel days = cityAqiDailyService.calculateDaysByTimeAndSysArea(area, startDate, endDate);
            CityPollutionLevel comparisonDays = cityAqiDailyService.calculateDaysByTimeAndSysArea(area, comparisonStartDate, comparisonEndDate);
            int fineDays = days.getExcellentWeatherDays() + days.getGoodWeatherDays();
            int serverDays = days.getSeriousWeatherDays() + days.getServerWeatherDays();
            int comparisonFineDays = comparisonDays.getExcellentWeatherDays() + comparisonDays.getGoodWeatherDays();
            int comparisonServerDays = comparisonDays.getSeriousWeatherDays() + comparisonDays.getServerWeatherDays();
            //对比6参和综合指数
            Map<String, ConcentrationAndPercent> sixParamAndComIndexResult = contrastSixParamAndComIndex(data, comparisonData);
            //对比优良天数以及重污染天气数
            ConcentrationAndPercent fine = contrastDays(fineDays, comparisonFineDays);
            ConcentrationAndPercent server = contrastDays(serverDays, comparisonServerDays);
            //创建返回对象
            AirQualityComparisonVO vo = new AirQualityComparisonVO();
            vo.setFineDays(fine);
            vo.setServerDays(server);
            vo.setCO(sixParamAndComIndexResult.get("CO"));
            vo.setO3(sixParamAndComIndexResult.get("O3"));
            vo.setPM25(sixParamAndComIndexResult.get("PM2_5"));
            vo.setPM10(sixParamAndComIndexResult.get("PM10"));
            vo.setSO2(sixParamAndComIndexResult.get("SO2"));
            vo.setNO2(sixParamAndComIndexResult.get("NO2"));
            vo.setCompositeIndex(sixParamAndComIndexResult.get("compositeIndex"));
            vo.setCityName(area.getAreaName());
            vos.add(vo);
        }
        return vos;
    }
 
    /**
     * @Description: 计算6参和综合指数对比的百分比
     * @Param: [data, comparisonData]
     * @return: java.util.Map<java.lang.String                               ,                               com.moral.api.pojo.dto.cityAQI.ConcentrationAndPercent>
     * @Author: 陈凯裕
     * @Date: 2022/1/17
     */
    private Map<String, ConcentrationAndPercent> contrastSixParamAndComIndex(Map<String, Object> data, Map<String, Object> comparisonData) {
        Map<String, ConcentrationAndPercent> result = new HashMap<>();
        result.put("CO", contrastParam(Double.parseDouble(data.get("CO").toString()), Double.parseDouble(comparisonData.get("CO").toString()), "CO"));
        result.put("NO2", contrastParam(Double.parseDouble(data.get("NO2").toString()), Double.parseDouble(comparisonData.get("NO2").toString()), "NO2"));
        result.put("SO2", contrastParam(Double.parseDouble(data.get("SO2").toString()), Double.parseDouble(comparisonData.get("SO2").toString()), "SO2"));
        result.put("O3", contrastParam(Double.parseDouble(data.get("O3").toString()), Double.parseDouble(comparisonData.get("O3").toString()), "O3"));
        result.put("PM2_5", contrastParam(Double.parseDouble(data.get("PM2_5").toString()), Double.parseDouble(comparisonData.get("PM2_5").toString()), "PM2_5"));
        result.put("PM10", contrastParam(Double.parseDouble(data.get("PM10").toString()), Double.parseDouble(comparisonData.get("PM10").toString()), "PM10"));
        result.put("compositeIndex", contrastParam(Double.parseDouble(data.get("compositeIndex").toString()), Double.parseDouble(comparisonData.get("compositeIndex").toString()), "compositeIndex"));
        return result;
    }
 
    /**
     * @Description: 计算6参和综合指数同比/环比百分比数据
     * @Param: [data, comparisonData]
     * @return: com.moral.api.pojo.dto.cityAQI.ConcentrationAndPercent
     * @Author: 陈凯裕
     * @Date: 2022/1/17
     */
    private ConcentrationAndPercent contrastParam(Double data, Double comparisonData, String sensor) {
        double percentD = MathUtils.division(data - comparisonData, comparisonData, 4);
        String percent = MathUtils.mul(percentD,100d) + "%";
        ConcentrationAndPercent concentrationAndPercent = new ConcentrationAndPercent();
        concentrationAndPercent.setPercent(percent);
        if (sensor.equals("CO")) {//CO小数点保留一位
            Double CO = AmendUtils.sciCal(data, 1);
            concentrationAndPercent.setConcentration(CO.toString());
        }else if (sensor.equals("compositeIndex")){
            concentrationAndPercent.setConcentration(data.toString());
        }else{
            Double sensorD = AmendUtils.sciCal(data, 0);
            Integer sensorI = new Double(sensorD).intValue();
            concentrationAndPercent.setConcentration(sensorI.toString());
        }
        return concentrationAndPercent;
    }
 
    /**
     * @Description: 对比天数,返回天数差值
     * @Param: [days, comparisonDays]
     * @return: com.moral.api.pojo.dto.cityAQI.ConcentrationAndPercent
     * @Author: 陈凯裕
     * @Date: 2022/1/17
     */
    private ConcentrationAndPercent contrastDays(Integer days, Integer comparisonDays) {
        ConcentrationAndPercent concentrationAndPercent = new ConcentrationAndPercent();
        concentrationAndPercent.setConcentration(days.toString());
        Integer result = days - comparisonDays;
        concentrationAndPercent.setPercent(result.toString() + "天");
        return concentrationAndPercent;
    }
 
    /**
     * @Description: 根据时间类型查询对应的6参以及综合指数,自定义时间类型用日数据做均值处理
     * @Param: [comparisonType, startDate, endDate, regionCode]
     * @return: java.util.Map<java.lang.String                                                               ,                                                               java.lang.Object>
     * @Author: 陈凯裕
     * @Date: 2022/1/17
     */
    private Map<String, Object> getDataByTimeTypeAndRegionCode(String TimeType, Date startDate, Date endDate, Integer regionCode) {
        Map<String, Object> data;
        if (Constants.MONTH.equals(TimeType) && (!DateUtils.isCurrentMonth(startDate) || !DateUtils.isCurrentYear(startDate))) {//月数据处理 不包括本月
            List<CityAqiMonthly> cityAqis = cityAqiMonthlyService.getCityAqiMonthByRegionCodeAndTime(regionCode, startDate, endDate);
            if (ObjectUtils.isEmpty(cityAqis))
                return null;
            data = JSON.parseObject(cityAqis.get(0).getValue(), Map.class);
        } else if (Constants.YEAR.equals(TimeType) && (!DateUtils.isCurrentYear(startDate))) {//年数据处理 不包括本年
            List<CityAqiYearly> cityAqis = cityAqiYearlyService.getCityAqiYearlyByRegionCodeAndTime(regionCode, startDate, endDate);
            if (ObjectUtils.isEmpty(cityAqis))
                return null;
            data = JSON.parseObject(cityAqis.get(0).getValue(), Map.class);
        } else {//自定义数据处理
            List<CityAqiDaily> cityAqis = cityAqiDailyService.getCityAqiDailyByRegionCodeAndTime(regionCode, startDate, endDate);
            if (ObjectUtils.isEmpty(cityAqis))
                return null;
            List<CityAqi> newCityAqis = new ArrayList<>();
            List<Map<String, Object>> dailyDataMaps = new ArrayList<>();
            cityAqis.forEach((value) -> {
                newCityAqis.add(new CityAqi(value));
                dailyDataMaps.add(JSON.parseObject(value.getValue(), Map.class));
            });
            //计算均值
            data = calculate6ParamAvg(newCityAqis);
            //小数点处理
            data.put("CO", Double.parseDouble(data.remove(Constants.SENSOR_CODE_CO).toString()));
            data.put("NO2", Double.parseDouble(data.remove(Constants.SENSOR_CODE_NO2).toString()));
            data.put("SO2", Double.parseDouble(data.remove(Constants.SENSOR_CODE_SO2).toString()));
            data.put("O3", Double.parseDouble(data.remove(Constants.SENSOR_CODE_O3).toString()));
            data.put("PM2_5", Double.parseDouble(data.remove(Constants.SENSOR_CODE_PM25).toString()));
            data.put("PM10", Double.parseDouble(data.remove(Constants.SENSOR_CODE_PM10).toString()));
            //计算综合指数
            Double compositeIndex = ComprehensiveIndexUtils.dailyData(data);
            data.put("compositeIndex", compositeIndex);
        }
        return data;
    }
 
 
    //按某字段排序
    private void sortByField(List<Map<String, Object>> list, String sortField) {
        list.sort((o1, o2) -> {
            double v1 = Double.parseDouble(o1.get(sortField).toString());
            double v2 = Double.parseDouble(o2.get(sortField).toString());
            if (v1 > v2) {
                return -1;
            } else if (v1 < v2) {
                return 1;
            }
            return 0;
        });
    }
 
    //排名
    private Map<String, Object> rankByField(List<Map<String, Object>> list, Integer cityCode, String rankField, Integer size) {
        Map<String, Object> result = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            if (cityCode == (int) map.get("cityCode")) {
                int rank = i + 1;
                result.put("rank", rank);
                result.put("size", size);
                Object value = map.get(rankField);
                result.put("value", value);
                break;
            }
        }
        return result;
    }
 
    /**
     * @Description: 根据类型和地区码获取所有的城市或者区县
     * @Param: [regionType, regionCode]
     * @return: java.util.List<com.moral.api.entity.SysArea>
     * @Author: 陈凯裕
     * @Date: 2022/1/14
     */
    private List<SysArea> getSysAreasByRegionType(String regionType, Integer regionCode) {
        List<SysArea> areas;
        if (regionType.equals(Constants.TWENTY_EIGHT_CITIES)) {
            SpecialCitiesProperties properties = new SpecialCitiesProperties();
            areas = properties.getTwentyEightCities();
        } else {
            areas = sysAreaService.getChildren(regionCode);
        }
        return areas;
    }
 
    /**
     * @Description: 计算6参平均值
     * @Param: [cityAqiList]
     * @return: java.util.Map<java.lang.String                                                               ,                                                                                                                               java.lang.Double>
     * 返回值key为sensorCode,value为值
     * @Author: 陈凯裕
     * @Date: 2021/11/2
     */
    private Map<String, Object> calculate6ParamAvg(List<CityAqi> cityAqiList) {
        Double co = calculateSensorAvg(cityAqiList, "CO");
        Double pm2_5 = calculateSensorAvg(cityAqiList, "PM2_5");
        Double pm10 = calculateSensorAvg(cityAqiList, "PM10");
        Double so2 = calculateSensorAvg(cityAqiList, "SO2");
        Double no2 = calculateSensorAvg(cityAqiList, "NO2");
        Double o3 = calculateSensorAvg(cityAqiList, "O3");
        Map<String, Object> result = new HashMap<>();
        result.put(Constants.SENSOR_CODE_CO, co);
        result.put(Constants.SENSOR_CODE_NO2, no2);
        result.put(Constants.SENSOR_CODE_SO2, so2);
        result.put(Constants.SENSOR_CODE_O3, o3);
        result.put(Constants.SENSOR_CODE_PM25, pm2_5);
        result.put(Constants.SENSOR_CODE_PM10, pm10);
        return result;
    }
 
    /**
     * @Description: 计算因子的平均值
     * @Param: [cityAqiList, sensor]
     * ,sensor是要计算的因子名称
     * @return: java.lang.Double
     * @Author: 陈凯裕
     * @Date: 2021/11/2
     */
    private Double calculateSensorAvg(List<CityAqi> cityAqiList, String sensor) {
        Double sum = 0d;
        int num = 0;
        for (CityAqi cityAqi : cityAqiList) {
            String value = cityAqi.getValue();
            if (value == null)
                continue;
            Map<String, Object> valueMap = JSON.parseObject(value, Map.class);
            Object sensorValueObject = valueMap.get(sensor);
            if (sensorValueObject == null)
                continue;
            Double sensorValue = Double.valueOf(sensorValueObject.toString());
            sum = MathUtils.add(sum, sensorValue);
            num++;
        }
        if (num == 0)
            return null;
        Double avg = MathUtils.division(sum, num, 2);
        return avg;
    }
}