xufenglei
2017-12-04 b28a5002a58d8d0b37082da12e5b218f0951de47
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
package com.moral.service.impl;
 
import static com.moral.common.bean.Constants.NULL_VALUE;
import static org.apache.commons.lang3.time.DateUtils.addDays;
import static org.apache.commons.lang3.time.DateUtils.addHours;
import static org.apache.commons.lang3.time.DateUtils.addMinutes;
import static org.apache.commons.lang3.time.DateUtils.addMonths;
import static org.apache.commons.lang3.time.DateUtils.parseDate;
import static org.apache.commons.lang3.time.DateUtils.truncate;
import static org.springframework.util.ObjectUtils.isEmpty;
 
import java.text.ParseException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.annotation.Resource;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
 
import com.mongodb.BasicDBObject;
import com.moral.common.exception.BusinessException;
import com.moral.common.util.CalculateUtils;
import com.moral.common.util.ResourceUtil;
import com.moral.mapper.HistoryMapper;
import com.moral.service.AccountService;
import com.moral.service.HistoryService;
 
@Service
public class HistoryServiceImpl implements HistoryService {
 
    @Resource
    private AccountService accountService;
 
    @Resource
    private HistoryMapper historyMapper;
 
    @Resource
    private MongoTemplate mongoTemplate;
 
    @Override
    public Map<String, Object> getAllSensorAverageByDevice(Map<String, Object> parameters) {
        accountService.setOrgIdsByAccount(parameters);
        Date date = new Date();
        // 当前时间 -10分钟
        parameters.put("start", addMinutes(date, -10));
        // 当前时间 -5分钟
        parameters.put("end", addMinutes(date, -5));
        String queryColumns = "";
        for (int i = 1; i < 20; i++) {
            if (i == 1) {
                queryColumns += "AVG(value -> '$.e" + i + "') e" + i;
            } else {
                queryColumns += " , AVG(value -> '$.e" + i + "') e" + i;
            }
        }
        parameters.put("queryColumns", queryColumns);
        parameters.put("macKey", "all");
        List<Map<String, Object>> list = historyMapper.getAreaAllDataByAccount(parameters);
 
        return list.get(0);
    }
 
    @Override
    public Map<String, Object> getDeviceRankingBySensorAverage(Map<String, Object> parameters) {
        Map<String, Object> result = new LinkedHashMap<String, Object>();
 
        accountService.setOrgIdsByAccount(parameters);
        Date date = new Date();
        // 当前时间 -1小时
        parameters.put("start", addHours(date, -1));
        parameters.put("end", date);
        parameters.put("macKey", "'$."+ parameters.get("macKey")+"'");
        List<Map<String, Object>> list = historyMapper.getAreaAllDataByAccount(parameters);
 
        for (Map<String, Object> map : list) {
            result.put((String) map.get("name"), map.get("avg"));
        }
        return result;
    }
 
    @Override
    public Map<String, Object> getDayAQIByDevice(Map<String, Object> parameters) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Date date = new Date();
        // 昨日00:00:00
        parameters.put("start", truncate(addDays(date, -1), Calendar.DATE));
        // 今日00:00:00
        parameters.put("end", truncate(date, Calendar.DATE));
        String[] IAQIValues = ResourceUtil.getArrValue("IAQI");
        Map<String, Double> average = historyMapper.getDayAQIByDevice(parameters);
        if (isEmpty(average)) {
            resultMap.put("AQI", NULL_VALUE);
        } else {
            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", NULL_VALUE);
            } 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, Object> getMonthAverageBySensor(Map<String, Object> parameters) {
        Map<String, Object> result = new HashMap<String, Object>();
        Date date = new Date();
        Long end = truncate(date, Calendar.DATE).getTime(), start;
        // 每月一日的数据取上月的数据
        if (1 == Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) {
            // 上个月1日00:00:00
            start = truncate(addMonths(date, -1), Calendar.MONTH).getTime();
        } else {
            // 这个月1日00:00:00
            start =  truncate(date, Calendar.MONTH).getTime();
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("mac").is(parameters.get("mac"))),
                Aggregation.match(Criteria.where("time").gte(start)), 
                Aggregation.match(Criteria.where("time").lt(end)),
                Aggregation.group("mac").avg((String) parameters.get("macKey")).as("average")
        );
        AggregationResults<BasicDBObject> results = mongoTemplate.aggregate(aggregation, "data", BasicDBObject.class);
        List<BasicDBObject> list = results.getMappedResults();
        if (isEmpty(list)) {
            result.put("average", NULL_VALUE);
        } else {
            result = list.get(0);
            result.put("average", String.format("%.2f", result.get("average")));
        }
        return result;
    }
 
    @Override
    public List<Map<String, Object>> getSensorsAverageByDevice4Report(Map<String, Object> parameters,List<Map<String, Object>> sensors) {
        Object type = parameters.get("type");
        if ("hour".equals(type)) {
            parameters.put("type", "%Y-%m-%d %H:00");
        } else if ("minute".equals(type)) {
            parameters.put("type", "%Y-%m-%d %H:%i:00");
        } else {
            throw new BusinessException("type参数输入错误!");
        }
        
        try {
            Date start = parseDate((String)parameters.get("time"), "yyyy-MM-dd");
            parameters.put("start", start);
            parameters.put("end", addDays(start, 1));
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("time参数输入错误!");
        }
        String queryColumns = "";
        for (int i = 0; i < sensors.size(); i++) {
            String sensorKey = (String) sensors.get(i).get("key");
            if (i == sensors.size() - 1) {
                queryColumns += "AVG(value -> '$." + sensorKey + "') " + sensorKey;
            } else {
                queryColumns += "AVG(value -> '$." + sensorKey + "') " + sensorKey +",";
            }
        }
        parameters.put("queryColumns", queryColumns);
        
        return historyMapper.getSensorsAverageByDevice4Report(parameters);
    }
 
}