package com.zhgd.xmgl.task; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.zhgd.xmgl.call.api.DevSmsManufacturer; import com.zhgd.xmgl.call.factory.DevSmsManufacturerFactory; import com.zhgd.xmgl.enums.ParamEnum; import com.zhgd.xmgl.modules.basicdata.constant.DictionaryConstant; import com.zhgd.xmgl.modules.basicdata.entity.DictionaryItem; import com.zhgd.xmgl.modules.basicdata.entity.SystemUser; import com.zhgd.xmgl.modules.basicdata.entity.bo.NoticeMessagePromptTone; import com.zhgd.xmgl.modules.basicdata.service.ISystemUserService; import com.zhgd.xmgl.modules.basicdata.service.impl.DictionaryItemServiceImpl; import com.zhgd.xmgl.modules.basicdata.service.impl.NoticeServiceImpl; import com.zhgd.xmgl.modules.environment.entity.EnvironmentAlarm; import com.zhgd.xmgl.modules.environment.entity.EnvironmentAlarmType; import com.zhgd.xmgl.modules.environment.service.IEnvironmentAlarmService; import com.zhgd.xmgl.modules.environment.service.IEnvironmentAlarmTypeService; import com.zhgd.xmgl.modules.project.entity.EnableMessageDevRule; import com.zhgd.xmgl.modules.project.entity.Project; import com.zhgd.xmgl.modules.project.service.IEnableMessageDevRuleService; import com.zhgd.xmgl.modules.project.service.IProjectService; import com.zhgd.xmgl.modules.video.entity.AiAnalyseHardWareAlarmRecord; import com.zhgd.xmgl.modules.video.service.IAiAnalyseHardWareAlarmRecordService; import com.zhgd.xmgl.modules.xz.entity.XzAiDeductRule; import com.zhgd.xmgl.modules.xz.service.IXzAiDeductRuleService; import lombok.extern.slf4j.Slf4j; import net.javacrumbs.shedlock.core.SchedulerLock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @Slf4j @Component @RestController @RequestMapping("xmgl/task") public class MessageDevRuleTask { @Lazy @Autowired ISystemUserService systemUserService; @Lazy @Autowired private DevSmsManufacturerFactory devSmsManufacturerFactory; @Lazy @Resource private IEnvironmentAlarmService environmentAlarmService; @Lazy @Autowired private IEnableMessageDevRuleService enableMessageDevRuleService; @Lazy @Autowired private IEnvironmentAlarmTypeService environmentAlarmTypeService; @Lazy @Autowired private NoticeServiceImpl noticeService; @Lazy @Autowired private IAiAnalyseHardWareAlarmRecordService aiAnalyseHardWareAlarmRecordService; @Lazy @Autowired private DictionaryItemServiceImpl dictionaryItemService; @Lazy @Autowired private IProjectService projectService; @Lazy @Autowired private IXzAiDeductRuleService xzAiDeductRuleService; /** * 发送设备的报警通知 */ @SchedulerLock(name = "sendDevMessage", lockAtMostFor = 1000 * 60 * 60, lockAtLeastFor = 1000 * 60 * 5) @Scheduled(cron = "0 0 */1 * * ?") @RequestMapping("sendDevMessage") public void sendDevMessage() { try { Map environmentTypeMap = environmentAlarmTypeService.list().stream().collect(Collectors.toMap(EnvironmentAlarmType::getId, Function.identity(), (o1, o2) -> o1)); List projects = projectService.list(new LambdaQueryWrapper()); Map>>> devSn2Parameter2LevelEnvironmentAlarmMap = environmentAlarmService.list(new LambdaQueryWrapper() .ge(EnvironmentAlarm::getAlarmTime, DateUtil.formatDateTime(DateUtil.offsetDay(new Date(), -1))) .le(EnvironmentAlarm::getAlarmTime, new Date()) ).stream().collect(Collectors.groupingBy(EnvironmentAlarm::getDeviceId, Collectors.groupingBy(ea -> environmentTypeMap.get(ea.getAlarmTypeId()).getAlarmType(), Collectors.groupingBy(ea -> Objects.equals(ea.getType(), 0) ? "报警" : "预警")))); List ruleList = enableMessageDevRuleService.list(new LambdaQueryWrapper().eq(EnableMessageDevRule::getIsEnabled, 1)); Map userMap = systemUserService.list(new LambdaQueryWrapper()).stream().collect(Collectors.toMap(SystemUser::getUserId, Function.identity(), (o1, o2) -> o1)); Map> moduleMap = ruleList.stream().collect(Collectors.groupingBy(EnableMessageDevRule::getMonitoringModuleName)); for (Project project : projects) { List dictList = dictionaryItemService.getDictList(DictionaryConstant.AI_ANALYSE_HARD_WARE_ALARM_RECORD_TYPE, project.getProjectSn()); Map dictDataMap = dictList.stream().collect(Collectors.toMap(DictionaryItem::getData, Function.identity(), (o1, o2) -> o1)); Map dicIdMap = xzAiDeductRuleService.list(new LambdaQueryWrapper() .eq(XzAiDeductRule::getProjectSn, project.getProjectSn())).stream().collect(Collectors.toMap(XzAiDeductRule::getDictionaryItemId, Function.identity(), (o1, o2) -> o1)); Map>>> devSn2Parameter2LevelAiMap = aiAnalyseHardWareAlarmRecordService.list(new LambdaQueryWrapper() .ge(AiAnalyseHardWareAlarmRecord::getCreateTime, DateUtil.formatDateTime(DateUtil.offsetDay(new Date(), -1))) .le(AiAnalyseHardWareAlarmRecord::getCreateTime, new Date()) ).stream().filter(r -> { return Objects.nonNull(Optional.ofNullable(dictDataMap.get(Convert.toStr(r.getAlarmType()))).map(m -> dicIdMap.get(m.getId())).map(XzAiDeductRule::getLevel).orElse(null)); }).collect(Collectors.groupingBy(AiAnalyseHardWareAlarmRecord::getHardwareId, Collectors.groupingBy(r1 -> dictDataMap.get(Convert.toStr(r1.getAlarmType())).getName(), Collectors.groupingBy(r -> Optional.of(dictDataMap.get(Convert.toStr(r.getAlarmType()))).map(m -> dicIdMap.get(m.getId())).map(r1 -> { if (Objects.equals(r1.getLevel(), 1)) { return "一级"; } else if (Objects.equals(r1.getLevel(), 2)) { return "二级"; } else if (Objects.equals(r1.getLevel(), 3)) { return "三级"; } else { return "四级"; } }).orElse(null))))); for (Map.Entry> moduleEntry : moduleMap.entrySet()) { List entryRules = moduleEntry.getValue(); for (EnableMessageDevRule rule : entryRules) { //扬尘 if (Objects.equals(ParamEnum.MessageModuleNameEnum.YCJC.getDesc(), moduleEntry.getKey())) { List filterAlarms = Optional.ofNullable(devSn2Parameter2LevelEnvironmentAlarmMap.get(rule.getDevSn())) .map(m -> m.get(rule.getMonitoringParameterName())).map(m -> m.get(rule.getMonitoringLevelName())).orElse(new ArrayList<>()); filterAlarms = filterAlarms.stream().filter(alarm -> DateUtil.compare(alarm.getAlarmTime(), DateUtil.offsetHour(new Date(), rule.getSmsPushFrequency() * -1)) >= 0 && DateUtil.compare(alarm.getAlarmTime(), new Date()) <= 0).collect(Collectors.toList()); //sms if (CollUtil.isNotEmpty(filterAlarms)) { sendNotice(rule, filterAlarms.size(), userMap, "7"); } } //AI if (Objects.equals(ParamEnum.MessageModuleNameEnum.AIJC.getDesc(), moduleEntry.getKey())) { List filterAlarms = Optional.ofNullable(devSn2Parameter2LevelAiMap.get(rule.getDevSn())) .map(m -> m.get(rule.getMonitoringParameterName())).map(m -> m.get(rule.getMonitoringLevelName())).orElse(new ArrayList<>()); filterAlarms = filterAlarms.stream().filter(alarm -> DateUtil.compare(DateUtil.parse(alarm.getCreateTime()), DateUtil.offsetHour(new Date(), rule.getSmsPushFrequency() * -1)) >= 0 && DateUtil.compare(DateUtil.parse(alarm.getCreateTime()), new Date()) <= 0).collect(Collectors.toList()); //sms if (CollUtil.isNotEmpty(filterAlarms)) { sendNotice(rule, filterAlarms.size(), userMap, "8"); } } } } } } catch (Exception e) { log.error("发送设备的报警通知", e); } } /** * 发送通知 * * @param rule * @param filterAlarms * @param userMap * @param type */ private void sendNotice(EnableMessageDevRule rule, int filterAlarms, Map userMap, String type) { if (Objects.equals(rule.getEnableSmsNotification(), 1) && isSmsSendTime(rule)) { DevSmsManufacturer messageManufacturer = devSmsManufacturerFactory.getMessageManufacturer(rule.getProjectSn()); if (messageManufacturer != null) { String text = StrUtil.format("{}{}{}异常,近{}小时累计报警{}次!", rule.getMonitoringModuleName(), rule.getMonitoringParameterName(), rule.getMonitoringLevelName(), rule.getSmsPushFrequency(), filterAlarms); List phoneNums = getPhoneNums(rule.getSmsAlarmRecipientIds(), userMap); if (CollUtil.isNotEmpty(phoneNums)) { messageManufacturer.sendMsg(phoneNums, rule.getNotificationSmsTemplateId(), null, text); } } } //系统站内 if (Objects.equals(rule.getEnableSystemMessagePush(), 1) && isSystemSendTime(rule)) { if (StrUtil.isNotBlank(rule.getAlarmRecipientIds())) { List ids = StrUtil.split(rule.getAlarmRecipientIds(), ",").stream().map(Convert::toLong).collect(Collectors.toList()); NoticeMessagePromptTone tone = null; //系统站内声音提示 if (Objects.equals(rule.getEnableSystemMessagePromptTone(), 1)) { tone = new NoticeMessagePromptTone(rule.getMessagePromptToneConfig(), rule.getPlaybackFrequency()); } for (Long id : ids) { noticeService.addUserNoticeAndApp(id, "设备报警通知", rule.getMessageTemplateContent(), type, tone); } } } } /** * 是需要发送的时间了 * * @param rule * @return */ private boolean isSystemSendTime(EnableMessageDevRule rule) { int hour = DateUtil.hour(new Date(), true); return Objects.nonNull(rule.getMessagePushFrequency()) && Objects.nonNull(rule.getMessagePushTimeBegin()) && Objects.nonNull(rule.getMessagePushTimeEnd()) && !Objects.equals(rule.getMessagePushFrequency(), 0) && hour % rule.getMessagePushFrequency() == 0 && rule.getMessagePushTimeBegin().getHour() <= hour && rule.getMessagePushTimeEnd().getHour() >= hour; } /** * 是需要发送的时间了 * * @param rule * @return */ private boolean isSmsSendTime(EnableMessageDevRule rule) { int hour = DateUtil.hour(new Date(), true); return Objects.nonNull(rule.getSmsPushFrequency()) && Objects.nonNull(rule.getSmsPushTimeBegin()) && Objects.nonNull(rule.getSmsPushTimeEnd()) && !Objects.equals(rule.getSmsPushFrequency(), 0) && hour % rule.getSmsPushFrequency() == 0 && rule.getSmsPushTimeBegin().getHour() <= hour && rule.getSmsPushTimeEnd().getHour() >= hour; } /** * 获取发送短信的号码 * * @param smsAlarmRecipientIds * @param userMap * @return */ private List getPhoneNums(String smsAlarmRecipientIds, Map userMap) { if (StrUtil.isBlank(smsAlarmRecipientIds)) { return null; } return StrUtil.split(smsAlarmRecipientIds, ",").stream().filter(id -> userMap.containsKey(Convert.toLong(id))).map(id -> userMap.get(Convert.toLong(id)).getUserTel()) .filter(StrUtil::isNotBlank).collect(Collectors.toList()); } }