From 44e84f1008d0c55c2e099c7b4b7eae866267b772 Mon Sep 17 00:00:00 2001
From: 潘志宝 <979469083@qq.com>
Date: 星期五, 07 二月 2025 15:37:49 +0800
Subject: [PATCH] 预警信息生成重复问题修复

---
 shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java |  174 ++++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 121 insertions(+), 53 deletions(-)

diff --git a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java
index aed70ef..19ab2ac 100644
--- a/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java
+++ b/shasteel-biz/src/main/java/com/iailab/module/shasteel/mq/consumer/ModelPredictFinishConsumer.java
@@ -6,7 +6,8 @@
 import com.iailab.module.model.api.mcs.dto.AlarmConfigRespDTO;
 import com.iailab.module.model.api.mcs.dto.AlarmMessageRespDTO;
 import com.iailab.module.model.api.mcs.dto.PreDataJsonReqVO;
-import com.iailab.module.shasteel.mq.common.RoutingConstant;
+import com.iailab.module.shasteel.mq.common.constant.CommonConstant;
+import com.iailab.module.shasteel.mq.common.constant.RoutingConstant;
 import com.iailab.module.shasteel.mq.config.QueuePredictFinishConfig;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.amqp.core.Message;
@@ -17,13 +18,12 @@
 
 import javax.annotation.Resource;
 import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
+import java.util.stream.Collectors;
 
 /**
  * 监听预测完成
+ * 根据预警配置产生预警信息
  *
  * @author PanZhibao
  * @Description
@@ -39,6 +39,8 @@
     @Resource
     private RabbitTemplate rabbitTemplate;
 
+    private static String lastRunAlarm = "";
+
     /**
      * 监听预测完成,产生预警消息
      *
@@ -46,62 +48,128 @@
      */
     @RabbitListener(queues = QueuePredictFinishConfig.QUEUE_NAME)
     public void listen(Message message) {
-        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
-        log.info("routingKey:" + routingKey);
-        String messageBody = new String(message.getBody());
-        log.info("messageBody:" + messageBody);
-        JSONObject messageJson = JSONObject.parseObject(messageBody);
-        List<AlarmConfigRespDTO> configList = mcsApi.listAlarmConfig(new HashMap<String, Object>());
-        if (CollectionUtils.isEmpty(configList)) {
-            return;
-        }
-        List<String> OutputIdList = new ArrayList<>();
-        configList.forEach(item -> {
-            OutputIdList.add(item.getOutId());
-        });
-        configList.forEach(item -> {
-            PreDataJsonReqVO reqVO = new PreDataJsonReqVO();
-            reqVO.setPredictTime(DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
-            reqVO.setOutputIdList(OutputIdList);
-            Map<String, List<Object[]>> preData = mcsApi.getPreDataCur(reqVO);
-            if (CollectionUtils.isEmpty(preData)) {
+        try {
+            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
+            log.info("routingKey:" + routingKey);
+            String messageBody = new String(message.getBody());
+            log.info("messageBody:" + messageBody);
+            JSONObject messageJson = JSONObject.parseObject(messageBody);
+            if (CollectionUtils.isEmpty(messageJson)) {
                 return;
             }
-            List<Object[]> result = preData.get(item.getOutId());
-            int toIndex = result.size();
-            if (toIndex <= 0) {
+            // 预测时间
+            Date predictTime = DateUtils.parse(messageJson.get("predictTime").toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND);
+            // 预测模块/预测管网
+            String moduleType = messageJson.get("moduleType").toString();
+            // 查询相关预警配置
+            List<AlarmConfigRespDTO> configList = mcsApi.listAlarmConfig(new HashMap<String, Object>());
+            if (CollectionUtils.isEmpty(configList)) {
+                log.info("AlarmConfigList is empty");
                 return;
             }
-            int fromIndex = result.size() - item.getCompLength();
-            List<Object[]> predictList = result.subList(fromIndex, toIndex);
-            for (Object[] data : predictList) {
-                BigDecimal dataValue = new BigDecimal(Double.parseDouble(data[1].toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
-                if (!(dataValue.compareTo(item.getLowerLimit()) >= 0 && dataValue.compareTo(item.getUpperLimit()) <= 0)) {
+            List<String> outputIdList = configList.stream().map(item -> {
+                return item.getOutId();
+            }).collect(Collectors.toList());
+            List<AlarmMessageRespDTO> alarmList = new ArrayList<>();
+            if (moduleType.equals(CommonConstant.NET_BFG) || moduleType.equals(CommonConstant.NET_COG) ||
+                    moduleType.equals(CommonConstant.NET_LDG)) {
+                String runKey = "GasAlarm_" +  predictTime.getTime();
+                log.info("runKey:" + runKey);
+                log.info("lastRunAlarm:" + lastRunAlarm);
+                if (lastRunAlarm.equals(runKey)) {
+                    return;
+                }
+                lastRunAlarm = runKey;
+                for (AlarmConfigRespDTO configItem : configList) {
+                    PreDataJsonReqVO reqVO = new PreDataJsonReqVO();
+                    reqVO.setPredictTime(predictTime);
+                    reqVO.setOutputIdList(outputIdList);
+                    Map<String, List<Object[]>> preData = mcsApi.getPreDataCur(reqVO);
+                    if (CollectionUtils.isEmpty(preData)) {
+                        return;
+                    }
+                    Map<String, BigDecimal> culData = new HashMap<>();
+                    preData.forEach((key, value) -> {
+                        double nv = value.stream().map(v1 -> {
+                            return Double.parseDouble(v1[1].toString());
+                        }).collect(Collectors.toList()).stream().mapToDouble(Double::doubleValue).sum();
+                        culData.put(key, new BigDecimal(nv));
+                    });
+
+                    List<Object[]> result = preData.get(configItem.getOutId());
+                    if (CollectionUtils.isEmpty(result)) {
+                        continue;
+                    }
+                    // 累计值
+                    BigDecimal culValue = new BigDecimal(result.stream().map(v1 -> {
+                        return Double.parseDouble(v1[1].toString());
+                    }).collect(Collectors.toList()).stream().mapToDouble(Double::doubleValue).sum());
+                    log.info("culValue:" + culValue);
+
+                    // 生成预警信息
                     AlarmMessageRespDTO alarmMessage = new AlarmMessageRespDTO();
-                    alarmMessage.setConfigId(item.getId());
-                    if (dataValue.compareTo(item.getLowerLimit()) < 0) {
-                        alarmMessage.setAlarmType("1");//超下限
-                    } else if (dataValue.compareTo(item.getUpperLimit()) > 0) {
-                        alarmMessage.setAlarmType("2");//超上限
+                    alarmMessage.setConfigId(configItem.getId());
+                    alarmMessage.setTitle(configItem.getTitle());
+                    alarmMessage.setAlarmObj(configItem.getAlarmObj());
+                    alarmMessage.setAlarmTime(predictTime);
+                    log.info("对比累计值是否超限");
+                    StringBuilder content = new StringBuilder();
+                    if (configItem.getCulUpper() != null && culValue.compareTo(configItem.getCulUpper()) > 0) {
+                        content.append("即将超出累计值上限");
+                        alarmMessage.setAlarmType(CommonConstant.EXCEEDING_UPPER_LIMIT);
+                        alarmMessage.setContent(content.toString());
+                        mcsApi.createAlarmMessage(alarmMessage);
+                        alarmList.add(alarmMessage);
+                        continue;
                     }
-                    alarmMessage.setAlarmTime(DateUtils.parse(data[0].toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
-                    StringBuffer sb = new StringBuffer();
-                    sb.append(data[0]);
-                    sb.append(item.getAlarmObj());
-                    if("1".equals(alarmMessage.getAlarmType())){
-                        sb.append("超下限");
-                    }else if("2".equals(alarmMessage.getAlarmType())){
-                        sb.append("超上限");
+                    if (configItem.getCulLower() != null && culValue.compareTo(configItem.getCulLower()) < 0) {
+                        content.append("即将低于累计值下限");
+                        alarmMessage.setAlarmType(CommonConstant.EXCEEDING_LOWER_LIMIT);
+                        alarmMessage.setContent(content.toString());
+                        mcsApi.createAlarmMessage(alarmMessage);
+                        alarmList.add(alarmMessage);
+                        continue;
                     }
-                    sb.append(dataValue);
-                    sb.append(item.getUnit());
-                    alarmMessage.setContent(sb.toString());
-                    System.out.println("预警消息=" + alarmMessage);
-                    rabbitTemplate.convertAndSend(RoutingConstant.EXCHANGE, RoutingConstant.Iailab_Model_Alarm, alarmMessage);
-                    break;
+
+                    log.info("对比预测值是否超限");
+                    int toIndex = result.size();
+                    int fromIndex = result.size() - configItem.getCompLength();
+                    List<Object[]> predictList = result.subList(fromIndex, toIndex);
+                    for (Object[] data : predictList) {
+                        BigDecimal dataValue = new BigDecimal(Double.parseDouble(data[1].toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
+                        if (dataValue.compareTo(configItem.getLowerLimit()) >= 0 && dataValue.compareTo(configItem.getUpperLimit()) <= 0) {
+                            log.info("预测值不超限");
+                            continue;
+                        }
+                        alarmMessage.setOutTime(DateUtils.parse(data[0].toString(), DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
+                        content.append(DateUtils.format(alarmMessage.getOutTime(), DateUtils.FORMAT_SIMPLE_TIME));
+                        content.append(",");
+                        content.append("即将");
+                        if (dataValue.compareTo(configItem.getLowerLimit()) < 0) {
+                            content.append("低与下限");
+                            alarmMessage.setAlarmType(CommonConstant.EXCEEDING_LOWER_LIMIT);
+
+                        } else if (dataValue.compareTo(configItem.getUpperLimit()) > 0) {
+                            content.append("超出上限");
+                            alarmMessage.setAlarmType(CommonConstant.EXCEEDING_UPPER_LIMIT);
+                        }
+                        alarmMessage.setContent(content.toString());
+                        mcsApi.createAlarmMessage(alarmMessage);
+                        alarmList.add(alarmMessage);
+                        break;
+                    }
                 }
             }
-            System.out.println(preData);
-        });
+            if (!CollectionUtils.isEmpty(alarmList)) {
+                log.info("发送预警消息");
+                Map<String, Object> msg = new HashMap<>(2);
+                msg.put("predictTime", DateUtils.format(predictTime, DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));
+                msg.put("alarmList", alarmList);
+                rabbitTemplate.convertAndSend(RoutingConstant.EXCHANGE, RoutingConstant.Iailab_Model_Alarm, msg);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
     }
 }
\ No newline at end of file

--
Gitblit v1.9.3