jinpengyong
2023-10-10 4319627cf67d19093a18ff724c21782e34fc7a26
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
package com.moral.api.controller;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.moral.api.entity.Organization;
import com.moral.api.entity.ServicesScope;
import com.moral.api.mapper.OrganizationMapper;
import com.moral.api.service.HistoryDailyService;
import com.moral.api.service.HistoryHourlyService;
import com.moral.api.service.HistoryMonthlyService;
import com.moral.api.service.ServicesScopeService;
import com.moral.constant.Constants;
import com.moral.constant.ResponseCodeEnum;
import com.moral.constant.ResultMessage;
import com.moral.util.DateUtils;
import com.moral.util.WebUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @program: screen
 * @description: 图表数据
 * @author: lizijie
 * @create: 2021-11-10 16:05
 **/
@Slf4j
@Api(tags = {"设备小时数据"})
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/chart")
public class ChartController {
 
    @Resource
    private OrganizationMapper organizationMapper;
 
    @Resource
    private HistoryHourlyService historyHourlyService;
 
    @Resource
    private HistoryDailyService historyDailyService;
 
    @Resource
    private HistoryMonthlyService historyMonthlyService;
 
    @Resource
    private ServicesScopeService servicesScopeService;
 
    @RequestMapping(value = "getThermodynamicDiagramDataByCondition", method = RequestMethod.GET)
    @ResponseBody
    public ResultMessage getThermodynamicDiagramDataByCondition(HttpServletRequest request) throws ParseException {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request,null);
        Object orgid = parameters.get("organization_id");
        Object sensorCode = parameters.get("sensor_code");
        Object type = parameters.get("type");
        if (ObjectUtils.isEmpty(orgid) || ObjectUtils.isEmpty(sensorCode) || ObjectUtils.isEmpty(type)){
            return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
        }
        Organization organization = organizationMapper.selectById(Integer.parseInt(orgid.toString()));
        if (ObjectUtils.isEmpty(organization)){
            return ResultMessage.fail(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getCode(), ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getMsg());
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (type.equals("hourly")){
            Object time = parameters.get("time");
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyHourlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTime(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("daily")){
            Object time = parameters.get("time");
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyDailyService.getThermodynamicDiagramDataByOrgIdSensorCodeTime(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("monthly")){
            Object time = parameters.get("time");
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyMonthlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTime(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("custom")){
            String startTime = parameters.get("startTime").toString();
            String endTime = parameters.get("endTime").toString();
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            if (startTime.length() == 13){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
                long newTime1 = simpleDateFormat.parse(startTime+":00:00").getTime();
                long newTime2 = simpleDateFormat.parse(endTime+":00:00").getTime();
                Long result = newTime2 - newTime1; //获取两时间相差的毫秒数
                long nd = 1000 * 24 * 60 * 60;
                long nh = 1000 * 60 * 60;
                long nm = 1000 * 60;
                long hour = result / nh; //获取相差的小时数
                if (hour+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12小时");
                }
                if (hour<0){
                    return ResultMessage.fail(ResponseCodeEnum.TIME_FORMAT_INVALID.getCode(), ResponseCodeEnum.TIME_FORMAT_INVALID.getMsg());
                }
                parameters.put("hour",hour);
                resultList = historyHourlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeslot(parameters);
                return ResultMessage.ok(resultList);
            }
            if (startTime.length() == 10){
                long days = DateUtils.getQuotByDays(startTime, endTime);
                if (days+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12天");
                }
                parameters.put("days",days);
                resultList = historyDailyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeSlot(parameters);
                return ResultMessage.ok(resultList);
            }
            if (startTime.length() == 7){
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
                Date satrtTimeDate = df.parse(startTime);
                Date endTimeDate = df.parse(endTime);
                long months = DateUtils.getMonth(satrtTimeDate,endTimeDate); //获取相差的小时数
                if (months+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12月");
                }
                parameters.put("months",months);
                resultList = historyMonthlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeSlot(parameters);
                return ResultMessage.ok(resultList);
            }
        }
        return ResultMessage.ok(resultMap);
    }
 
    @RequestMapping(value = "getThermodynamicDiagramDataByConditionV2", method = RequestMethod.GET)
    @ResponseBody
    public ResultMessage getThermodynamicDiagramDataByConditionV2(HttpServletRequest request) throws ParseException {
        Map<String, Object> parameters = WebUtils.getParametersStartingWith(request,null);
        Object servicesScopeId = parameters.get("servicesScopeId");
        Object sensorCode = parameters.get("sensor_code");
        Object type = parameters.get("type");
        if (ObjectUtils.isEmpty(servicesScopeId) || ObjectUtils.isEmpty(sensorCode) || ObjectUtils.isEmpty(type)){
            return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
        }
        QueryWrapper<ServicesScope> servicesScopeQueryWrapper = new QueryWrapper<>();
        servicesScopeQueryWrapper.eq("is_delete",Constants.NOT_DELETE);
        servicesScopeQueryWrapper.eq("id",servicesScopeId);
        ServicesScope servicesScope = servicesScopeService.getOne(servicesScopeQueryWrapper);
        if (ObjectUtils.isEmpty(servicesScope)){
            return ResultMessage.fail(ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getCode(), ResponseCodeEnum.ORGANIZATION_NOT_EXIST.getMsg());
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (type.equals("hourly")){
            Object time = parameters.get("time");
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyHourlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeV2(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("daily")){
            Object time = parameters.get("startTime");
            parameters.put("time",time);
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyDailyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeV2(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("monthly")){
            Object time = parameters.get("time");
            if (ObjectUtils.isEmpty(time)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            resultMap = historyMonthlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeV2(parameters);
            return ResultMessage.ok(resultMap);
        }
        if (type.equals("custom")){
            String startTime = parameters.get("startTime").toString();
            String endTime = parameters.get("endTime").toString();
            if (ObjectUtils.isEmpty(startTime) || ObjectUtils.isEmpty(endTime)){
                return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
            }
            if (startTime.length() == 13){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
                long newTime1 = simpleDateFormat.parse(startTime+":00:00").getTime();
                long newTime2 = simpleDateFormat.parse(endTime+":00:00").getTime();
                Long result = newTime2 - newTime1; //获取两时间相差的毫秒数
                long nd = 1000 * 24 * 60 * 60;
                long nh = 1000 * 60 * 60;
                long nm = 1000 * 60;
                long hour = result / nh; //获取相差的小时数
                if (hour+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12小时");
                }
                if (hour<0){
                    return ResultMessage.fail(ResponseCodeEnum.TIME_FORMAT_INVALID.getCode(), ResponseCodeEnum.TIME_FORMAT_INVALID.getMsg());
                }
                parameters.put("hour",hour);
                resultList = historyHourlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeslotV2(parameters);
                return ResultMessage.ok(resultList);
            }
            if (startTime.length() == 10){
                long days = DateUtils.getQuotByDays(startTime, endTime);
                if (days+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12天");
                }
                parameters.put("days",days);
                resultList = historyDailyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeSlotV2(parameters);
                return ResultMessage.ok(resultList);
            }
            if (startTime.length() == 7){
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
                Date satrtTimeDate = df.parse(startTime);
                Date endTimeDate = df.parse(endTime);
                long months = DateUtils.getMonth(satrtTimeDate,endTimeDate); //获取相差的小时数
                if (months+1>12){
                    return ResultMessage.fail(-1, "时间不能超过12月");
                }
                parameters.put("months",months);
                resultList = historyMonthlyService.getThermodynamicDiagramDataByOrgIdSensorCodeTimeSlotV2(parameters);
                return ResultMessage.ok(resultList);
            }
        }
        return ResultMessage.ok(resultMap);
    }
 
    @GetMapping("honeycombDiagram")
    public ResultMessage honeycombDiagram (HttpServletRequest httpServletRequest, HttpServletResponse response) throws IOException {
        Map<String, Object> params = WebUtils.getParametersStartingWith(httpServletRequest, null);
        Object serviceScopeId = params.get("serviceScopeId");
        Object sensor_code = params.get("sensor_code");
        Object type = params.get("type");
        Object time = params.get("time");
        Object distance = params.get("distance");
        if (ObjectUtils.isEmpty(serviceScopeId)){
            return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
        }
        List<Map<String, Object>> resultList = servicesScopeService.honeycombDiagram(Integer.parseInt(serviceScopeId.toString()), Integer.parseInt(distance.toString()), type.toString(), time.toString(), sensor_code.toString());
        //List<Map<String, Object>> resultList = servicesScopeService.honeycombDiagram(6, 40, "monthly", "2022-02", "a34004");
 
        //获取jar包所在目录
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String path = applicationHome.getSource().getParentFile().toString() + "/static/tsv";
 
        //File file = File.createTempFile("test",".tsv");
        /*if (!new File(path).exists()){
            new File(path).mkdir();
        }*/
        File file = null;
        File dir = new File(path);
        file = File.createTempFile("honeycombDiagram",".tsv",dir);
 
        //构建输出流,同时指定编码
        OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
 
        //tsv文件是空格分隔,除第一个外,每次写入一个单元格数据后需要输入空格
        ow.write("lng");
        ow.write("  ");
        ow.write("lat");
        ow.write("  ");
        ow.write("count");
        //写完文件头换行
        ow.write("\r\n");
        //写内容
        for (Map map:resultList) {
            ow.write(map.get("lon").toString());
            ow.write("  ");
            ow.write(map.get("lat").toString());
            ow.write("  ");
            ow.write(map.get("value").toString());
            //写完一行换行
            ow.write("\r\n");
        }
        ow.flush();
        ow.close();
 
        /*String localAddr = httpServletRequest.getLocalAddr();
        int serverPort = httpServletRequest.getServerPort();*/
 
        Map<String,Object> res = new HashMap<>();
        res.put("path","http://47.99.64.149:8081"+"/static/tsv/"+file.getName());
 
        return ResultMessage.ok(res);
    }
 
    @RequestMapping(value = "returnDataTest", method = RequestMethod.GET)
    @ResponseBody
    public ResultMessage returnDataTest(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
        Map<String, Object> params = WebUtils.getParametersStartingWith(request, null);
        Object serviceScopeId = params.get("serviceScopeId");
        Object sensor_code = params.get("sensor_code");
        Object type = params.get("type");
        Object time = params.get("time");
        Object distance = params.get("distance");
        /*if (ObjectUtils.isEmpty(serviceScopeId)){
            return ResultMessage.fail(ResponseCodeEnum.PARAMETERS_IS_MISSING.getCode(), ResponseCodeEnum.PARAMETERS_IS_MISSING.getMsg());
        }*/
        List<Map<String, Object>> resultList = servicesScopeService.honeycombDiagram(Integer.parseInt(serviceScopeId.toString()), Integer.parseInt(distance.toString()), type.toString(), time.toString(), sensor_code.toString());
        //List<Map<String, Object>> resultList = servicesScopeService.honeycombDiagram(6, 40, "monthly", "2022-02", "a34004");
 
        //获取jar包所在目录
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
        String path = applicationHome.getSource().getParentFile().toString() + "/static/tsv";
 
        //File file = File.createTempFile("test",".tsv");
        if (!new File(path).exists()){
            new File(path).mkdir();
        }
        File file = null;
        File dir = new File(path);
        file = File.createTempFile("honeycombDiagram",".tsv",dir);
        //构建输出流,同时指定编码
        OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
 
        //tsv文件是空格分隔,除第一个外,每次写入一个单元格数据后需要输入空格
        ow.write("lon");
        ow.write("  ");
        ow.write("lat");
        ow.write("  ");
        ow.write("value");
        //写完文件头换行
        ow.write("\r\n");
        //写内容
        for (Map map:resultList) {
            ow.write(map.get("lon").toString());
            ow.write("  ");
            ow.write(map.get("lat").toString());
            ow.write("  ");
            ow.write(map.get("value").toString());
            //写完一行换行
            ow.write("\r\n");
        }
        ow.flush();
        ow.close();
        /*File file1 = new File(file.getPath());
        InputStream inputStream = new FileInputStream(file1);
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes)) != -1){
            response.getOutputStream().write(bytes,0,len);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();*/
 
        /*response.setCharacterEncoding("UTF-8");
        System.out.println(file.getName());
        String realFileName = file.getName();
        response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Length",String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8"));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        os = response.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(file));
        int i = bis.read(buff);
        while (i != -1) {
            os.write(buff, 0, buff.length);
            os.flush();
            i = bis.read(buff);
        }
        bis.close();*/
 
        /*//1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(file.getName(), "UTF-8"));
 
        File file1 = new File(file.getParent(),file.getName());
        System.out.println(file1.getParent());
        //2、 读取文件--输入流
        InputStream input=new FileInputStream(file1);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();
 
        byte[] buff =new byte[1024];
        int index=0;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();*/
 
        Map<String,Object> res = new HashMap<>();
        res.put("path",file.getPath());
        return ResultMessage.ok(res);
    }
 
}