huangzhen
2023-10-20 5c72b20bee11513c06cdfb30c52cd0a4016a7102
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
package com.gkhy.fourierSpecialGasMonitor.schedule;
 
import com.alibaba.fastjson.JSON;
import com.gkhy.fourierSpecialGasMonitor.Application;
import com.gkhy.fourierSpecialGasMonitor.commons.enums.ForeignResultCode;
import com.gkhy.fourierSpecialGasMonitor.commons.enums.ResultCode;
import com.gkhy.fourierSpecialGasMonitor.commons.exception.BusinessException;
import com.gkhy.fourierSpecialGasMonitor.commons.exception.DataReceiveException;
import com.gkhy.fourierSpecialGasMonitor.config.file.ReportFilePathConfig;
import com.gkhy.fourierSpecialGasMonitor.entity.*;
import com.gkhy.fourierSpecialGasMonitor.service.*;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xddf.usermodel.text.XDDFTextBody;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
 
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author Mr.huang
 * @decription
 * @date 2023/8/11 13:25
 */
@Component
public class DailyReportSchedule {
 
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
 
    private static final DateTimeFormatter reportNameFormatter = DateTimeFormatter.ofPattern("yyyy_MM_dd");
 
    private static final DateTimeFormatter execformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
 
    private static final DateTimeFormatter lineChartXDataDisplay = DateTimeFormatter.ofPattern("HH:mm");
 
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
    @Autowired
    private GasWarnLogService gasWarnLogService;
 
    @Autowired
    private GasConcentrationService gasConcentrationService;
 
    @Autowired
    private RedissonClient redissonClient;
 
    @Autowired
    private RegionService regionService;
 
    @Autowired
    private ReportFilePathConfig reportFilePathConfig;
 
    @Autowired
    private GasFluxService gasFluxService;
 
    @Autowired
    private MonitorDailyReportService monitorDailyReportService;
 
    @Scheduled(cron = "0 0 2 * * ?") //每天两点执行一次
    @Async(value = "SocketTaskExecutor")
    public void generateDailyReport() {
        LocalDateTime now = LocalDateTime.now();
        String startTime = now.format(execformatter);
        RBucket<List<GasCategory>> bucket = redissonClient.getBucket("gas_category_cache_info");
        List<GasCategory> gasCategories = bucket.get();
        logger.info("【##】开始生成日报 ,时间:"+startTime);
        OPCPackage opcPackage = null;
        //加载文档
        XWPFDocument doc = null;
        try {
            ClassLoader classLoader = Application.class.getClassLoader();
            InputStream originalFileInputStream = classLoader.getResourceAsStream("template/dailyReportTemplate.docx");
            String copyFileUrl = reportFilePathConfig.getDcPath()+"temp/dailyReportTemplate.docx";
            File file = new File(copyFileUrl);
            if (!file.exists()){
                try {
                    // 获取文件所在的文件夹路径
                    String folderPath = file.getParent();
                    // 创建文件夹(包括父目录)
                    File folder = new File(folderPath);
                    if (!folder.exists()){
                        folder.mkdirs();
                    }
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream copyFileOutputStream = new FileOutputStream(copyFileUrl);
            IOUtils.copy(originalFileInputStream, copyFileOutputStream);
            opcPackage = POIXMLDocument.openPackage(copyFileUrl);
 
            //FileInputStream originalFileInputStream = new FileInputStream("src/main/resources/template/dailyReportTemplate.docx");
            //FileOutputStream copyFileOutputStream = new FileOutputStream("src/main/resources/temp/dailyReportTemplate.docx");
            //// 创建副本文件
            //IOUtils.copy(originalFileInputStream, copyFileOutputStream);
            //opcPackage = POIXMLDocument.openPackage("src/main/resources/temp/dailyReportTemplate.docx");
            doc = new XWPFDocument(opcPackage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> map = dataMap(gasCategories);
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        for (XWPFParagraph par : paragraphList) {
            //获取段落的文本对象
            List<XWPFRun> runs = par.getRuns();
            for (XWPFRun run : runs) {
                //获取文本的值
                String text = run.getText(0);
                //遍历map
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    //获取map的key
                    String key = entry.getKey();
                    //判断文本的值和map的key,文本中是否有和key一样的占位符
                    if (text != null && text.indexOf(key) != -1) {
                        //获取对应key的value
                        Object value = entry.getValue();
                        //把文本的内容,key替换为value
                        text = text.replace(key, value.toString());
                        //把替换好的文本内容,保存到当前这个文本对象
                        run.setText(text, 0);
                    }
                }
            }
        }
        String format = now.format(reportNameFormatter);
        String fileName = "富城能源气体监测日报"+format+".docx";
        String fileurl = reportFilePathConfig.getDcPath()+fileName;
        File file = new File(fileurl);
        if (!file.exists()){
            try {
                // 获取文件所在的文件夹路径
                String folderPath = file.getParent();
                // 创建文件夹(包括父目录)
                File folder = new File(folderPath);
                if (!folder.exists()){
                    folder.mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            doc.write(fileOutputStream);
            fileOutputStream.close();
            opcPackage.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<GasConcentration> gasConcentrations = gasConcentrationService.listDatabyTimeSlot(LocalDateTime.of(now.minusDays(1).toLocalDate(), LocalTime.MIN)
                ,  LocalDateTime.of(now.minusDays(1).toLocalDate(), LocalTime.MAX));
        if (!CollectionUtils.isEmpty(gasConcentrations)) {
            for (int i = 0; i < 30; i++) {
                String series = gasCategories.get(i).getMolecularFormula() + "浓度观测结果";
                String title = "—" + gasCategories.get(i).getMolecularFormula();
                drawLineChart(gasConcentrations, fileurl, series, title, gasCategories.get(i).getMolecularFormula(), i);
            }
        }
        //List<GasFlux> gasFluxes = gasFluxService.listYesterday();
        List<GasFlux> gasFluxes = gasFluxService.listYesterdayTenAmToSixPm();
        List<Integer> areaNum = gasFluxes.stream().map(GasFlux::getAreaId).distinct().collect(Collectors.toList());
 
        List<Region> allRegion = regionService.findAll();
        if (CollectionUtils.isEmpty(allRegion))
            throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL.getCode(),"区域信息为空");
        Map<Integer, String> regionMap = allRegion.stream()
                .collect(Collectors.toMap(Region::getId, Region::getName));
        if (!CollectionUtils.isEmpty(gasFluxes)) {
            for (int i = 1; i <= areaNum.size(); i++) {
                for (int j = 0; j < 20; j++) {
                    drawBarChart(gasFluxes, fileurl, regionMap.get(i), "柱形图" + gasCategories.get(j).getMolecularFormula(), i, j + 1);
                }
            }
        }
        String endTime = LocalDateTime.now().format(execformatter);
        long execTime = ChronoUnit.SECONDS.between(now, LocalDateTime.now());
        MonitorDailyReport report = new MonitorDailyReport();
        report.setName(fileName);
        report.setGmtCreate(now);
        report.setEndTime(LocalDateTime.now());
        report.setFileUrl(reportFilePathConfig.getUrlRootPath()+fileName);
        MonitorDailyReport save = monitorDailyReportService.save(report);
        if (save == null)
            throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL,"日常报表保存失败");
        logger.info("【##】日报生成成功!!! ,时间:"+endTime+",所耗时间: "+execTime+"s");
    }
 
    public void drawBarChart(List<GasFlux> gasFluxes,String fileurl,String series,String molecularFormula,Integer i,Integer j) {
        List<String> collect = gasFluxes.stream()
                .map(gasFlux -> gasFlux.getTime().format(lineChartXDataDisplay))
                .collect(Collectors.toList());
        String[] x2 = collect.toArray(new String[collect.size()]);
        String fieldName = "gasValue";
        if (j<10){
            fieldName = fieldName + "0" + j;
        }else {
            fieldName = fieldName + j;
        }
        final String fieldTempName = fieldName;
        Double[] n = gasFluxes.stream().map(obj -> {
            try {
                Field field = obj.getClass().getDeclaredField(fieldTempName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                logger.info("柱状图反射获取字段值异常");
                return null;
            }
        }).collect(Collectors.toList()).toArray(new Double[gasFluxes.size()]);
 
        String templatePath = fileurl;
        XWPFDocument doc=null;
        InputStream is = null;
        try{
            is = new FileInputStream(new File(templatePath));
            doc = new XWPFDocument(is);
        } catch (Exception e){
            System.out.println(e);
        }
        //区域名称
        String[] series2 = {series};//
        //y轴
        List<Number[]> value2 = new ArrayList<>();//每一条折现图,第二个表1条
        value2.add(n);
 
        List<XWPFChart> charts = doc.getCharts();
        for (int k = 0; k < charts.size(); k++) {
            XWPFChart xwpfChart = charts.get(k);
            XDDFTitle xddfTitletitle = xwpfChart.getTitle();
            if (xddfTitletitle != null) {
                XDDFTextBody body = xddfTitletitle.getBody();
                CTTextBody xmlObject = body.getXmlObject();
                String tt = xmlObject.toString(); //图表的标题
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    // 解析 XML 字符串
                    org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(tt.getBytes()));
                    // 获取根元素 <a:r>
                    Element root = document.getDocumentElement();
                    // 获取包含文本的 <a:t> 元素
                    Element aT = (Element) root.getElementsByTagName("a:t").item(0);
                    // 获取 <a:t> 元素的文本内容 获取标题具体内容
                    String value = aT.getTextContent();
                    String chartTitle = "图"+(31 + i * j)+" "+i+"号厂区排放"+molecularFormula+"通量反演结果";
                    if ((i+"-"+j).equals(value)) {
                        drawBarChartExec(charts.get(k), series2, x2, value2, chartTitle);
                    }
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            }
        }
        try (FileOutputStream fos = new FileOutputStream(templatePath)) {
            doc.write(fos);
            doc.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
 
    public void drawLineChart(List<GasConcentration> gasConcentrations,String fileurl,String series,String title,String molecularFormula,Integer i) {
        List<String> collect = gasConcentrations.stream()
                .map(gasConcentration -> gasConcentration.getTime().format(lineChartXDataDisplay))
                .collect(Collectors.toList());
        String[] x2 = collect.toArray(new String[collect.size()]);
        String fieldName = "gasValue";
        i = i+1;
        if (i<10){
            fieldName = fieldName + "0" + i;
        }else {
            fieldName = fieldName + i;
        }
        final String fieldTempName = fieldName;
        Double[] n = gasConcentrations.stream().map(obj -> {
            try {
                Field field = obj.getClass().getDeclaredField(fieldTempName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
        }).collect(Collectors.toList()).toArray(new Double[gasConcentrations.size()]);
 
        String templatePath = fileurl;
        XWPFDocument doc=null;
        InputStream is = null;
        try{
            is = new FileInputStream(new File(templatePath));
            doc = new XWPFDocument(is);
        } catch (Exception e){
            System.out.println(e);
        }
        String[] series2 = {"图" + (i)+" "+series};//
 
        String title2=title;
        //y轴
        List<Number[]> value2 = new ArrayList<>();
        value2.add(n);
 
        //
        List<XWPFChart> charts = doc.getCharts();
        for (int j = 0; j < charts.size(); j++) {
            XWPFChart xwpfChart = charts.get(j);
            XDDFTitle xddfTitletitle = xwpfChart.getTitle();
            if (xddfTitletitle != null) {
                XDDFTextBody body = xddfTitletitle.getBody();
                CTTextBody xmlObject = body.getXmlObject();
                String tt = xmlObject.toString(); //图表的标题
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    // 解析 XML 字符串
                    org.w3c.dom.Document document = builder.parse(new ByteArrayInputStream(tt.getBytes()));
                    // 获取根元素 <a:r>
                    Element root = document.getDocumentElement();
                    // 获取包含文本的 <a:t> 元素
                    Element aT = (Element) root.getElementsByTagName("a:t").item(0);
                    // 获取 <a:t> 元素的文本内容 获取标题具体内容
                    String value = aT.getTextContent();
                    if (molecularFormula.equals(value)) {
                        drawLineChartExec(charts.get(j), series2, x2, value2, title2);
                    }
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            }
        }
        try (FileOutputStream fos = new FileOutputStream(templatePath)) {
            doc.write(fos);
            doc.close();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
 
    public void drawBarChartExec(XWPFChart chart, String[] series, String[] categories,
                                  List<Number[]> values, String chartTitle) {
        final List<XDDFChartData> data = chart.getChartSeries();
 
        final XDDFBarChartData line = (XDDFBarChartData) data.get(0);//这里一般获取第一个,我们这里是折线图就是XDDFLineChartData
        line.getCategoryAxis().setTitle(chartTitle);
        line.getValueAxes().get(0).setTitle("C2H2 Emission Rate (ug/m^2/s)");
        final int numOfPoints = categories.length;
 
        final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
 
        final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
        for (int i = 0; i < values.size(); i++) {
            final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, i + 1, i + 1));
            Number[] value = values.get(i);
            final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(value, valuesDataRange, i + 1);
            XDDFChartData.Series ser;//图表中的系列
            ser = line.getSeries().get(i);
            ser.replaceData(categoriesData, valuesData);
            CellReference cellReference = chart.setSheetTitle(series[i], 1);//修改系列标题
            ser.setTitle(series[i], cellReference);
        }
        chart.plot(line);
        chart.setTitleText("");//折线图标题
        chart.setTitleOverlay(false);
    }
 
    public void drawLineChartExec(XWPFChart chart, String[] series, String[] categories,
                               List<Number[]> values, String chartTitle) {
        final List<XDDFChartData> data = chart.getChartSeries();
 
        final XDDFLineChartData line = (XDDFLineChartData) data.get(0);//这里一般获取第一个,我们这里是折线图就是XDDFLineChartData
 
        final int numOfPoints = categories.length;
 
        //List<String> lineChartXDataDisplayDefault = Arrays.asList("00:00","01:00","02:00","03:00","04:00","05:00","06:00"
        //        ,"07:00","08:00","09:00",
        //        "10:00","11:00","12:00","13:00","19:00");
        //for (int i = 0; i < numOfPoints; i++) {
        //    if (!lineChartXDataDisplayDefault.contains(categories[i])) {
        //        categories[i] = ""; // 设置为空字符串,隐藏原有的标签
        //    }
        //}
 
        final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
 
        final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
        for (int i = 0; i < values.size(); i++) {
            final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, i + 1, i + 1));
            Number[] value = values.get(i);
            final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(value, valuesDataRange, i + 1);
            XDDFChartData.Series ser;//图表中的系列
            ser = line.getSeries().get(i);
            ser.replaceData(categoriesData, valuesData);
            CellReference cellReference = chart.setSheetTitle(series[i], 1);//修改系列标题
            ser.setTitle(series[i], cellReference);
        }
        chart.plot(line);
        chart.setTitleText(chartTitle);//折线图标题
        chart.setTitleOverlay(false);
    }
 
    private Map<String, Object> dataMap(List<GasCategory> gasCategories){
        LocalDateTime now = LocalDateTime.now();
        String today = now.format(formatter);
        String yesterday = LocalDateTime.now().minusDays(1).format(formatter);
        //要替换的map,key为占位符,value为要被替换的值
        Map<String, Object> map = new HashMap<>();
        map.put("${today}", today);
        map.put("${yesterday}", yesterday);
        map.put("${generalradius}","10");
        map.put("${generalradiu}","20");
 
        List<GasWarnLog> gasWarnLogs = gasWarnLogService.listYesterday();
        if (!CollectionUtils.isEmpty(gasWarnLogs)){
            String warnInfo = "根据以上气体浓度变化曲线,各物种的浓度有如下特征:";
            for (int i = 0; i < gasWarnLogs.size(); i++) {
                LocalDateTime warnTime = gasWarnLogs.get(i).getWarnTime();
                String time = warnTime.format(execformatter);
                warnInfo = warnInfo + gasWarnLogs.get(i).getGasMolecularFormula()
                        +"("+gasWarnLogs.get(i).getGasName()+")浓度在"+time+" 出现"+gasWarnLogs.get(i).getGasThresholdName()
                        + "浓度达到:"+gasWarnLogs.get(i).getGasConcentration()+gasWarnLogs.get(i).getGasUnit() + ";   ";
 
            }
            map.put("${warn}",warnInfo);
        }else {
            map.put("${warn}","");
        }
        String fiveGas = "";
        String sixGas = "";
        for (int i = 0; i < 6; i++) {
            String name = gasCategories.get(i).getMolecularFormula()+"("+gasCategories.get(i).getName()+")";
            name = name + "、";
            if (i < 5){
                fiveGas = fiveGas + name;
                if (i == 4){
                    int index = fiveGas.lastIndexOf("、");
                    fiveGas =  fiveGas.substring(0, index)+"共五种";
                }
            }
            if (i < 6){
                sixGas = sixGas + name;
                if (i == 5){
                    int index = sixGas.lastIndexOf("、");
                    sixGas =  sixGas.substring(0, index)+"共六种";
                }
            }
        }
        map.put("${fiveGas}",fiveGas);
        map.put("${sixGas}",sixGas);
        return map;
    }
}