lizijie
2020-12-03 a66d53c3cbfb0024804045f4d795be06089d4f9d
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
package com.moral.service.impl;
 
import com.moral.mapper.*;
import io.swagger.models.auth.In;
 
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
 
import javax.annotation.Resource;
 
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.jasper.compiler.JspUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.moral.common.util.CalculateUtils;
import com.moral.common.util.ParameterUtils;
import com.moral.common.util.ReportTimeFormat;
import com.moral.common.util.ResourceUtil;
import com.moral.common.util.ValidateUtil;
import com.moral.entity.Area;
import com.moral.entity.City;
import com.moral.entity.MonitorPoint;
import com.moral.entity.Province;
import com.moral.entity.Sensor;
import com.moral.entity.charts.DataCondition;
import com.moral.entity.charts.LineChartCriteria;
import com.moral.entity.charts.TimePeriod;
import com.moral.mapper.AlarmDailyMapper;
import com.moral.mapper.AreaMapper;
import com.moral.mapper.CityMapper;
import com.moral.mapper.DeviceMapper;
import com.moral.mapper.HistoryMapper;
import com.moral.mapper.HistoryMinutelyMapper;
import com.moral.mapper.MonitorPointMapper;
import com.moral.mapper.ProvinceMapper;
import com.moral.mapper.SensorMapper;
import com.moral.mapper.ShAreaMapper;
import com.moral.service.HistoryMinutelyService;
import com.sun.org.apache.bcel.internal.generic.ANEWARRAY;
 
import static com.moral.common.bean.Constants.NULL_VALUE;
import static org.springframework.util.ObjectUtils.isEmpty;
 
@Service
@SuppressWarnings({"unchecked", "unused", "rawtypes"})
public class HistoryMinutelyServiceImpl implements HistoryMinutelyService {
 
    @Resource
    private HistoryMinutelyMapper historyMinutelyMapper;
 
    @Resource
    private HistoryMapper historyMapper;
 
    @Resource
    private DeviceMapper deviceMapper;
 
    @Resource
    private SensorMapper sensorMapper;
 
    @Resource
    private AlarmDailyMapper alarmDailyMapper;
 
    @Resource
    private AreaMapper areaMapper;
 
    @Resource
    private ProvinceMapper provinceMapper;
 
    @Resource
    private CityMapper cityMapper;
 
    @Resource
    private MonitorPointMapper monitorPointMapper;
 
 
    @Override
    public Map<String, Object> getDayAQIByDevice(Map<String, Object> parameters) {
        //ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        LocalDate time = LocalDate.now();
        int year = time.getYear();
        int month = time.getMonthValue();
        int day = time.getDayOfMonth();
        if (day == 1) {
            if (month == 1) {
                month = 12;
                year = year - 1;
            } else {
                month = month - 1;
            }
        }
        String monthStr = month < 10 ? ("0" + month) : month + "";
        String yearAndMonth = year + monthStr;
        // 昨日00:00:00
        parameters.put("start", time.minusDays(1));
 
        // 今日00:00:00
        parameters.put("end", time);
        parameters.put("yearAndMonth", yearAndMonth);
        parameters.put("sensorKeys", Arrays.asList("e1", "e2", "e10", "e11", "e15", "e16"));
        Map<String, Double> average = historyMinutelyMapper.getSersionAvgByDevice(parameters);
        return getAQIByDataMap(average);
    }
 
    @Override
    public Map<String, Object> getHourAQIByDevice(Map<String, Object> parameters) {
        //ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        LocalDate localDate = LocalDate.now();
        // 昨日00:00:00
        //parameters.put("start", localDate.minusDays(1));
 
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) - 1);
        int hour = calendar.get(Calendar.HOUR) - 1;
 
        // 今日00:00:00
        parameters.put("end", localDate);
        parameters.put("sensorKeys", Arrays.asList("e1", "e2", "e10", "e11", "e15", "e16"));
        Map<String, Double> average = historyMinutelyMapper.getSersionAvgByDevice(parameters);
        return getAQIByDataMap(average);
    }
 
    private Map<String, Object> getAQIByDataMap(Map<String, Double> average) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (isEmpty(average)) {
            resultMap.put("AQI", "N/V");
        } else {
            String[] IAQIValues = ResourceUtil.getArrValue("IAQI");
            Set<Double> IAQIs = new HashSet<Double>();
            for (Map.Entry<String, Double> entry : average.entrySet()) {
                double minMacKey = 0, maxMacKey = 0, minIAQI = 0, maxIAQI = 0;
                String[] macKeyValues = ResourceUtil.getArrValue(entry.getKey());
                Double avg = entry.getValue();
                if (isEmpty(avg)) {
                    IAQIs.add(null);
                } else {
                    int index = -1;
                    for (int i = 0; i < macKeyValues.length; i++) {
                        if (avg <= Double.valueOf(macKeyValues[i])) {
                            if (i == 0) {
                                index = i;
                            } else {
                                index = i - 1;
                            }
                            break;
                        }
                    }
                    if (index == -1) {
                        IAQIs.add(Double.MAX_VALUE);
                    } else {
                        minMacKey = Double.valueOf(macKeyValues[index]);
                        maxMacKey = Double.valueOf(macKeyValues[index + 1]);
                        minIAQI = Double.valueOf(IAQIValues[index]);
                        maxIAQI = Double.valueOf(IAQIValues[index + 1]);
                        Double result = CalculateUtils.calculateIAQI(maxIAQI, minIAQI, maxMacKey, minMacKey, avg);
                        IAQIs.add(result);
                    }
                }
            }
            IAQIs.remove(null);
            if (isEmpty(IAQIs)) {
                resultMap.put("AQI", "N/V");
            } else {
                Double AQI = Collections.max(IAQIs);
                if (AQI == Double.MAX_VALUE) {
                    resultMap.put("AQI", IAQIValues[IAQIValues.length - 1]);
                } else {
                    resultMap.put("AQI", String.format("%.0f", AQI));
                }
            }
        }
        return resultMap;
    }
 
    @Override
    public Map<String, List> getCompareReport(Map<String, Object> parameters) throws Exception {
        Map<String, List> resultMap = new HashMap<String, List>();
        List<Map<String, Object>> list = JSON.parseObject((String) parameters.remove("items"), new TypeReference<List<Map<String, Object>>>() {
        });
 
        String type = (String) parameters.get("type");
        // parameters.putAll(getElementByType(type));
        ParameterUtils.getElementByType(parameters);
        Integer timeLength = Integer.valueOf(parameters.remove("timeLength").toString());
        if ("month".equals(type)) {
            for (Map<String, Object> map : list) {
                String[] formatTime = map.get("formatTime").toString().split("-");
                LocalDate localDate = LocalDate.of(Integer.valueOf(formatTime[0]), Integer.valueOf(formatTime[1]), 1);
                int lengthOfMonth = localDate.lengthOfMonth();
                if (lengthOfMonth > timeLength) {
                    timeLength = lengthOfMonth;
                }
            }
        }
 
        List<Object> timeList = new ArrayList<Object>();
        for (int i = 0; i < timeLength; i++) {
            timeList.add(String.format("%02d", "day".equals(type) || "hour".equals(type) ? i : i + 1));
        }
        parameters.put("timeList", timeList);
 
        ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService<Map<String, Object>> cs = new ExecutorCompletionService<Map<String, Object>>(threadPool);
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            map.put("part", i);
            if (ObjectUtils.isEmpty(map.get("mac"))) {
                map.remove("mac");
            }
            map.put("time", map.remove("formatTime"));
            map.putAll(parameters);
            cs.submit(new Callable<Map<String, Object>>() {
                @Override
                public Map<String, Object> call() throws Exception {
                    return getMonitorPointOrDeviceAvgData4Compare(map);
                }
            });
        }
 
        List<Object> dataList = new ArrayList<Object>();
        for (Map<String, Object> map : list) {
            dataList.add(cs.take().get());
        }
        Object[] datas = new Object[list.size()];
        Object[] deviceCounts = new Object[list.size()];
        Object[] alarmDatas = new Object[list.size()];
        Set<String> sensors = new TreeSet<String>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.split("-")[0].compareTo(o2.split("-")[0]);
                //return Integer.compare(Integer.valueOf(o1.split("-")[0].replace("e", "")), Integer.valueOf(o2.split("-")[0].replace("e", "")));
            }
        });
        Map<String, Double> sortMap = new HashMap<String, Double>();
        for (Object object : dataList) {
            Map<String, Object> map = (Map<String, Object>) object;
            for (String key : map.keySet()) {
                int index = Integer.valueOf(key.substring(key.length() - 1));
                String actual = key.substring(0, key.length() - 1);
                Object obj = map.get(key);
                switch (actual) {
                    case "data":
                        datas[index] = obj;
                        break;
                    case "deviceCount":
                        deviceCounts[index] = obj;
                        break;
                    case "alarmData":
                        alarmDatas[index] = obj;
                        if (!ObjectUtils.isEmpty(obj)) {
                            Map<String, BigDecimal> mapData = (Map<String, BigDecimal>) obj;
                            BigDecimal sum = mapData.remove("sum");
                            for (Entry<String, BigDecimal> entry : mapData.entrySet()) {
                                if (!"name".equals(entry.getKey())) {
                                    sortMap.put(entry.getKey() + "-" + index, new BigDecimal(100).multiply(entry.getValue())
                                            .divide(sum, 2, BigDecimal.ROUND_HALF_UP).doubleValue());
 
                                }
                            }
                        }
                        break;
                    case "sensors":
                        sensors.addAll((List<String>) obj);
                        break;
                }
            }
        }
        List<Map.Entry<String, Double>> sortList = new ArrayList<Map.Entry<String, Double>>(sortMap.entrySet());
        Collections.sort(sortList, new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
                if (o2.getValue().compareTo(o1.getValue()) == 0) {
                    String[] key1 = o1.getKey().split("-");
                    String[] key2 = o2.getKey().split("-");
//                    String sensor1  = key1[0].replace("e", "");
//                    String sensor2  = key2[0].replace("e", "");
//                    if (Integer.valueOf(sensor1).compareTo(Integer.valueOf(sensor2)) == 0) {
//                        return Integer.compare(Integer.valueOf(key1[1]), Integer.valueOf(key2[1]));
//                    }
//                    return Integer.valueOf(sensor1).compareTo(Integer.valueOf(sensor2));
                    if (key1[0].compareTo(key2[0]) == 0) {
                        return Integer.compare(Integer.valueOf(key1[1]), Integer.valueOf(key2[1]));
                    } else {
                        return key1[0].compareTo(key2[0]);
                    }
                } else {
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
 
        });
        resultMap.put("times", timeList);
        resultMap.put("datas", Arrays.asList(datas));
        resultMap.put("deviceCounts", Arrays.asList(deviceCounts));
        resultMap.put("alarmDatas", Arrays.asList(alarmDatas));
        resultMap.put("sensors", new ArrayList<Object>(sensors));
        resultMap.put("sortList", sortList);
        return resultMap;
    }
 
 
    public Map<String, Object> getMonitorPointOrDeviceAvgData4Compare(Map<String, Object> parameters) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultList = getMonitorPointOrDeviceAvgData(parameters);
        List<Object> timeList = (List<Object>) parameters.get("timeList");
        List<String> sensors = (List<String>) parameters.get("sensors");
        String part = parameters.get("part").toString();
        Map<String, Double[]> doubleMap = new LinkedHashMap<String, Double[]>();
        for (Map<String, Object> map : resultList) {
            String time = map.get("time").toString();
            time = time.substring(time.length() - 2);
            int index = timeList.indexOf(time);
            for (String sensor : sensors) {
                String[] split = sensor.split("-");
                String sensorKey = split[0];
                if (map.containsKey(sensorKey)) {
                    Double[] doubles;
                    if (doubleMap.containsKey(sensor)) {
                        doubles = doubleMap.get(sensor);
                    } else {
                        doubles = new Double[timeList.size()];
                    }
                    doubles[index] = (Double) map.get(sensorKey);
                    doubleMap.put(sensor, doubles);
                }
            }
        }
 
        Object deviceCount;
        if (parameters.containsKey("deviceCount")) {
            deviceCount = parameters.remove("deviceCount");
        } else {
            deviceCount = deviceMapper.getDeviceCountByRegion(parameters);
        }
 
        resultMap.put("deviceCount" + part, deviceCount);
        resultMap.put("data" + part, doubleMap);
        resultMap.put("sensors" + part, sensors);
        Object type = parameters.get("type");
        if ("year".equals(type) || "month".equals(type)) {
            parameters.put("sensorKeys", Arrays.asList("e1", "e2", "e10", "e11", "e15", "e16"));
            List<Map<String, Object>> alarmData = alarmDailyMapper.getAlarmData(parameters);
            if (!ObjectUtils.isEmpty(alarmData)) {
                resultMap.put("alarmData" + part, alarmDailyMapper.getAlarmData(parameters).get(0));
            }
        }
        return resultMap;
    }
 
    @Override
    public List<Map<String, Object>> getMonitorPointOrDeviceAvgData(Map<String, Object> parameters) throws Exception {
        convertQueryParam(parameters);
        if (!ObjectUtils.isEmpty(parameters.get("compensate"))) {
            parameters.put("timeUnits", "10min");
        }
        return historyMinutelyMapper.getMonitorPointOrDeviceAvgData(parameters);
    }
 
    @Override
    public List<Map<String, Object>> get(Map<String, Object> parameters) throws Exception {
        convertQueryParam(parameters);
        if (!ObjectUtils.isEmpty(parameters.get("compensate"))) {
            parameters.put("timeUnits", "10min");
        }
        return historyMinutelyMapper.getMultiDeviceSensorData(parameters);
    }
 
    @Override
    public void convertQueryParam(Map<String, Object> parameters) throws ParseException {
        if (!parameters.containsKey("field")) {
            ParameterUtils.getElementByType(parameters);
            if (parameters.containsKey("timeUnits")) {
                if ("minutely".equals(parameters.get("timeUnits"))) {
                    if (parameters.containsKey("time")) {
                        String[] timeStr = parameters.get("time").toString().split("-");
                        int year = Integer.valueOf(timeStr[0]);
                        int month = Integer.valueOf(timeStr[1]);
                        if (year >= 2020) {
                            String yearAndMonth;
                            if (month < 10) {
                                yearAndMonth = "minutely_" + year + "0" + month;
                            } else {
                                yearAndMonth = "minutely_" + year + month;
                            }
                            parameters.put("timeUnits", yearAndMonth);
                        }
                    }
                }
            }
        }
        String time = (String) parameters.get("time");
        String format = (String) parameters.get("format");
        Integer field = Integer.valueOf(parameters.get("field").toString());
        Date start = DateUtils.parseDate(time, format), end = null;
        if (parameters.containsKey("timeb")) {
            end = DateUtils.parseDate((String) parameters.get("timeb"), format);
        } else {
            Calendar instance = Calendar.getInstance();
            instance.setTime(start);
            instance.add(field, 1);
            end = instance.getTime();
        }
        parameters.put("start", start);
        parameters.put("end", end);
 
        List<String> sensorKeys = new ArrayList<String>();
        List<String> sensors = new ArrayList<String>();
        if (parameters.containsKey("sensors")) {
            try {
                sensors = JSON.parseObject((String) parameters.get("sensors"), new TypeReference<List<String>>() {
                });
                for (String sensor : sensors) {
                    sensorKeys.add(sensor.split("-")[0]);
                }
            } catch (Exception e) {
                sensorKeys = sensors = (List<String>) parameters.remove("sensors");
            }
        } else {
            List<Sensor> sensorList = sensorMapper.getSensorsByCriteria(parameters);
            for (Sensor sensor : sensorList) {
                sensorKeys.add(sensor.getSensorKey());
                String string = sensor.getSensorKey() + "-" + sensor.getName() + "-" + sensor.getUnit();
                if (parameters.containsKey("description")) {
                    string += "-" + sensor.getDescription();
                }
                sensors.add(string);
            }
        }
        parameters.put("sensorKeys", sensorKeys);
        parameters.put("sensors", sensors);
    }
 
    @Override
    public Map<String, Object> getMonthAverageBySensor(Map<String, Object> parameters) {
        //ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        Object sensorKey = parameters.remove("macKey");
        ValidateUtil.notNull(sensorKey, "param.is.null");
        Map<String, Object> result = new HashMap<String, Object>();
        LocalDate end = LocalDate.now(), start;
        // 每月一日的数据取上月的数据
        if (1 == end.getDayOfMonth()) {
            // 上个月1日00:00:00
            start = end.plusDays(-1).with(TemporalAdjusters.firstDayOfMonth());
        } else {
            // 这个月1日00:00:00
            start = end.with(TemporalAdjusters.firstDayOfMonth());
        }
        parameters.put("start", start);
        parameters.put("end", end);
        parameters.put("sensorKeys", Arrays.asList(sensorKey));
 
        Map<String, Double> average = historyMinutelyMapper.getSersionAvgByDevice(parameters);
        if (isEmpty(average)) {
            result.put("average", NULL_VALUE);
        } else {
            result.put("average", String.format("%.2f", average.get(sensorKey)));
        }
        return result;
    }
 
    @Override
    public Map<String, Object> getAverageBySensor(Map<String, Object> parameters) {
        //ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        Object sensorKey = parameters.remove("macKey");
        ValidateUtil.notNull(sensorKey, "param.is.null");
        Map<String, Object> result = new HashMap<String, Object>();
        LocalDate end = LocalDate.now(), start;
        // 每月一日的数据取上月的数据
        if (1 == end.getDayOfMonth()) {
            // 上个月1日00:00:00
            start = end.plusDays(-1).with(TemporalAdjusters.firstDayOfMonth());
        } else {
            // 这个月1日00:00:00
            start = end.with(TemporalAdjusters.firstDayOfMonth());
        }
        parameters.put("start", start);
        parameters.put("end", end);
        parameters.put("sensorKeys", Arrays.asList(sensorKey));
 
        Map<String, Double> average = historyMinutelyMapper.getAvgByDevice(parameters);
        if (isEmpty(average)) {
            result.put("average", NULL_VALUE);
        } else {
            result.put("average", String.format("%.2f", average.get(sensorKey)));
        }
        return result;
    }
 
    /**
     * 根据线性表单的条件规则,获取多条线性表单数据
     *
     * @param lineChartCriteria
     * @return
     */
    @Override
    public Map<String, List<List<Double>>> queryLineChartDateByCrieria(LineChartCriteria lineChartCriteria) {
        Map<String, List<List<Double>>> listMap = new HashMap<>();
        List<String> sensorKeys = lineChartCriteria.getSensorKeys();
        List<DataCondition> dataConditionList = lineChartCriteria.getDataConditions();
        TimePeriod timePeriod = lineChartCriteria.getTimePeriod();
        sensorKeys.forEach(sensorKey -> {
            listMap.put(sensorKey, new ArrayList<List<Double>>(dataConditionList.size()));
        });
        dataConditionList.forEach(dataCondition -> {
            Map<String, List<Double>> dataMap = queryOneLineChartDateByCrieria(sensorKeys, timePeriod, dataCondition);
            // 数据装载
            listMap.forEach((sensorKey, list) -> {
                List<Double> rowData = dataMap.get(sensorKey);
                list.add(rowData);
            });
        });
        return listMap;
    }
 
    /**
     * 根据线性表单的条件规则,获取一条线性表单数据,包含 所有检测项目
     *
     * @param sensorKeys
     * @param timePeriod
     * @param dataCondition
     * @return
     */
    public Map<String, List<Double>> queryOneLineChartDateByCrieria(List<String> sensorKeys, TimePeriod timePeriod, DataCondition dataCondition) {
        List<String> timeList = ReportTimeFormat.makeTimeList(timePeriod);
        Instant instant = timePeriod.getStartTime().toInstant();
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        LocalDate localDate = zdt.toLocalDate();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        String timeUnits;
        if (year < 2020) {
            timeUnits = "minutely";
        } else {
            if (month < 10) {
                timeUnits = "minutely_" + year + "0" + month;
            } else {
                timeUnits = "minutely_" + year + month;
            }
        }
        List<Map<String, Object>> lineChartDatas = historyMinutelyMapper.selectLineChartDateByCrieria(sensorKeys, timePeriod, timeUnits, dataCondition);
        Map<String, List<Double>> lineChartDatasWithEmpty = new HashMap<>();
        // lineChartDatasWithEmpty 初始化
        sensorKeys.forEach(sensorKey -> {
            lineChartDatasWithEmpty.put(sensorKey, timeList.stream().map(time -> {
                Double data = null;
                return data;
            }).collect(Collectors.toList()));
        });
        // m 为查询data的index,此处要防止m越界
        int m = 0;
        int dataLength = lineChartDatas.size() - 1;
        m = dataLength > -1 ? 0 : -1;
        if (m > -1) {
            for (int n = 0; n < timeList.size(); n++) {
                if (m > -1) {
                    String time = timeList.get(n);
                    Map<String, Object> rowData = lineChartDatas.get(m);
                    String keyTime = rowData.get("format_time").toString();
                    if (time.equals(keyTime)) {
                        // list to map
                        int finalN = n;
                        sensorKeys.forEach(sensorKey -> {
                            Object value = rowData.get(sensorKey);
                            List<Double> lineChartDatasWithEmptyTemp = lineChartDatasWithEmpty.get(sensorKey);
                            if (finalN < lineChartDatasWithEmptyTemp.size()) {
                                Double sensorValue = value != null ? new Double(value.toString()) : null;
                                lineChartDatasWithEmptyTemp.set(finalN, sensorValue);
                            }
                        });
                        // 置为 -1,防止越界
                        m = m < dataLength ? m + 1 : -1;
                    }
                }
            }
        }
        return lineChartDatasWithEmpty;
    }
 
    private Map<String, Object> getElementByType(Object type) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        switch (type.toString()) {
            case "year":
                resultMap.put("format", "yyyy");
                resultMap.put("typeFormat", "%Y-%m");
                resultMap.put("timeLength", 12);
                resultMap.put("field", Calendar.YEAR);
                break;
            case "month":
                resultMap.put("format", "yyyy-MM");
                resultMap.put("typeFormat", "%Y-%m-%d");
                resultMap.put("timeLength", 28);
                resultMap.put("field", Calendar.MONTH);
                break;
            case "day":
                resultMap.put("format", "yyyy-MM-dd");
                resultMap.put("typeFormat", "%Y-%m-%d %H");
                resultMap.put("timeLength", 24);
                resultMap.put("field", Calendar.DATE);
                break;
            case "hour":
                resultMap.put("format", "yyyy-MM-dd HH");
                resultMap.put("typeFormat", "%Y-%m-%d %H:%i");
                resultMap.put("timeLength", 60);
                resultMap.put("field", Calendar.HOUR);
                break;
        }
        return resultMap;
    }
 
    /*
     * @description 查询无人机在时间段内的sensor值
     * @author ZhuDongming
     * @date 2019-07-25 09:21:45
     * @param parameters
     * @return
     */
    @Override
    public List<List<Map<String, Object>>> getSensorData(Map<String, Object> parameters) {
        String startTime = parameters.get("startTime").toString();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTimeLocalDateTime = LocalDateTime.parse(startTime, dateTimeFormatter);
        int year = startTimeLocalDateTime.getYear();
        int month = startTimeLocalDateTime.getMonthValue();
        String monthStr = month < 10 ? ("0" + month) : month + "";
        String yearAndMonth = year + monthStr;
        List<Sensor> sensors = sensorMapper.getSensorsByMac(parameters);
        List<String> sensorKeys = new ArrayList<>();
        for (Sensor sensor : sensors) {
            sensorKeys.add(sensor.getSensorKey());
        }
        parameters.put("sensorKeys", sensorKeys);
        List<Map<String, Object>> listMap = null;
        if (year <= 2019) {
            listMap = historyMinutelyMapper.getSensorData(parameters);
        } else {
            parameters.put("yearAndMonth", yearAndMonth);
            listMap = historyMinutelyMapper.getSensorData2020(parameters);
        }
        List<List<Map<String, Object>>> listMaps = new ArrayList<>();
        List<Map<String, Object>> listMapAvg = new ArrayList<>();
        List<Map<String, Object>> listMapMin = new ArrayList<>();
        List<Map<String, Object>> listMapMax = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listMap)) {
            for (Map<String, Object> map : listMap) {
                Map<String, Object> mapAvg = new LinkedHashMap<>();
                Map<String, Object> mapMin = new LinkedHashMap<>();
                Map<String, Object> mapMax = new LinkedHashMap<>();
                mapAvg.put("time", map.get("time"));
                mapMin.put("time", map.get("time"));
                mapMax.put("time", map.get("time"));
                for (Entry<String, Object> entry : map.entrySet()) {
                    for (Sensor sensor : sensors) {
                        if (sensor.getSensorKey().equals(entry.getKey())) {
                            mapAvg.put(entry.getKey(), new BigDecimal(entry.getValue().toString()).stripTrailingZeros().toPlainString() + sensor.getUnit());
                        } else if (("min" + sensor.getSensorKey()).equals(entry.getKey())) {
                            mapMin.put(entry.getKey().substring(3), new BigDecimal(entry.getValue().toString().replace("\"", "")).stripTrailingZeros().toPlainString());
                        } else if (("max" + sensor.getSensorKey()).equals(entry.getKey())) {
                            mapMax.put(entry.getKey().substring(3), new BigDecimal(entry.getValue().toString().replace("\"", "")).stripTrailingZeros().toPlainString());
                        }
                    }
                }
                if ("0°".equals(mapAvg.get("e76")) || "0".equals(mapMin.get("e76")) || "0".equals(mapMax.get("e76")) || "0°".equals(mapAvg.get("e77")) || "0".equals(mapMin.get("e77")) || "0".equals(mapMax.get("e77"))) {
                    continue;
                }
                listMapAvg.add(mapAvg);
                listMapMin.add(mapMin);
                listMapMax.add(mapMax);
            }
            listMaps.add(listMapAvg);
            listMaps.add(listMapMin);
            listMaps.add(listMapMax);
        }
        return listMaps;
    }
 
    @Override
    public List<Map<String, Object>> getDevicesAvgDataToExcel(Map<String, Object> parameters) throws Exception {
        if ("month".equals(parameters.get("type"))) {
            parameters.put("timeUnits", "daily");
            parameters.put("typeFormat", "%Y-%m-%d");
            String time = parameters.get("time") + "-01T00:00:00";
            LocalDateTime value = LocalDateTime.parse(time);
            LocalDateTime start = value.with(TemporalAdjusters.firstDayOfMonth());
            LocalDateTime end = value.with(TemporalAdjusters.lastDayOfMonth());
            parameters.put("start", start);
            parameters.put("end", end);
            int day = end.getDayOfMonth();
            List<String> timeList = new ArrayList<>();
            for (int i = 0; i <= day - 1; i++) {
                timeList.add(start.plusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
            parameters.put("timeList", timeList);
        } else if ("day".equals(parameters.get("type"))) {
            String time = parameters.get("time") + "T01:00:00";
            LocalDateTime value = LocalDateTime.parse(time);
            LocalDateTime end = value.plusHours(23);
            parameters.put("timeUnits", "hourly");
            parameters.put("typeFormat", "%Y-%m-%d %H:%i");
            parameters.put("start", time);
            parameters.put("end", end);
            List<String> timeList = new ArrayList<>();
            for (int i = 0; i <= 23; i++) {
                timeList.add(value.plusHours(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            }
            parameters.put("timeList", timeList);
        }
        return historyMinutelyMapper.getDevicesAvgDataToExcel(parameters);
    }
 
    @Override
    public List<Map<String, Object>> getDevicesSensorsAvgDataToExcel(Map<String, Object> parameters) throws Exception {
        if ("month".equals(parameters.get("type"))) {
            parameters.put("timeUnits", "daily");
            parameters.put("typeFormat", "%Y-%m-%d");
            String time = parameters.get("time") + "-01T00:00:00";
            LocalDateTime value = LocalDateTime.parse(time);
            LocalDateTime start = value.with(TemporalAdjusters.firstDayOfMonth());
            LocalDateTime end = value.with(TemporalAdjusters.lastDayOfMonth());
            parameters.put("start", start);
            parameters.put("end", end);
            int day = end.getDayOfMonth();
            List<String> timeList = new ArrayList<>();
            for (int i = 0; i <= day - 1; i++) {
                timeList.add(start.plusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
            parameters.put("timeList", timeList);
        } else if ("day".equals(parameters.get("type"))) {
            String time = parameters.get("time") + "T00:00:00";
            LocalDateTime value = LocalDateTime.parse(time);
            LocalDateTime end = value.plusHours(23);
            parameters.put("timeUnits", "hourly");
            parameters.put("typeFormat", "%Y-%m-%d %H:%i");
            parameters.put("start", time);
            parameters.put("end", end);
            List<String> timeList = new ArrayList<>();
            for (int i = 0; i <= 23; i++) {
                timeList.add(value.plusHours(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            }
            parameters.put("timeList", timeList);
        }
        return historyMinutelyMapper.getDevicesSensorsAvgDataToExcel(parameters);
    }
 
 
    @Override
    public List<Map<String, Object>> get5MinutesOrHalfHour(Map<String, Object> parameters) throws ParseException {
        if (parameters.get("city") == null) {
            return new ArrayList<Map<String, Object>>();
        }
        String string = parameters.get("time").toString();
        String year = string.substring(0, 4);
        String[] split = string.substring(5).split("-");
        String month = split[0];
        String day = split[1];
        if (split[0].length() < 2) {
            month = 0 + split[0];
        }
        if (split[1].length() < 2) {
            day = 0 + split[1];
        }
        String time = year + "-" + month + "-" + day;
        String cityName = parameters.get("city").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String type = parameters.get("type").toString();
        String range = parameters.get("range").toString();
        Area area = areaMapper.getAreaByName(cityName);
        Integer code;
        String name;
        if (area == null) {
            City city = cityMapper.getCityByName(cityName);
            if (city == null) {
                Province province = provinceMapper.getProvinceByName(cityName);
                code = province.getProvinceCode();
                name = province.getProvinceName();
            } else {
                code = city.getCityCode();
                name = city.getCityName();
            }
        } else {
            code = area.getAreaCode();
            name = area.getAreaName();
        }
        parameters.put("cityCode", code);
        parameters.put("name", name);
        Map<String, Object> map = new HashMap<>();
        if (code.toString().endsWith("0000")) {
            map.put("provinceCode", code);
        } else if (code.toString().endsWith("00")) {
            map.put("cityCode", code);
        } else {
            map.put("areaCode", code);
        }
        //List<String> sensorKeys = sensorMapper.getSensorKeys();
 
        List<String> sensorKeys = new ArrayList<String>();
        Collections.addAll(sensorKeys, "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e10", "e11", "e12", "e13", "e14", "e15"
                , "e16", "e17", "e18", "e21", "e23", "e25", "e26", "e27", "e28", "e31", "e33", "e45", "e49", "e97", "e98", "e102");
 
        String timeUnits = "minutely_" + time.substring(0, 7).replace("-", "");
        map.put("sensorKeys", sensorKeys);
        map.put("timeUnits", timeUnits);
        Calendar cal = Calendar.getInstance();
        List<Map<String, Object>> resultList = new ArrayList<>();
        int seg;
        long startTime;
        long endTime;
        int minuteChange;
        if ("m".equals(type)) {
            cal.setTime(sdf.parse(time + " 00:05:00"));
            startTime = cal.getTimeInMillis();
            cal.add(Calendar.DAY_OF_MONTH, 1);
            endTime = cal.getTimeInMillis();
            seg = 5 * 60 * 1000;
            minuteChange = -5;
        } else {
            cal.setTime(sdf.parse(time + " 00:30:00"));
            startTime = cal.getTimeInMillis();
            cal.add(Calendar.DAY_OF_MONTH, 1);
            endTime = cal.getTimeInMillis();
            seg = 30 * 60 * 1000;
            minuteChange = -30;
        }
        for (long time1 = startTime; time1 < endTime; time1 += seg) {
            Date end = new Date(time1);
            cal.setTime(end);
            cal.add(Calendar.MINUTE, minuteChange);
            Date start = cal.getTime();
            map.put("start", start);
            map.put("end", end);
            Map<String, Object> dataMap = historyMinutelyMapper.get5MiutesOrHalfHourByDay(map);
            if (dataMap == null) {
                break;
            }
            dataMap.put("time", sdf.format(end));
            dataMap.put("city", name);
            Set<String> set = dataMap.keySet();
            Iterator<String> it = set.iterator();
            List<String> listKey = new ArrayList<>();
            while (it.hasNext()) {
                String key = it.next();
                if (dataMap.get(key) == null || "".equals(dataMap.get(key))) {
                    listKey.add(key);
                }
            }
            for (String key : listKey) {
                dataMap.remove(key);
            }
            resultList.add(dataMap);
        }
        return resultList;
    }
 
    @Override
    public List<Map<String, Object>> getMultiDeviceSensorData(Map<String, Object> parameters) throws Exception {
        String sensorKey = parameters.get("sensorKey").toString();
        String[] macs = parameters.get("macs").toString().split(",");
        List<String> sensorKeys = new ArrayList<>();
        sensorKeys.add(sensorKey);
        parameters.put("sensorKeys", sensorKeys);
        parameters.put("sensors", sensorKeys);
        String type = parameters.get("type").toString();
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 31; i++) {
            list.add(null);
        }
        for (String mac : macs) {
            parameters.put("mac", mac);
            List<Map<String, Object>> data = getMonitorPointOrDeviceAvgData(parameters);
            List<Map<String, Object>> l = new ArrayList<>();
            for (int i = 0; i < 31; i++) {
                l.add(null);
            }
            for (Map<String, Object> dataMap : data) {
                String time = dataMap.get("time").toString();
                Integer t = Integer.valueOf(time.substring(time.length() - 2));
                dataMap.put("time", t);
                if ("day".equals(type)) {
                    l.set(t, dataMap);
                } else {
                    l.set(t - 1, dataMap);
                }
            }
            for (int i = 0; i < l.size(); i++) {
                if (l.get(i) == null) {
                    Map<String, Object> m = new HashMap<>();
                    List<String> v = new ArrayList<>();
                    v.add("");
                    if ("day".equals(type)) {
                        m.put("time", i);
                    } else {
                        m.put("time", i + 1);
                    }
                    m.put("values", v);
                    l.set(i, m);
                }
            }
            data = l;
            for (Map<String, Object> map : data) {
                Map<String, Object> hashMap = new HashMap<>();
                if (map != null) {
                    int t = Integer.valueOf(map.get("time").toString());
                    hashMap.put("time", t);
                    String value;
                    if (map.get(sensorKey) == null) {
                        value = "";
                    } else {
                        value = map.get(sensorKey).toString();
                    }
                    List<String> values;
 
                    if ("day".equals(type)) {
                        t = t + 1;
                    }
                    if (list.get(t - 1) != null) {
                        values = (ArrayList<String>) list.get(t - 1).get("values");
                    } else {
                        values = new ArrayList<>();
                    }
                    values.add(value);
                    hashMap.put("values", values);
                    list.set(t - 1, hashMap);
                }
            }
        }
        boolean flag = false;
        Iterator<Map<String, Object>> iterator = list.iterator();
        int digit = 0;
        while (iterator.hasNext()) {
            Map<String, Object> next = iterator.next();
            ArrayList<String> values = (ArrayList<String>) next.get("values");
            for (String value : values) {
                if ("".equals(value)) {
                    flag = true;
                } else {
                    digit = value.split("\\.")[1].length();
                    flag = false;
                    break;
                }
            }
            if (flag) {
                iterator.remove();
            }
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(digit);
        for (Map<String, Object> map : list) {
            int time = Integer.valueOf(map.get("time").toString());
            ArrayList<String> values = (ArrayList<String>) map.get("values");
            if (values.size() > 1) {
                int length = 0;
                double sum = 0.0;
                for (String value : values) {
                    if (!"".equals(value)) {
                        Double v = Double.valueOf(value);
                        length += 1;
                        sum += v;
                    }
                }
                Double avg = sum / length;
                String format = nf.format(avg);
                values.add(format);
                map.put("values", values);
            }
        }
        return list;
    }
 
    @Override
    public List<Map<String, Object>> getAllDeviceDataToExcel(Map<String, Object> parameters) throws Exception {
        Calendar cal = Calendar.getInstance();
        int length = ((String) parameters.get("startTime")).split("-").length;
        String time = parameters.remove("startTime").toString();
        String timeb;
        if (parameters.get("endTime") == null) {
            timeb = time;
        } else {
            timeb = parameters.remove("endTime").toString();
        }
        String dateFormat = "";
        String typeFormat = "";
        String timeUnits = "daily";
        int i = 0;
        if (length == 1) {
            dateFormat = "yyyy";
            typeFormat = "%Y";
            i = Calendar.YEAR;
        } else if (length == 2) {
            dateFormat = "yyyy-MM";
            typeFormat = "%Y-%m";
            i = Calendar.MONTH;
        } else if (length == 3) {
            dateFormat = "yyyy-MM-dd";
            typeFormat = "%Y-%m-%d";
            i = Calendar.DAY_OF_MONTH;
        } else if (length == 4) {
            dateFormat = "yyyy-MM-dd HH";
            typeFormat = "%Y-%m-%d %H";
            timeUnits = "hourly";
            i = Calendar.HOUR_OF_DAY;
            time = time.substring(0, 10) + " " + time.substring(11, 13);
            timeb = timeb.substring(0, 10) + " " + timeb.substring(11, 13);
        }
        parameters.put("time", time);
        parameters.put("timeb", timeb);
 
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        cal.setTime(sdf.parse(timeb));
        cal.add(i, 1);
        Date endTime = cal.getTime();
        parameters.put("format", dateFormat);
        parameters.put("typeFormat", typeFormat);
        parameters.put("timeUnits", timeUnits);
        parameters.put("field", i);
        cal.setTime(sdf.parse(time));
        List<String> times = new ArrayList<>();
        for (long d = cal.getTimeInMillis(); d < endTime.getTime(); cal.set(i, cal.get(i) + 1), d = cal.getTimeInMillis()) {
            String format = sdf.format(d);
            times.add(format);
        }
        String[] sensorKeys = parameters.get("sensorKey").toString().split(",");
        List<String> keys = Arrays.asList(sensorKeys);
        parameters.put("sensors", keys);
        parameters.put("sensorKeys", keys);
        parameters.put("timeb", sdf.format(endTime));
        int mpId = Integer.valueOf(parameters.get("monitorPoint").toString());
        String monitorPointName = monitorPointMapper.getMonitorName(mpId);
        List<Map<String, Object>> devices = deviceMapper.getDevicesByMpId(mpId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> map : devices) {
            String mac = map.get("mac").toString();
            parameters.put("mac", mac);
            String name = map.get("name").toString();
            List<Map<String, Object>> data = getMonitorPointOrDeviceAvgData(parameters);
            for (String sensorKey : keys) {
                Map<String, Object> sensor = sensorMapper.getSensorBySensorKey(sensorKey);
                if (sensor == null) {
                    continue;
                }
                String description = sensor.get("description").toString();
                String unit = sensor.get("unit").toString();
                Map<String, Object> hashMap = new LinkedHashMap<>();
                for (String t : times) {
                    hashMap.put("monitorPointName", monitorPointName);
                    hashMap.put("name", name);
                    hashMap.put("sensor", description + "(" + unit + ")");
                    hashMap.put(t, "");
                }
                if (data.size() != 0) {
                    for (Map<String, Object> dataMap : data) {
                        String t = dataMap.get("time").toString();
                        if (dataMap.get(sensorKey) != null) {
                            String value = dataMap.get(sensorKey).toString();
                            hashMap.put(t, value);
                        }
                    }
                }
                resultList.add(hashMap);
            }
        }
        return resultList;
    }
}