XtDataSameJob.java 18.2 KB
package com.skua.modules.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.skua.core.util.ConvertUtils;
import com.skua.core.util.DateUtils;
import com.skua.core.util.chuanglan.HttpSenderMsg;
import com.skua.modules.alarmtmp.entity.AlarmMessageHistory;
import com.skua.modules.alarmtmp.entity.AlarmRecordHistory;
import com.skua.modules.alarmtmp.entity.AlarmRuleConfig;
import com.skua.modules.alarmtmp.entity.AlarmRuleLevelConfigTemplate;
import com.skua.modules.alarmtmp.service.AlarmMessageHistoryService;
import com.skua.modules.alarmtmp.service.AlarmRecordHistoryService;
import com.skua.modules.alarmtmp.service.AlarmRuleConfigService;
import com.skua.modules.alarmtmp.service.IAlarmDataSameService;
import com.skua.modules.alarmtmp.service.IAlarmRuleLevelConfigTemplateService;
import com.skua.modules.alarmtmp.vo.SystemNoticeVO;
import com.skua.modules.system.datestandard.entity.SysMonitorMetricInfo;
import com.skua.modules.system.datestandard.service.ISysMonitorMetricInfoService;
import com.skua.modules.system.entity.SysUser;
import com.skua.modules.system.service.IPgService;
import com.skua.modules.system.service.ISysDepartService;
import com.skua.modules.system.service.ISysUserService;
import com.skua.modules.util.SystemNoticeUtils;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description 数据长期不变
 * @Date 2021-09-03 13:46
 * @Param
 * @return
 **/

@Slf4j
@Component
public class XtDataSameJob implements Job {

    @Autowired
    private ISysMonitorMetricInfoService sysMonitorMetricInfoService;
    @Autowired
    private SystemNoticeUtils systemNoticeUtils;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private AlarmRecordHistoryService alarmRecordHistoryService;

    @Autowired
    private AlarmMessageHistoryService alarmMessageHistoryService;

    @Autowired
    private IAlarmRuleLevelConfigTemplateService alarmRuleLevelConfigTemplateService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPgService pgService;
    
    @Autowired
    private AlarmRuleConfigService alarmRuleConfigService;


    //${start}采集数据${conent}超过${data},请注意!
    private static String prefix = "【金控数矿】";
    private static String departNameTemplete = "${departName}";
    private static String contentTemplete = "${content}";
    private static String dataTemplete = "${data}";
    private static String suffix = ",请注意!";

    //添加到报警记录表,用于移动端审批的使用
    private static String tableName = "alarm_record_history";

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        try {
            log.info("数据长期不变状态任务开始");
            //先计算数据
            dealSameData();
            log.info("数据长期不变状态任务结束");
        } catch (Exception e) {
            log.info("数据长期不变状态任务异常" + e);
        }
    }
    
    /**
     * <pre>
     * 获取长期不变数据,并入库存储
     * </pre>
     * @author Li Yuanyuan, 2023年3月31日 下午2:31:56
     * @throws ParseException 
     * @Description: TODO(这里描述这个方法的需求变更情况)
     */
    private void dealSameData() throws ParseException {
        //查询报警配置表,获取模拟量点
    	QueryWrapper<AlarmRuleConfig> alarmQuaryWrapper = new QueryWrapper<AlarmRuleConfig>();
    	alarmQuaryWrapper.select("alarm_program_code","depart_id");
    	alarmQuaryWrapper.eq("alarm_rule_status", "1");
    	//TODO 这里1,2,3,5,8代表模拟量的报警数据,后期需要优化此处
    	alarmQuaryWrapper.in("alarm_rule_type", Arrays.asList("1,2,3,5,8".split(",")));
    	List<AlarmRuleConfig> alarmRuleConfigList = alarmRuleConfigService.list(alarmQuaryWrapper);
    	//构造报警规则Map对象,按照机构做数据分组
    	Map<String,List<AlarmRuleConfig>> alarmRuleConfigMapping = new HashMap<String,List<AlarmRuleConfig>>();
    	//拼接模拟量指标
    	alarmRuleConfigList.forEach(alarmRuleConfig ->{
    		String departId = alarmRuleConfig.getDepartId();
    		List<AlarmRuleConfig> departGroupList = alarmRuleConfigMapping.get(departId);
    		if(departGroupList==null) {
    			departGroupList = new ArrayList<AlarmRuleConfig>();
    			alarmRuleConfigMapping.put(departId, departGroupList);
    		}
    		departGroupList.add(alarmRuleConfig);
    	});
    	//构造报警模板Map对象,按机构做数据分组
    	Map<String,AlarmRuleLevelConfigTemplate> alarmTempleteMapping = new HashMap<String,AlarmRuleLevelConfigTemplate>();
    	
    	QueryWrapper<AlarmRuleLevelConfigTemplate> templeteQueryWrapper = new QueryWrapper<AlarmRuleLevelConfigTemplate>();
		templeteQueryWrapper.eq("alarm_template_name", "数据长期不变累计时长报警配置");
		templeteQueryWrapper.eq("alarm_template_type", 5);
		templeteQueryWrapper.isNotNull("cumulative_time");
        List<AlarmRuleLevelConfigTemplate> templeteList = alarmRuleLevelConfigTemplateService.list(templeteQueryWrapper);
        templeteList.forEach(alarmRuleLevelConfigTemplate ->{
        	String departId = alarmRuleLevelConfigTemplate.getDepartId();
        	String cumulativeTime = alarmRuleLevelConfigTemplate.getCumulativeTime();
        	if(StringUtils.isNotBlank(cumulativeTime)){
        		alarmTempleteMapping.put(departId, alarmRuleLevelConfigTemplate);
        	}
        });
    	
    	String endTime = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
    	
    	Set<String> departIdSet = alarmTempleteMapping.keySet();
    	
    	departIdSet.forEach(departId ->{
    		//获取累计时常
    		AlarmRuleLevelConfigTemplate alarmRuleLevelConfigTemplate = alarmTempleteMapping.get(departId);
    		String cumulativeTime = alarmRuleLevelConfigTemplate.getCumulativeTime();
    		
    		List<AlarmRuleConfig> alarmRuleConfigGroupList = alarmRuleConfigMapping.get(departId);
    		StringBuffer fieldCodeBuffer = new StringBuffer();
    		alarmRuleConfigGroupList.forEach(alarmRuleConfig ->{
    			fieldCodeBuffer.append(","+alarmRuleConfig.getAlarmProgramCode());
    		});
    		String fieldCodes = fieldCodeBuffer.toString();
        	if(StringUtils.isNotBlank(fieldCodes)) {
        		fieldCodes = fieldCodes.substring(1);
        	}
    		//获取模板累计时长数据
    		try {
				Map<String, Set<String>> sameDataMap = pgService.queryDataSameData(departId,fieldCodes, DateUtils.formatAddTime(endTime, "yyyy-MM-dd HH:mm:ss", Calendar.HOUR_OF_DAY, -ConvertUtils.getInt(cumulativeTime)), endTime);
				//按厂站处理报警数据
				dealAlarmData(departId,alarmRuleLevelConfigTemplate,sameDataMap);
    		} catch (Exception e) {
				e.printStackTrace();
			}
    	});
    	
    }
    
    public void dealAlarmData(String departId,AlarmRuleLevelConfigTemplate alarmRuleLevelConfigTemplate,Map<String, Set<String>> sameDataMap) {
    	//获取机构名称
    	String departName = sysDepartService.queryDepartNameById(departId);
    	//采集点位set集合
    	Set<String> monitorFieldSet = sameDataMap.keySet();
    	//判定是否存在未处理报警记录
    	QueryWrapper<AlarmRecordHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("depart_id", departId);
        queryWrapper.in("alarm_param_code", monitorFieldSet);
        queryWrapper.eq("alarm_param_type", alarmRuleLevelConfigTemplate.getAlarmTemplateName());
        queryWrapper.eq("alarm_rule_type", "5");
        queryWrapper.eq("handle_status", "0");
        List<AlarmRecordHistory> alarmRecordHistoryList = alarmRecordHistoryService.list(queryWrapper);
        Map<String,AlarmRecordHistory> alarmRecordHistoryMapping = new HashMap<String,AlarmRecordHistory>();
        if(alarmRecordHistoryList!=null) {
        	alarmRecordHistoryList.forEach(alarmRecordHistory ->{
        		alarmRecordHistoryMapping.put(alarmRecordHistory.getAlarmParamCode(), alarmRecordHistory);
        	});
        }
        //构造报警要恢复的数据集合
        List<AlarmRecordHistory> resumeList = new ArrayList<AlarmRecordHistory>();
        //构造新报警数据集合
        List<AlarmRecordHistory> addList = new ArrayList<AlarmRecordHistory>();
        
        monitorFieldSet.forEach(monitorField ->{
        	//获取未处理的报警记录
        	AlarmRecordHistory alarmRecordHistory = alarmRecordHistoryMapping.get(monitorField);
        	if(alarmRecordHistory!=null) {
        		//存在未处理的记录,
        		Set<String> valueSet = sameDataMap.get(monitorField);
        		if(valueSet!=null&&valueSet.size()>1) {
        			//在限定时间内数据存在变化,出发自动处理服务
        			alarmRecordHistory.setHandleUser("admin");
        	        alarmRecordHistory.setHandleTime(DateUtils.getDate());
        	        alarmRecordHistory.setHandleStatus(1);
        	        resumeList.add(alarmRecordHistory);
        		}else if(valueSet!=null&&valueSet.size()==1){
        			//如果短信发送频率设置,此处逻辑用处不多,后续优化
        		}
        	}else {
        		Set<String> valueSet = sameDataMap.get(monitorField);
        		if(valueSet!=null&&valueSet.size()==1) {
        			//不存在未处理记录,数据新增
            		alarmRecordHistory = new AlarmRecordHistory();
            		String value = ConvertUtils.getString(valueSet.toArray()[0]);
            		//手动创建UUID,用于报警自动送审
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    alarmRecordHistory.setId(uuid);
                    alarmRecordHistory.setAlarmParamCode(monitorField);
                    SysMonitorMetricInfo sysMonitorMetricInfo = sysMonitorMetricInfoService.getById(monitorField);
                    alarmRecordHistory.setAlarmParamName(sysMonitorMetricInfo.getMetricName());
                    alarmRecordHistory.setAlarmRuleLevelName(alarmRuleLevelConfigTemplate.getAlarmTemplateLevelName());
                    alarmRecordHistory.setAlarmRuleType("5");
                    alarmRecordHistory.setAlarmParamType(alarmRuleLevelConfigTemplate.getAlarmTemplateName());
                    alarmRecordHistory.setRecordTime(DateUtil.date());
                    alarmRecordHistory.setAlarmParamUnit(sysMonitorMetricInfo.getMetricUnit());
                    alarmRecordHistory.setDepartId(departId);
                    alarmRecordHistory.setActualAvgValue(value);
                    alarmRecordHistory.setHandleStatus(0);
                    alarmRecordHistory.setDelFlag(1);
                    //${start}采集数据${conent}已超标,请注意!
                    //最大值超标
                    String firstContent = contentTemplete.replace("${content}", sysMonitorMetricInfo.getMetricName() + sysMonitorMetricInfo.getMetricUnit());
                    String secondContent = dataTemplete.replace("${data}", alarmRuleLevelConfigTemplate.getCumulativeTime() + "小时保持" + value + "没有变化");
                    alarmRecordHistory.setAlarmContent(prefix + departName + "采集数据" + firstContent + "超过" + secondContent+suffix);
                    alarmRecordHistory.setCreateBy("admin");
                    addList.add(alarmRecordHistory);
        		}
        	}
        });
        //未处理报警数据自动恢复
        if(resumeList!=null&&resumeList.size()>0) {
        	alarmRecordHistoryService.saveOrUpdateBatch(resumeList);
        }
    	//新增报警记录添加推送功能
        sendMessage(addList,alarmRuleLevelConfigTemplate);
    }
    
    public void sendMessage(List<AlarmRecordHistory> addList,AlarmRuleLevelConfigTemplate alarmRuleLevelConfigTemplate) {
    	if(addList!=null&&addList.size()>0) {
    		//批量新增
    		alarmRecordHistoryService.saveOrUpdateBatch(addList);
    		addList.forEach(alarmRecordHistory ->{
    			//判断是否需要发送系统通知 (内容跟报警记录信息相同)
                if ("1".equals(alarmRuleLevelConfigTemplate.getIsSendNotice())) {
                    if (StringUtils.isNotBlank(alarmRuleLevelConfigTemplate.getAlarmNoticeRecipient())) {
                        SystemNoticeVO systemNoticeVO = new SystemNoticeVO(alarmRuleLevelConfigTemplate.getAlarmNoticeRecipient(),
                                alarmRuleLevelConfigTemplate.getAlarmTemplateLevelName(), alarmRecordHistory.getAlarmContent(), alarmRecordHistory.getDepartId(), "5");
                        systemNoticeUtils.dealNoticeMessage(systemNoticeVO);
                    }
                }
                //判断是否需要发送短信,1表示发送
                if (alarmRuleLevelConfigTemplate.getIsSendSms().equals("1")) {
                	SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm");
                	String date = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
					//判读是否在发送时间内
                    Date allowStartDate = null;
                    Date allowEndDate = null;
                    Date nowDate = null;
                	try {
						//判读是否在发送时间内
	                    allowStartDate = simpleDateFormatHour.parse(alarmRuleLevelConfigTemplate.getSmsAllowSendTime().split("-")[1]);
	                    allowEndDate = simpleDateFormatHour.parse(alarmRuleLevelConfigTemplate.getSmsAllowSendTime().split("-")[0]);
	                    nowDate = simpleDateFormatHour.parse(date.substring(11, 16));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    
                    //如果在发送时间内,则发送
                    if (isEffectiveDate(nowDate, allowStartDate, allowEndDate)) {
                        //判断是否满足报警频率,将两个时间转为毫秒
                            List<String> userList = new ArrayList<>();
                            String alarmSmsRecipient = alarmRuleLevelConfigTemplate.getAlarmSmsRecipient();
                            //获取需要发送短信的手机号
                            if (StringUtils.isNotBlank(alarmSmsRecipient)) {
                            	userList = Arrays.asList(alarmSmsRecipient.split(","));
                                QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
                                sysUserQueryWrapper.in("id", userList);
                                List<SysUser> sysUserList = sysUserService.list(sysUserQueryWrapper);
                                //获取报警接收人的手机号
                                StringBuilder phoneStringBuilder = new StringBuilder();
                                for (int i = 0; i < sysUserList.size(); i++) {
                                    phoneStringBuilder.append(",");
                                    String phone = sysUserList.get(i).getPhone();
                                    if (StringUtils.isNotBlank(phone)) {
                                        phoneStringBuilder.append(phone);
                                        //发送短信
                                        HttpSenderMsg.sendMsg(alarmRecordHistory.getAlarmContent(), phone);
                                        log.info("短信发送成功手机号:" + phone + ",内容:" +alarmRecordHistory.getAlarmContent());
                                    }
                                }
                                String phone = phoneStringBuilder.toString().substring(1);
                                if (StringUtils.isNotBlank(phone)) {
                                    //将发送的短信保存到数据库
                                    AlarmMessageHistory alarmMessageHistory = new AlarmMessageHistory();
                                    alarmMessageHistory.setAlarmSendUser(alarmSmsRecipient);
                                    alarmMessageHistory.setAlarmSendPhone(phone);
                                    alarmMessageHistory.setAlarmSendTime(DateUtil.date());
                                    alarmMessageHistory.setAlarmSendContent(alarmRecordHistory.getAlarmContent());
                                    alarmMessageHistory.setAlarmSendType("1");
                                    alarmMessageHistory.setAlarmParamCode(alarmRecordHistory.getAlarmParamCode());
                                    alarmMessageHistory.setAlarmParamName(alarmRecordHistory.getAlarmParamName());
                                    //alarmMessageHistory.setAlarmRuleLevelId("");//预留后期选择指标配置功能
                                    alarmMessageHistory.setAlarmRuleType("5");
                                    //alarmMessageHistory.setAlarmParamUpperLimit(maxValue.toString());
                                    //alarmMessageHistory.setAlarmParamLowerLimit(minValue.toString());
                                    alarmMessageHistory.setAlarmParamUnit(alarmRecordHistory.getAlarmParamUnit());
                                    alarmMessageHistory.setDepartId(alarmRecordHistory.getDepartId());
                                    alarmMessageHistory.setActualAvgValue(alarmRecordHistory.getActualAvgValue());
                                    alarmMessageHistoryService.save(alarmMessageHistory);
                                }
                            }
                        }
                    }
    		});
    	}
    }
    

    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }


    }
}