From d4020168658efdee89a633083cd9c14b06c4d863 Mon Sep 17 00:00:00 2001
From: zhangf <1603559716@qq.com>
Date: 星期三, 11 九月 2024 17:09:10 +0800
Subject: [PATCH] 修改消息推送时间间隔

---
 src/main/java/com/gkhy/fourierSpecialGasMonitor/schedule/DailyReportSchedule.java |  125 +++++++++++++++++++++++++++--------------
 1 files changed, 83 insertions(+), 42 deletions(-)

diff --git a/src/main/java/com/gkhy/fourierSpecialGasMonitor/schedule/DailyReportSchedule.java b/src/main/java/com/gkhy/fourierSpecialGasMonitor/schedule/DailyReportSchedule.java
index 722471f..8ced11b 100644
--- a/src/main/java/com/gkhy/fourierSpecialGasMonitor/schedule/DailyReportSchedule.java
+++ b/src/main/java/com/gkhy/fourierSpecialGasMonitor/schedule/DailyReportSchedule.java
@@ -1,10 +1,9 @@
 package com.gkhy.fourierSpecialGasMonitor.schedule;
 
-import com.alibaba.fastjson.JSON;
-import com.gkhy.fourierSpecialGasMonitor.commons.enums.ForeignResultCode;
+import com.gkhy.fourierSpecialGasMonitor.Application;
 import com.gkhy.fourierSpecialGasMonitor.commons.enums.ResultCode;
+import com.gkhy.fourierSpecialGasMonitor.commons.enums.SystemCacheKeyEnum;
 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.*;
@@ -16,10 +15,6 @@
 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;
@@ -33,15 +28,14 @@
 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.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
+import java.time.Month;
 import java.time.format.DateTimeFormatter;
 import java.time.temporal.ChronoUnit;
 import java.util.*;
@@ -65,6 +59,8 @@
 
     private final Logger logger = LoggerFactory.getLogger(this.getClass());
 
+    private static int serialNumber = 4;
+
     @Autowired
     private GasWarnLogService gasWarnLogService;
 
@@ -86,30 +82,55 @@
     @Autowired
     private MonitorDailyReportService monitorDailyReportService;
 
+    @Autowired
+    private GasCategoryService gasCategoryService;
+
     @Scheduled(cron = "0 0 2 * * ?") //每天两点执行一次
+//    @Scheduled(cron = "0 0/1 * * * ? ")    // 分钟
     @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");
+        RBucket<List<GasCategory>> bucket = redissonClient.getBucket(SystemCacheKeyEnum.KEY_GAS_CATEGORY.getKey());
         List<GasCategory> gasCategories = bucket.get();
-        //logger.info("【##】开始生成日报 ,时间:"+startTime);
+        serialNumber = 4;
+        logger.info("【##】开始生成日报 ,时间:"+startTime);
         OPCPackage opcPackage = null;
         //加载文档
         XWPFDocument doc = null;
         try {
-            FileInputStream originalFileInputStream = new FileInputStream("src/main/resources/template/dailyReportTemplate.docx");
-            FileOutputStream copyFileOutputStream = new FileOutputStream("src/main/resources/temp/dailyReportTemplate.docx");
-            // 创建副本文件
+            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("src/main/resources/temp/dailyReportTemplate.docx");
+            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) {
             //获取段落的文本对象
@@ -164,16 +185,19 @@
         } catch (IOException e) {
             e.printStackTrace();
         }
-        List<GasConcentration> gasConcentrations = gasConcentrationService.listDatabyTimeSlot(LocalDateTime.now().minusDays(2).with(LocalDate.MIN), LocalDateTime.now());
+        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++) {
+            List<GasCategory> gasCategoryForReport = gasCategoryService.findGasCategoryForReport();
+            for (int i = 0; i < gasCategoryForReport.size(); i++) {
                 String series = gasCategories.get(i).getMolecularFormula() + "浓度观测结果";
-                String title = "—" + 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.listYesterday();
+        List<GasFlux> gasFluxes = gasFluxService.listYesterdayTenAmToSixPm();
         List<Integer> areaNum = gasFluxes.stream().map(GasFlux::getAreaId).distinct().collect(Collectors.toList());
 
         List<Region> allRegion = regionService.findAll();
@@ -181,12 +205,24 @@
             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 <= 1; i++) {
-                for (int j = 0; j < 1; j++) {
-                    drawBarChart(gasFluxes, fileurl, regionMap.get(i), "柱形图" + gasCategories.get(j).getMolecularFormula(), i, j + 1);
+//            for (int j = 0; j < gasCategories.size(); j++) {
+//                for (int i = 1; i <= areaNum.size(); i++) {
+//                    //for (int j = 0; j < 20; j++) {
+//                    int finalI = i;
+//                    List<GasFlux> gasFluxesByArea = gasFluxes.stream().filter(gasFlux -> gasFlux.getAreaId() == finalI)
+//                            .collect(Collectors.toList());
+//                    drawBarChart(gasFluxesByArea, fileurl, regionMap.get(i), gasCategories.get(j).getMolecularFormula(), i, j + 1);
+//                }
+//            }
+                for (int i = 1; i <= areaNum.size(); i++) {
+                    //for (int j = 0; j < 20; j++) {
+                    int finalI = i;
+                    List<GasFlux> gasFluxesByArea = gasFluxes.stream().filter(gasFlux -> gasFlux.getAreaId() == finalI)
+                            .collect(Collectors.toList());
+                    drawBarChart(gasFluxesByArea, fileurl, regionMap.get(i), gasCategories.get(0).getMolecularFormula(), i, 1);
                 }
-            }
         }
         String endTime = LocalDateTime.now().format(execformatter);
         long execTime = ChronoUnit.SECONDS.between(now, LocalDateTime.now());
@@ -198,9 +234,13 @@
         MonitorDailyReport save = monitorDailyReportService.save(report);
         if (save == null)
             throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL,"日常报表保存失败");
-        //logger.info("【##】日报生成成功!!! ,时间:"+endTime+",所耗时间: "+execTime+"s");
+        logger.info("【##】日报生成成功!!! ,时间:"+endTime+",所耗时间: "+execTime+"s");
     }
 
+    /**
+     * @decription 画柱形图
+     * @author Mr.huang
+     */
     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))
@@ -240,6 +280,7 @@
         value2.add(n);
 
         List<XWPFChart> charts = doc.getCharts();
+        serialNumber++;
         for (int k = 0; k < charts.size(); k++) {
             XWPFChart xwpfChart = charts.get(k);
             XDDFTitle xddfTitletitle = xwpfChart.getTitle();
@@ -258,9 +299,9 @@
                     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);
+                    String chartTitle = "图"+serialNumber+" "+i+"号厂区排放"+molecularFormula+"通量反演结果";
+                    if ((j+"-"+i).equals(value)) {
+                        drawBarChartExec(charts.get(k), series2, x2, value2, chartTitle,molecularFormula);
                     }
                 } catch (ParserConfigurationException e) {
                     e.printStackTrace();
@@ -368,12 +409,12 @@
 
 
     public void drawBarChartExec(XWPFChart chart, String[] series, String[] categories,
-                                  List<Number[]> values, String chartTitle) {
+                                  List<Number[]> values, String chartTitle,String molecularFormula) {
         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)");
+        line.getValueAxes().get(0).setTitle(molecularFormula+" Emission Rate (ug/m^2/s)");
         final int numOfPoints = categories.length;
 
         final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
@@ -432,13 +473,13 @@
     private Map<String, Object> dataMap(List<GasCategory> gasCategories){
         LocalDateTime now = LocalDateTime.now();
         String today = now.format(formatter);
-        String yesterday = LocalDateTime.now().plusDays(1).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");
+        map.put("${generalradius}","1km");
+        map.put("${generalradiu}","300m");
 
         List<GasWarnLog> gasWarnLogs = gasWarnLogService.listYesterday();
         if (!CollectionUtils.isEmpty(gasWarnLogs)){
@@ -457,21 +498,21 @@
         }
         String fiveGas = "";
         String sixGas = "";
-        for (int i = 0; i < 6; i++) {
+        for (int i = 0; i < 3; i++) {
             String name = gasCategories.get(i).getMolecularFormula()+"("+gasCategories.get(i).getName()+")";
             name = name + "、";
-            if (i < 5){
+            if (i < 3){
                 fiveGas = fiveGas + name;
-                if (i == 4){
+                if (i == 2){
                     int index = fiveGas.lastIndexOf("、");
-                    fiveGas =  fiveGas.substring(0, index)+"共五种";
+                    fiveGas =  fiveGas.substring(0, index)+"共三种";
                 }
             }
-            if (i < 6){
+            if (i < 3){
                 sixGas = sixGas + name;
-                if (i == 5){
+                if (i == 2){
                     int index = sixGas.lastIndexOf("、");
-                    sixGas =  sixGas.substring(0, index)+"共六种";
+                    sixGas =  sixGas.substring(0, index)+"共三种";
                 }
             }
         }

--
Gitblit v1.9.2