jinpengyong
2020-11-18 e786ed5d01635555dac37c69003bdbbf757d69d8
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
package com.moral.service.impl;
 
import java.math.BigDecimal;
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.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
 
import javax.annotation.Resource;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.moral.common.util.ValidateUtil;
import com.moral.entity.Device;
import com.moral.entity.Profession;
import com.moral.entity.Sensor;
import com.moral.mapper.DeviceMapper;
import com.moral.mapper.HistoryMapper;
import com.moral.mapper.HistoryMinutelyMapper;
import com.moral.mapper.MonitorPointMapper;
import com.moral.mapper.OrganizationRelationMapper;
import com.moral.mapper.SensorMapper;
import com.moral.mapper.SensorUnitMapper;
import com.moral.service.AccountService;
import com.moral.service.HistoryService;
import com.moral.service.ProfessionService;
import com.moral.util.AQICalculation;
import com.moral.util.DatesUtil;
 
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
 
@Service
public class HistoryServiceImpl implements HistoryService {
 
    @Resource
    private AccountService accountService;
 
    @Resource
    private HistoryMapper historyMapper;
 
    @Resource
    private HistoryMinutelyMapper historyMinutelyMapper;
 
    @Resource
    private DeviceMapper deviceMapper;
 
    @Resource
    private SensorMapper sensorMapper;
 
    @Resource
    private ProfessionService professionService;
 
    @Resource
    private OrganizationRelationMapper organizationRelationMapper;
 
    @Resource
    private MonitorPointMapper monitorPointMapper;
 
    @Override
    public Map<String, Object> getAllSensorAverageByDevice(Map<String, Object> parameters) throws Exception {
        ValidateUtil.notNull(parameters.get("areaCode"), "param.is.null");
        ValidateUtil.notNull(parameters.get("accountId"), "param.is.null");
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        accountService.setOrgIdsByAccount(parameters);
        LocalDateTime time = LocalDateTime.now();
        parameters.put("end", time);
        // 当前时间 -5分钟
        LocalDateTime start = time.minusMinutes(5);
        parameters.put("start", start);
        List<Sensor> Sensors = sensorMapper.getSensorsByCriteria(parameters);
        List<String> sensorKeys = new ArrayList<String>();
        for (Sensor sensor : Sensors) {
            sensorKeys.add(sensor.getSensorKey());
        }
        parameters.put("sensorKeys", sensorKeys);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMM");
        parameters.put("timeUnits", "five_minutely_" + df.format(time));
        List<Map<String, Object>> list = historyMapper.getAreaAllDataByAccount(parameters);
        resultMap.putAll(list.get(0));
        return resultMap;
    }
 
    @Override
    public Map<String, Object> getDeviceRankingBySensorAverage(Map<String, Object> parameters) {
        ValidateUtil.notNull(parameters.get("areaCode"), "param.is.null");
        ValidateUtil.notNull(parameters.get("accountId"), "param.is.null");
        Object macKey = parameters.get("macKey");
        ValidateUtil.notNull(macKey, "param.is.null");
 
        Map<String, Object> result = new LinkedHashMap<String, Object>();
        accountService.setOrgIdsByAccount(parameters);
        LocalDateTime time = LocalDateTime.now();
        // 当前时间 -1小时
        parameters.put("start", time.minusHours(1));
        parameters.put("end", time);
        List<String> sensorKeys = new ArrayList<String>();
        sensorKeys.add(macKey.toString());
        parameters.put("sensorKeys", sensorKeys);
        parameters.put("timeUnits", "hourly");
        List<Map<String, Object>> list = historyMapper.getAreaAllDataByAccount(parameters);
        for (Map<String, Object> map : list) {
            result.put((String) map.get("name"), map.get(macKey.toString()));
        }
        return result;
    }
 
    @Override
    public String queryValueByMacAndTime(String mac, Date time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String timeUnits = sdf.format(time);
        return historyMapper.selectValueByMacAndTime(mac, time, timeUnits);
    }
 
    public String getValueByMacAndTime(String mac, String time, String time1) {
        String timeUnits = time1.substring(0, 10).replace("-", "");
        return historyMapper.getValueByMacAndTime(mac, time, time1, timeUnits);
    }
 
    @Override
    public List<Map<String, Object>> getRegionRankingData(Map<String, Object> parameters) {
        ValidateUtil.notNull(parameters.get("regionCode"), "param.is.null");
        ValidateUtil.notNull(parameters.get("dimension"), "param.is.null");
        ValidateUtil.notNull(parameters.get("sensorKey"), "param.is.null");
        ValidateUtil.notNull(parameters.get("accountId"), "param.is.null");
 
        String regionCode = parameters.get("regionCode").toString();
        parameters.put("provinceCode", regionCode.substring(0, 2).concat("0000"));
        String regionType = "village";
        String nextLevel = "";
        if (regionCode.length() == 6) {
            if (regionCode.endsWith("0000")) {
                regionType = "province";
                nextLevel = "city";
            } else if (regionCode.endsWith("00")) {
                regionType = "city";
                nextLevel = "area";
            } else {
                regionType = "area";
                nextLevel = "town";
            }
        } else {
            if (regionCode.endsWith("000")) {
                regionType = "town";
                nextLevel = "village";
            }
        }
        parameters.put("regionType", regionType);
        parameters.put("nextLevel", nextLevel);
 
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMM");
        Object timeType = parameters.get("timeType");
 
        String table = "history";
        String column = "json";
        /*if ("month".equals(timeType)) {
            if (1 != localDate.getDayOfMonth()) {
                table = "history_daily";
                column = "json";
            }
            parameters.put("start", localDate.with(TemporalAdjusters.firstDayOfMonth()));
        } else if ("day".equals(timeType)) {
            parameters.put("start", localDate);
        } else if ("hour".equals(timeType)) {
            parameters.put("start", LocalDateTime.now().truncatedTo(ChronoUnit.HOURS));
        } else {
            parameters.put("start", LocalDateTime.now().minusMinutes(5));
        }*/
 
        if ("month".equals(timeType)) {
            table = "history_daily";
            parameters.put("start", localDate.with(TemporalAdjusters.firstDayOfMonth()));
        } else if ("day".equals(timeType)) {
            table = "history_hourly";
            parameters.put("start", localDate);
        } else if ("hour".equals(timeType)) {
            table = "history_minutely_" + df.format(localDate);
            parameters.put("start", LocalDateTime.now().truncatedTo(ChronoUnit.HOURS));
        }
 
        parameters.put("table", table);
        parameters.put("column", column);
 
        String dimension = "";
        if ("discharge".equals(parameters.get("dimension"))) {
            dimension = "discharge";
            parameters.put("dimension", "monitorPoint");
        }
 
        accountService.setOrgIdsByAccount(parameters);
        List<Map<String, Object>> result = historyMapper.getRegionRankingData(parameters);
        for (Map<String, Object> map : result) {
            if (ObjectUtils.isEmpty(map.get("avg"))) {
                map.put("avg", 0);
            }
        }
        if ("profession".equals(parameters.get("dimension"))) {
            List<Profession> professions = professionService.getProfessiontList(parameters);
            for (Map<String, Object> map : result) {
                for (Profession profession : professions) {
                    if (map.get("name").equals(profession.getName())) {
                        professions.remove(profession);
//                        if (ObjectUtils.isEmpty(map.get("avg"))) {
//                            map.put("avg", 0);
//                        }
                        break;
                    }
                }
            }
            for (Profession profession : professions) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", profession.getName());
                map.put("avg", 0);
                result.add(map);
            }
        } else if ("region".equals(parameters.get("dimension"))) {
            List<String> regions = historyMapper.selectNextLevelRegion(parameters);
            for (Map<String, Object> map : result) {
                if (regions.contains(map.get("name"))) {
                    regions.remove(map.get("name"));
//                    if (ObjectUtils.isEmpty(map.get("avg"))) {
//                        map.put("avg", 0);
//                    }
                }
 
            }
            for (String region : regions) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", region);
                map.put("avg", 0);
                result.add(map);
            }
        }
        if ("discharge".equals(dimension)) {
            parameters.put("year", LocalDate.now().getYear());
            List<Map<String, Object>> discharges = historyMapper.getDischargeByRegion(parameters);
            for (Map<String, Object> map : result) {
                for (Map<String, Object> discharge : discharges) {
                    if (map.get("name").equals(discharge.get("name"))) {
                        map.put("value", discharge.get("value"));
                        discharges.remove(discharge);
                        break;
                    }
                }
            }
            Collections.sort(result, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return Double.compare(((Double) o2.get("avg")) - Double.valueOf((String) o2.get("value")),
                            ((Double) o1.get("avg")) - Double.valueOf((String) o1.get("value")));
                }
            });
        }
        return result;
    }
 
    @Override
    public List<Map<String, Object>> getSensorsDataByDevice(Map<String, Object> parameters) {
        ValidateUtil.notNull(parameters.get("deviceVersionId"), "param.is.null");
        ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        ValidateUtil.notNull(parameters.get("deviceId"), "param.is.null");
        List<Map<String, Object>> sensors = sensorMapper.getSensorsByDeviceVersionId(parameters);
        parameters.put("size", 1);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String timeUnits = sdf.format(date);
        parameters.put("timeUnits", timeUnits);
        List<Map<String, Object>> values = historyMapper.getValueByMacAndSize(parameters);
        JSONObject map = null;
        if (!ObjectUtils.isEmpty(values)) {
            map = JSON.parseObject(values.get(0).get("value").toString());
        }
        Device device = deviceMapper.selectByPrimaryKey(Integer.valueOf((String) parameters.get("deviceId")));
        Map<String, Object> sensorUnits = getSensorUnitByDeviceMac(parameters);
        for (Map<String, Object> sensor : sensors) {
            Object sensorKey = sensor.get("sensor_key");
            sensor.put("name", sensor.get("description"));
            sensor.put("state", device.getState());
            if (!ObjectUtils.isEmpty(map)) {
                sensor.put("value", map.remove(sensor.get("sensor_key")));
            }
            if (sensorUnits.containsKey(sensorKey)) {
                Map<String, Object> sensorUnit = (Map<String, Object>) sensorUnits.get(sensorKey);
                sensor.put("unit", sensorUnit.get("name"));
                if (sensor.containsKey("value")) {
                    Object value = sensor.get("value");
                    String rules = sensorUnit.get("rules").toString();
                    rules = rules.replace("d", "").replace("{0}", "value");
                    Expression expression = AviatorEvaluator.compile(rules);
                    Map<String, Object> env = new HashMap<String, Object>();
                    env.put("value", Double.valueOf(value.toString()));
                    value = expression.execute(env);
                    sensor.put("value", String.format("%.2f", value));
                }
            }
        }
        return sensors;
    }
 
    @Override
    public List<Map<String, Object>> getSensorDataBySensorKey(Map<String, Object> parameters) {
        Object sensorKey = parameters.get("sensorKey");
        ValidateUtil.notNull(sensorKey, "param.is.null");
        ValidateUtil.notNull(parameters.get("mac"), "param.is.null");
        ValidateUtil.notNull(parameters.get("size"), "param.is.null");
        parameters.put("size", Integer.valueOf(parameters.remove("size").toString()));
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String timeUnits = sdf.format(date);
        parameters.put("timeUnits", timeUnits);
        List<Map<String, Object>> values = historyMapper.getValueByMacAndSize(parameters);
        Map<String, Object> sensorUnits = getSensorUnitByDeviceMac(parameters);
        for (Map<String, Object> value : values) {
            JSONObject json = JSON.parseObject(value.remove("value").toString());
            Object sensorKeyValue = json.get(sensorKey);
            if (sensorUnits.containsKey(sensorKey)) {
                Map<String, Object> sensorUnit = (Map<String, Object>) sensorUnits.get(sensorKey);
                String rules = sensorUnit.get("rules").toString();
                rules = rules.replace("d", "").replace("{0}", "value");
                Expression expression = AviatorEvaluator.compile(rules);
                Map<String, Object> env = new HashMap<String, Object>();
                env.put("value", Double.valueOf(sensorKeyValue.toString()));
                sensorKeyValue = expression.execute(env);
                sensorKeyValue = String.format("%.2f", sensorKeyValue);
            }
            value.put("value", sensorKeyValue);
        }
        return values;
    }
 
    @Override
    public Map<String, Object> getActualDataByRegion(Map<String, Object> parameters) {
        Object sensorKey = parameters.get("sensorKey");
        ValidateUtil.notNull(sensorKey, "param.is.null");
        ValidateUtil.notNull(parameters.get("accountId"), "param.is.null");
        ValidateUtil.notNull(parameters.get("interval"), "param.is.null");
        Integer interval = Integer.valueOf(parameters.get("interval").toString());
        LocalDateTime start, end;
        if (!parameters.containsKey("time")) {
            end = LocalDateTime.now();
            int second = end.getSecond() / interval * interval;
            end = end.truncatedTo(ChronoUnit.MINUTES).plusSeconds(second);
            start = end.minusSeconds(interval);
        } else {
            //start = LocalDateTime.ofEpochSecond(Long.valueOf(parameters.get("time").toString()) / 1000, 0, ZoneOffset.ofHours(8));
            start = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(parameters.get("time").toString())), ZoneId.of("+8"));
            end = start.plusSeconds(interval);
        }
        parameters.put("start", start);
        parameters.put("end", end);
        parameters.put("sensorKeys", Arrays.asList(((String) sensorKey).split(",")));
        accountService.setOrgIdsByAccount(parameters);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        //从history年月日表获取
        parameters.put("timeUnits", df.format(start));
        Map<String, Object> result = historyMapper.getActualDataByRegion(parameters);
        if (ObjectUtils.isEmpty(result)) {
            result = new HashMap<String, Object>();
        }
        result.put("time", end.toInstant(ZoneOffset.of("+8")).toEpochMilli());
        return result;
    }
 
    @Resource
    private SensorUnitMapper sensorUnitMapper;
 
    @Override
    public Map<String, Object> getSensorUnitByDeviceMac(Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> list = sensorUnitMapper.getSensorUnitByDeviceMac(parameters);
        for (Map<String, Object> map : list) {
            resultMap.put(map.remove("sensor_key").toString(), map);
        }
        return resultMap;
    }
 
    @Override
    public Map<String, Object> gitHourlyAQIByMacAndTimeslot(Map<String, Object> parameters) {
        String mac = parameters.get("mac").toString();
        //获取日期
        LocalDate localDate = LocalDate.now();
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
        int endHour = c.get(Calendar.HOUR_OF_DAY);
        String endTime = localDate + " " + endHour + ":00:00";
 
        String startTime;
        if (endHour == 0) {
            LocalDate startDate = localDate.minusDays(1);
            startTime = startDate + " " + "23:00:00";
        } else {
            int startHour = endHour - 1;
            startTime = localDate + " " + startHour + ":00:00";
        }
        //从不同history日表获取数据
        String timeUnits = startTime.substring(0, 10).replace("-", "");
        Map<String, Object> map = historyMapper.getAVGValueByMacAndTimeslot(mac, startTime, endTime, timeUnits);
        Map<String, Object> returnMap = new HashMap<>();
        if (map.isEmpty()) {
            returnMap.put("AQI", "N/V");
        } else {
            Map<String, Double> AQIMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Double value = Double.parseDouble(entry.getValue().toString());
                AQIMap.put(key, value);
            }
            returnMap = AQICalculation.hourlyAQI(AQIMap);
        }
        long aqi = Math.round(Double.valueOf(returnMap.get("AQI").toString()));
        returnMap.put("AQI", aqi);
        return returnMap;
    }
 
    @Override
    public List<Map<String, Object>> getMointorPointRankByOrganizationId(Map<String, Object> parameters) {
        //获取组织id
        String organizationId = parameters.get("organization_id").toString();
        //声明一个集合存放要查询站点数据的组织id
        List<Object> organizationIdList = new ArrayList<>();
        organizationIdList.add(organizationId);
        //声明一个集合存放父组织id
        List<Object> parentIdList = new ArrayList<>();
        parentIdList.add(organizationId);
 
        //进行循环
        for (int i = 0; i < 10; i++) {
            if (!parentIdList.isEmpty()) {
                //或去该组织下的子组织
                List<Map<String, Object>> childIdList = organizationRelationMapper.getChildIdByParentId(parentIdList);
                //清空父组织id集合
                parentIdList.clear();
                //将子组织id放入到集合中
                for (Map<String, Object> map : childIdList) {
                    organizationIdList.add(map.get("child_id"));
                    parentIdList.add(map.get("child_id"));
                }
            } else {
                break;
            }
        }
 
        //根据组织id获取站点id
        List<Map<String, Object>> monitorPointIdListMap = monitorPointMapper.getIdByOrganizationId(organizationIdList);
        //将List<Map<String, Object>>装换为List<Object>
        List<Object> monitorPointIdList = new ArrayList<>();
        for (Map<String, Object> map : monitorPointIdListMap) {
            monitorPointIdList.add(map.get("id"));
        }
 
        //通过站点id获取设备因子的排名
        //获取系统当前时间
        Calendar rightNow = Calendar.getInstance();
        //获取五分钟前的时间
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间
        Date beforeD = beforeTime.getTime();
        Date end = rightNow.getTime();
        String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(end);
        String before5Time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);  // 前五分钟时间
        String sensor = parameters.get("sensor").toString();
        String timeUnits1 = before5Time.substring(0, 10).replace("-", "");
        List<Map<String, Object>> result1 = historyMapper.getAVGSensorRankByMonitorPointIdList(sensor, monitorPointIdList, before5Time, endTime, timeUnits1);
        String timeUnits2 = before5Time.substring(0, 10).replace("-", "");
        List<Map<String, Object>> result2 = historyMapper.getAVGSensorRankByMonitorPointIdList(sensor, monitorPointIdList, before5Time, endTime, timeUnits2);
        if (result1.isEmpty()) {
            return result2;
        } else if (result2.isEmpty()) {
            return result1;
        } else {
            for (Map<String, Object> map1 : result1) {
                Object name1 = map1.get("name");
                double value1 = Double.parseDouble(map1.get("sensor").toString());
                double avg = 0.0;
                for (Map<String, Object> map2 : result2) {
                    Object name2 = map2.get("name");
                    double value2 = Double.parseDouble(map2.get("sensor").toString());
                    if (name1.equals(name2)) {
                        avg = (value1 + value2) / 2;
                        map1.put("sensor", avg);
                    }
                }
            }
        }
        return result1;
    }
 
    @Override
    public Map<String, Object> gitHourlyAQIByMonitorPointIdAndTimeslot(Map<String, Object> parameters) {
        String monitor_point_id = parameters.get("monitor_point_id").toString();
        //获取日期
        LocalDate localDate = LocalDate.now();
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
        int endHour = c.get(Calendar.HOUR_OF_DAY);
        String endTime = localDate + " " + endHour + ":00:00";
 
        String startTime;
        if (endHour == 0) {
            LocalDate startDate = localDate.minusDays(1);
            startTime = startDate + " " + "23:00:00";
        } else {
            int startHour = endHour - 1;
            startTime = localDate + " " + startHour + ":00:00";
        }
        //从不同history日表获取数据
        String timeUnits = startTime.substring(0, 10).replace("-", "");
 
        Map<String, Object> map = historyMapper.getMonitorPointAVGValueByMonitorPointIdAndTimeslot(monitor_point_id, startTime, endTime, timeUnits);
        Map<String, Object> returnMap = new HashMap<>();
        if (map.isEmpty()) {
            returnMap.put("AQI", "N/V");
        } else {
            Map<String, Double> AQIMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Double value = Double.parseDouble(entry.getValue().toString());
                AQIMap.put(key, value);
            }
            returnMap = AQICalculation.hourlyAQI(AQIMap);
        }
 
        return returnMap;
    }
 
    @Override
    public List<List<Map<String, Object>>> getCarSensorData(Map<String, Object> parameters) throws Exception {
        String startTime = parameters.get("startTime").toString();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTimeLocalDateTime = LocalDateTime.parse(startTime, dateTimeFormatter);
        LocalDateTime today = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS);
        LocalDateTime startTimeDay = startTimeLocalDateTime.truncatedTo(ChronoUnit.DAYS);
        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 (today.compareTo(startTimeDay) == 0) {
            listMap = historyMapper.listGetSensorData(parameters);
        }*/
        //if (CollectionUtils.isEmpty(listMap)) {
        listMap = historyMapper.getCarSensorData(parameters);
        if (CollectionUtils.isEmpty(listMap)) {
            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 (Map.Entry<String, Object> entry : map.entrySet()) {
                    for (Sensor sensor : sensors) {
                        if (sensor.getSensorKey().equals(entry.getKey())) {
                            if (entry.getValue() != null) {
                                mapAvg.put(entry.getKey(), new BigDecimal(entry.getValue().toString().replace("\"", "")).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>> getUavSensorData(Map<String, Object> parameters) {
        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>> uavSensorData = historyMapper.getUavSensorData(parameters);
        for (Map<String, Object> dataMap : uavSensorData) {
            for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                for (Sensor sensor : sensors) {
                    if (sensor.getSensorKey().equals(entry.getKey())) {
                        if (entry.getValue() != null) {
                            dataMap.put(entry.getKey(), new BigDecimal(entry.getValue().toString().replace("\"", "")).stripTrailingZeros().toPlainString() + sensor.getUnit());
                        }
                    }
                }
            }
        }
        Map<String, Object> map = sensorMapper.getSensorBySensorKey(parameters.get("sensorKey").toString());
        parameters.put("unit", map.get("unit"));
        parameters.put("description", map.get("description"));
        return uavSensorData;
    }
 
    @Override
    public List<Map<String, Object>> getO3AVG(Map<String, Object> parameters) {
        String mac = (String) parameters.get("mac");
        String stime = (String) parameters.get("time");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Date time = null;
        try {
            time = format.parse(stime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<String> stringListDate = DatesUtil.getAllTheDateOftheMonth(time);
        List<Map<String, Object>> maxList = new ArrayList<Map<String, Object>>();
        for (String date : stringListDate) {
            Map<String, Object> parm = new HashMap<String, Object>();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime time1 = LocalDateTime.parse(date + " 00:00:00", df);
            LocalDateTime time2 = time1.plusDays(1);
            String time3 = time2.toString().substring(0, 10);
            String nextDate = time3 + " 07:00:00";
            parm.put("date", date);
            parm.put("nextDate", nextDate);
            parm.put("mac", mac);
            List<Map<String, Object>> listMap = historyMapper.getO3AVG(parm);
            List list = new ArrayList();
            DatesUtil.getList(listMap, list);
            List list1 = new ArrayList();
            String maxO3 = "";
            for (int i = 0; i < list.size(); i++) {
                List elist = new ArrayList();
                Double sum = 0.0;
                Double avg = 0.0;
                for (Object o : (List) list.get(i)) {
                    Iterator<Map.Entry> iterator = ((Map) o).entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = iterator.next();
                        if (entry.getKey().equals("e15")) {
                            elist.add(entry.getValue());
                        }
                    }
                }
                for (int j = 0; j < elist.size(); j++) {
                    sum += Double.parseDouble((String) elist.get(j));
                    if (listMap.size() <= 8 && listMap.size() > 0) {
                        avg = sum / listMap.size();
                    } else {
                        avg = sum / 8;
                    }
                }
                if (avg == 0.0) {
                    list1.add("");
                } else {
                    BigDecimal b = new BigDecimal(avg);
                    double avg1 = b.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    list1.add(avg1);
                }
            }
            String timef = date + " 00:00:00";
            String timea = date + " 23:59:59";
            int num = historyMapper.getNum(timef, timea);
            if (num == 0) {
                maxO3 = "";
            } else {
                if (list1.size() != 0) {
                    maxO3 = "" + Collections.max(list1);
                } else {
                    maxO3 = "";
                }
            }
            Map<String, Object> avgMap = new HashMap<String, Object>();
            avgMap.put("time", date);
            avgMap.put("e15", maxO3);
            maxList.add(avgMap);
        }
        return maxList;
    }
 
    @Override
    public String getJsonData(String mac, String time, String table) {
        return historyMapper.getJsonData(mac, time, table);
    }
 
}