package com.ho.flow.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.ho.business.entity.Station;
import com.ho.business.entity.TranslateName;
import com.ho.business.vo.DeviceTransfer;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.entity.UserDetailRespVO;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.flow.entity.process.MovementDTO;
import com.ho.flow.feignclient.BusinessFeignClient;
import com.ho.flow.mapper.AlarmConfigMapper;
import com.ho.flow.mapper.EventMapper;
import com.ho.flow.monitor.EventToProcessMonitor;
import com.ho.flow.service.AlarmConfigService;
import com.ho.flow.service.EventService;
import com.ho.flow.service.FlowOutApiService;
import com.ho.flow.service.SendSmsConfigService;
import com.ho.flow.vo.AlarmConfig;
import com.ho.flow.vo.Event;
import com.ho.flow.vo.req.AlarmConfig.AlarmConfigQueryVo;
import com.ho.flow.vo.req.SendSmsConfig.SendSmsConfigQueryReq;
import com.ho.flow.vo.req.event.EventAddReq;
import com.ho.flow.vo.resp.StationStatusRespVO;
import com.ho.flow.vo.resp.event.EventTypeAndLevelsReqVO;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author kerwin 原有flowable-src-1.0.jar
 */
@Service
@ConditionalOnProperty(
        name = {"switch.usedDefaultAlarmLogic"},
        havingValue = "true",
        matchIfMissing = true
)
public class FlowOutApiServiceImpl implements FlowOutApiService {
    private static final Logger log = LoggerFactory.getLogger(FlowOutApiServiceImpl.class);
    @Autowired
    Snowflake snowflake;
    @Autowired
    RedisService redisService;
    @Autowired
    EventMapper eventMapper;
    @Autowired
    AlarmConfigMapper alarmConfigMapper;
    @Autowired
    BusinessFeignClient businessFeignClient;
    @Autowired
    SendSmsConfigService sendSmsConfigService;
    @Autowired
    AlarmConfigService alarmConfigService;
    @Autowired
    EventService eventService;
    @Value("${spring.activiti.flag}")
    private Integer flag;
    EventToProcessMonitor monitor = new EventToProcessMonitor();

    public FlowOutApiServiceImpl() {
    }

    public Map<String, List<Event>> matchEventRecords(EventAddReq eventAddReq, JSONObject dataSet, Map<String, AlarmConfig> stationConfigMap, Map<String, AlarmConfig> groupConfigMap) {
        Map<String, List<Event>> resultMap = this.receiveEvent(eventAddReq, dataSet, stationConfigMap, groupConfigMap);
        return resultMap;
    }

    public Map<String, List<Event>> receiveEvent(EventAddReq eventAddReq, JSONObject dataSet, Map<String, AlarmConfig> stationConfigMap, Map<String, AlarmConfig> groupConfigMap) {
        Map<String, List<Event>> resultMap = new HashMap();
        List<Event> events = new ArrayList();
        List<Event> updateEvents = new ArrayList();
        List<Event> updateEventStatus = new ArrayList();
        Date date = new Date();
        String redisKey = eventAddReq.getDeviceType() + ":" + eventAddReq.getStationId() + ":" + eventAddReq.getSrcId();
        Map<Object, Object> hgetall = this.redisService.hgetall(redisKey);
        DeviceTransfer deviceTransfer = null;
        Iterator var13 = dataSet.entrySet().iterator();

        while(true) {
            while(true) {
                String k;
                Object v;
                AlarmConfig alarmConfig;
                do {
                    do {
                        if (!var13.hasNext()) {
                            resultMap.put("updateEvents", updateEvents);
                            resultMap.put("events", events);
                            resultMap.put("updateEventStatus", updateEventStatus);
                            return resultMap;
                        }

                        Map.Entry<String, Object> entry = (Map.Entry)var13.next();
                        k = (String)entry.getKey();
                        v = entry.getValue();
                    } while(v == null);

                    alarmConfig = null;
                    if (stationConfigMap.containsKey(k)) {
                        alarmConfig = (AlarmConfig)stationConfigMap.get(k);
                    } else if (groupConfigMap.containsKey(k)) {
                        alarmConfig = (AlarmConfig)groupConfigMap.get(k);
                    }
                } while(alarmConfig == null);

                Event event = new Event();
                boolean needSave = false;
                event.setSensType(alarmConfig.getSensType());
                if (CommonConstant.EventSignal.SIGNAL.equals(alarmConfig.getSensType())) {
                    needSave = true;
                    Integer value = (Integer)v;
                    String info = null;
                    if (eventAddReq.getDeviceType().contains("communicationStatus")) {
                        if (CommonConstant.ONE.equals(value)) {
                            info = alarmConfig.getInfo0();
                            event.setIsRecovery(CommonConstant.ONE);
                            event.setEventLevel(CommonConstant.EventLevel.notice);
                        } else {
                            info = alarmConfig.getInfo1();
                            event.setIsRecovery(CommonConstant.ZERO);
                            event.setEventLevel(alarmConfig.getAlarmLevel());
                        }
                    } else if ("communicationStatus".equals(k)) {
                        if (CommonConstant.ZERO.equals(value)) {
                            info = alarmConfig.getInfo0();
                            event.setIsRecovery(CommonConstant.ZERO);
                            event.setEventLevel(alarmConfig.getAlarmLevel());
                        } else if (CommonConstant.ONE.equals(value)) {
                            info = alarmConfig.getInfo1();
                            event.setIsRecovery(CommonConstant.ONE);
                            event.setEventLevel(CommonConstant.EventLevel.notice);
                        }
                    } else if (CommonConstant.ZERO.equals(value)) {
                        info = alarmConfig.getInfo0();
                        event.setIsRecovery(CommonConstant.ONE);
                        event.setEventLevel(CommonConstant.EventLevel.notice);
                    } else if (value > CommonConstant.ZERO) {
                        info = alarmConfig.getInfo1();
                        event.setIsRecovery(CommonConstant.ZERO);
                        event.setEventLevel(alarmConfig.getAlarmLevel());
                    }

                    event.setDescription(info);
                    TranslateName translate = eventService.getNameLanguage(event.getDescription());
                    event.setDescriptionEn(translate.getNameEn());
                    event.setDescriptionFra(translate.getNameFra());
                    event.setDescriptionSpa(translate.getNameSpa());
                    event.setDescriptionDe(translate.getNameDe());
                    event.setDescriptionPl(translate.getNamePl());
                    event.setDescriptionAra(translate.getNameAra());
                } else if (CommonConstant.EventSignal.TELEMETER.equals(alarmConfig.getSensType())) {
                    BigDecimal lowerLimit = alarmConfig.getLowerLimit();
                    BigDecimal upperLimit = alarmConfig.getUpperLimit();
                    BigDecimal value = new BigDecimal(String.valueOf(v));
                    String desc = alarmConfig.getColName() + "恢复";
                    if (upperLimit != null && value.compareTo(upperLimit) > 0) {
                        needSave = true;
                        desc = alarmConfig.getColName() + " 越上限";
                    }

                    if (lowerLimit != null && value.compareTo(lowerLimit) < 0) {
                        needSave = true;
                        desc = alarmConfig.getColName() + " 越下限";
                    }

                    event.setIsRecovery(CommonConstant.ONE);
                    event.setEventLevel(CommonConstant.EventLevel.notice);
                    if (needSave) {
                        event.setIsRecovery(CommonConstant.ZERO);
                        event.setEventLevel(CommonConstant.EventLevel.overLimit);
                    }

                    event.setDescription(desc);
                    TranslateName translate = eventService.getNameLanguage(event.getDescription());
                    event.setDescriptionEn(translate.getNameEn());
                    event.setDescriptionFra(translate.getNameFra());
                    event.setDescriptionSpa(translate.getNameSpa());
                    event.setDescriptionDe(translate.getNameDe());
                    event.setDescriptionPl(translate.getNamePl());
                    event.setDescriptionAra(translate.getNameAra());
                }

                Event eventLast = null;
                deviceTransfer = (DeviceTransfer)hgetall.get(k);
                if (null != deviceTransfer) {
                    Long eventId = deviceTransfer.getEventId();
                    Integer isRecovery = deviceTransfer.getIsRecovery();
                    if (null != isRecovery && null != eventId) {
                        eventLast = new Event();
                        eventLast.setIsRecovery(isRecovery);
                        eventLast.setId(eventId);
                    }
                }

                needSave = true;
                long id;
                if (CommonConstant.ONE.equals(event.getIsRecovery())) {
                    if (null != eventLast && !CommonConstant.ONE.equals(eventLast.getIsRecovery())) {
                        id = this.snowflake.nextId();
                        log.info("new recovery event snowflake id: {},event_level:{},alarmStationId:{},targetDevice:{},deviceType:{},signal:{}", new Object[]{id, event.getEventLevel(), eventAddReq.getStationId(), eventAddReq.getSrcId(), eventAddReq.getDeviceType(), k});
                        event.setId(id);
                        event.setSignal(k);
                        event.setBeforeEventId(eventLast.getId());
                        this.generateAlarm(eventAddReq, v, event);
                        log.info("new recovery event update redis before:{},redisKey:{},k:{}", new Object[]{this.redisService.hget(redisKey, k), redisKey, k});
                        deviceTransfer.setEventId(event.getId());
                        deviceTransfer.setIsRecovery(event.getIsRecovery());
                        this.redisService.hset(redisKey, k, deviceTransfer);
                        log.info("new recovery event update redis after:{},redisKey:{},k:{}", new Object[]{this.redisService.hget(redisKey, k), redisKey, k});
                        Event conformEvent = new Event();
                        conformEvent.setConfirmMan("system");
                        conformEvent.setConfirmTime(date);
                        conformEvent.setId(eventLast.getId());
                        conformEvent.setStatus(CommonConstant.ONE);
                        this.eventMapper.updateByPrimaryKeySelective(conformEvent);
                    }
                } else if (CommonConstant.ZERO.equals(event.getIsRecovery())) {
                    if (eventLast != null && CommonConstant.ZERO.equals(eventLast.getIsRecovery())) {
                        eventLast.setValue(new BigDecimal(String.valueOf(v)));
                        eventLast.setDescription(event.getDescription());
                        TranslateName translate = eventService.getNameLanguage(event.getDescription());
                        eventLast.setDescriptionEn(translate.getNameEn());
                        eventLast.setDescriptionFra(translate.getNameFra());
                        eventLast.setDescriptionSpa(translate.getNameSpa());
                        eventLast.setDescriptionDe(translate.getNameDe());
                        eventLast.setDescriptionPl(translate.getNamePl());
                        eventLast.setDescriptionAra(translate.getNameAra());
                        this.eventMapper.updateBatchById(eventLast);
                    } else {
                        id = this.snowflake.nextId();
                        log.info("new error event snowflake id: {},event_level:{},alarmStationId:{},targetDevice:{},deviceType:{},signal:{}", new Object[]{id, event.getEventLevel(), eventAddReq.getStationId(), eventAddReq.getSrcId(), eventAddReq.getDeviceType(), k});
                        event.setId(id);
                        event.setSignal(k);
                        this.generateAlarm(eventAddReq, v, event);
                        log.info("new error event update redis before:{},redisKey:{},k:{}", new Object[]{this.redisService.hget(redisKey, k), redisKey, k});
                        deviceTransfer.setEventId(event.getId());
                        deviceTransfer.setIsRecovery(event.getIsRecovery());
                        this.redisService.hset(redisKey, k, deviceTransfer);
                        log.info("new error event update redis after:{},redisKey:{},k:{}", new Object[]{this.redisService.hget(redisKey, k), redisKey, k});
                    }
                }
            }
        }
    }

    private void generateAlarm(EventAddReq eventAddReq, Object v, Event event) {
        event.setGroupId(eventAddReq.getGroupId());
        event.setStationId(eventAddReq.getStationId());
        event.setEventType(CommonConstant.EventType.alarm);
        event.setTimeStamp(eventAddReq.getTs());
        event.setTargetDevice(eventAddReq.getSrcId());
        event.setDeviceType(eventAddReq.getDeviceType());
        event.setDeviceTypeId(eventAddReq.getDeviceTypeId());
        event.setStatus(CommonConstant.ZERO);
        if (CommonConstant.EventLevel.notice.equals(event.getEventLevel()) || CommonConstant.EventLevel.statusChange.equals(event.getEventLevel()) || CommonConstant.ONE.equals(event.getIsRecovery())) {
            event.setStatus(CommonConstant.ONE);
            event.setConfirmTime(new Date());
            event.setConfirmMan("system");
        }

        event.setValue(new BigDecimal(String.valueOf(v)));
        Date now = new Date();
        event.setCreateTime(new Date());
        event.setUpdateTime(now);
        this.eventMapper.insert(event);
    }

    public Boolean isRecoveryDevice(AlarmConfigQueryVo alarmConfigQueryVo) {
        if (null == alarmConfigQueryVo.getStartTime() || null == alarmConfigQueryVo.getEndTime()) {
            alarmConfigQueryVo.setStartTime(DateUtil.format(DateUtil.offsetDay(new Date(), -10), "yyyy-MM-dd"));
            alarmConfigQueryVo.setEndTime(DateUtil.format(DateUtil.tomorrow(), "yyyy-MM-dd"));
        }

        List<Event> eventsList = this.eventMapper.selectByTargetDevice(alarmConfigQueryVo);
        log.info("isRecoveryDevice. eventsList.size: {} ", eventsList.size());
        Map<String, List<Event>> eventList = (Map)eventsList.stream().collect(Collectors.groupingBy(Event::getSignal));
        log.info("isRecoveryDevice. eventList.size: {} ", eventList.size());
        return this.isNormal(eventList);
    }

    private boolean isNormal(Map<String, List<Event>> eventList) {
        boolean flag = true;
        List<Event> events = null;
        int eventNum = 0;
        int num = 0;
        Iterator var6 = eventList.entrySet().iterator();

        while(var6.hasNext()) {
            Map.Entry<String, List<Event>> map = (Map.Entry)var6.next();
            events = (List)map.getValue();
            if (null != events && events.size() > 0) {
                ++eventNum;
                if (CommonConstant.ONE.equals(((Event)events.get(0)).getIsRecovery())) {
                    ++num;
                }
            }
        }

        log.info("isRecoveryDevice. eventNum: {} ,num:{}", eventNum, num);
        if (num < eventNum) {
            flag = false;
        }

        return flag;
    }

    public List<StationStatusRespVO> isNormalStation(AlarmConfigQueryVo alarmConfigQueryVo) {
        List<StationStatusRespVO> resultList = new ArrayList();
        if (null == alarmConfigQueryVo.getStartTime() || null == alarmConfigQueryVo.getEndTime()) {
            alarmConfigQueryVo.setStartTime(DateUtil.format(DateUtil.offsetDay(new Date(), -10), "yyyy-MM-dd"));
            alarmConfigQueryVo.setEndTime(DateUtil.format(DateUtil.tomorrow(), "yyyy-MM-dd"));
        }

        List<Event> eventsList = this.eventMapper.selectByTargetDevice(alarmConfigQueryVo);
        Map<Integer, Boolean> stationStatusMap = new HashMap();
        Map<Integer, List<Event>> stationEventMap = (Map)eventsList.stream().collect(Collectors.groupingBy(Event::getStationId));
        Iterator var6 = stationEventMap.entrySet().iterator();

        List<Event> stationStatusRespVO;
        while(var6.hasNext()) {
            Map.Entry<Integer, List<Event>> map = (Map.Entry)var6.next();
            stationStatusRespVO = map.getValue();
            Map<String, List<Event>> deviceSignalEventMap = (Map)stationStatusRespVO.stream().collect(Collectors.groupingBy((s) -> {
                return s.getTargetDevice() + "_" + s.getSignal();
            }));
            stationStatusMap.put(map.getKey(), this.isNormal(deviceSignalEventMap));
        }

        DataResult<List<Station>> dataResult = this.businessFeignClient.selectByGroupId(alarmConfigQueryVo.getGroupId());
        List<Station> stationList = (List)dataResult.getData();
        stationStatusRespVO = null;
        boolean stationStatus = true;
        Iterator var10 = stationList.iterator();

        while(var10.hasNext()) {
            Station station = (Station)var10.next();
            StationStatusRespVO vo = new StationStatusRespVO();
            vo.setStationId(station.getId());
            stationStatus = stationStatusMap.get(station.getId()) == null || (Boolean)stationStatusMap.get(station.getId());
            vo.setStationStatus(stationStatus);
            resultList.add(vo);
        }

        return resultList;
    }

    public void polymerizationAlarm(EventAddReq eventAddReq, List<AlarmConfig> groupAlarmConfigs, List<AlarmConfig> stationAlarmConfigs) {
        String redisKey = eventAddReq.getDeviceType() + ":" + eventAddReq.getStationId() + ":" + eventAddReq.getSrcId();
        Map<Object, Object> hgetall = this.redisService.hgetall(redisKey);
        Map<String, AlarmConfig> groupMapOne = groupAlarmConfigs == null ? new HashMap() : (Map)groupAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.ONE.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Map<String, AlarmConfig> stationMapOne = stationAlarmConfigs == null ? new HashMap() : (Map)stationAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.ONE.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Map<String, AlarmConfig> groupMapTwo = groupAlarmConfigs == null ? new HashMap() : (Map)groupAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.TWO.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Map<String, AlarmConfig> stationMapTwo = stationAlarmConfigs == null ? new HashMap() : (Map)stationAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.TWO.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Map<String, AlarmConfig> groupMapThree = groupAlarmConfigs == null ? new HashMap() : (Map)groupAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.THREE.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Map<String, AlarmConfig> stationMapThree = stationAlarmConfigs == null ? new HashMap() : (Map)stationAlarmConfigs.stream().filter((i) -> {
            return i.getAlarmLevel() != null && CommonConstant.THREE.equals(i.getAlarmLevel());
        }).collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
            return AlarmConfig;
        }));
        Event vo = new Event();
        vo.setStationId(eventAddReq.getStationId());
        vo.setTargetDevice(eventAddReq.getSrcId());
        vo.setSignal("polymerization");
        vo.setEventLevel(CommonConstant.ONE);
        if (((Map)stationMapOne).size() != 0 || ((Map)groupMapOne).size() != 0) {
            this.commonPolymerizationAlarm(eventAddReq, (Map)stationMapOne, (Map)groupMapOne, hgetall, vo);
        }

        vo.setEventLevel(CommonConstant.TWO);
        if (((Map)stationMapTwo).size() != 0 || ((Map)groupMapTwo).size() != 0) {
            this.commonPolymerizationAlarm(eventAddReq, (Map)stationMapTwo, (Map)groupMapTwo, hgetall, vo);
        }

        vo.setEventLevel(CommonConstant.THREE);
        if (((Map)stationMapThree).size() != 0 || ((Map)groupMapThree).size() != 0) {
            this.commonPolymerizationAlarm(eventAddReq, (Map)stationMapThree, (Map)groupMapThree, hgetall, vo);
        }

    }

    private void commonPolymerizationAlarm(EventAddReq eventAddReq, Map<String, AlarmConfig> stationMap, Map<String, AlarmConfig> groupMap, Map<Object, Object> hgetall, Event vo) {
        boolean isError = false;
        Event event = new Event();
        isError = this.isError(stationMap, hgetall, isError, event, eventAddReq);
        if (!isError && groupMap.size() > 0) {
            isError = this.isError(groupMap, hgetall, isError, event, eventAddReq);
        }

        String redisKey = "polymerization:" + vo.getStationId() + ":" + vo.getTargetDevice();
        DeviceTransfer eventLast = (DeviceTransfer)this.redisService.hget(redisKey, vo.getEventLevel().toString());
        Integer level = vo.getEventLevel();
        event.setEventLevel(level);
        long eventId;
        if (null != eventLast) {
            if (CommonConstant.ONE.equals(eventLast.getIsRecovery()) && isError) {
                event.setStatus(CommonConstant.ZERO);
                eventId = this.insertNewEvent(eventAddReq, CommonConstant.ZERO, event);
                this.updatePolymerization(redisKey, eventLast, vo.getEventLevel(), CommonConstant.ZERO, eventId);
                if (!CommonConstant.THREE.equals(level)) {
                    this.sendSms(eventAddReq.getStationId(), event.getDescription(), level);
                    this.sendWorkOrder(event);
                }
            } else if (CommonConstant.ZERO.equals(eventLast.getIsRecovery()) && !isError) {
                List<Long> ids = new ArrayList();
                ids.add(eventLast.getEventId());
                UserDetailRespVO userDetail = new UserDetailRespVO();
                userDetail.setUsername("system");
                this.eventMapper.updateByIds(ids, userDetail);
                event.setBeforeEventId(eventLast.getEventId());
                event.setConfirmMan("system");
                event.setStatus(CommonConstant.ONE);
                event.setConfirmTime(new Date());
                eventId = this.insertNewEvent(eventAddReq, CommonConstant.ONE, event);
                this.updatePolymerization(redisKey, eventLast, vo.getEventLevel(), CommonConstant.ONE, eventId);
            }
        } else if (isError) {
            event.setStatus(CommonConstant.ZERO);
            eventId = this.insertNewEvent(eventAddReq, CommonConstant.ZERO, event);
            eventLast = new DeviceTransfer();
            this.updatePolymerization(redisKey, eventLast, vo.getEventLevel(), CommonConstant.ZERO, eventId);
            if (!CommonConstant.THREE.equals(level)) {
                this.sendSms(eventAddReq.getStationId(), event.getDescription(), level);
                this.sendWorkOrder(event);
            }
        }

    }

    private void updatePolymerization(String redisKey, DeviceTransfer eventLast, Integer level, Integer recovery, long eventId) {
        eventLast.setEventId(eventId);
        eventLast.setIsRecovery(recovery);
        eventLast.setUpdateTime(new Date());
        this.redisService.hset(redisKey, level.toString(), eventLast);
        log.info("updatePolymerization redis:{},{},{}", new Object[]{redisKey, level.toString(), eventLast});
    }

    private void sendWorkOrder(Event event) {
        MovementDTO movementDTO = new MovementDTO();
        List<Event> events = new ArrayList();
        events.add(event);
        movementDTO.setEvents(events);
        this.monitor.setEvents(movementDTO);
    }

    private long insertNewEvent(EventAddReq eventAddReq, Integer recoveryStatus, Event event) {
        long id = this.snowflake.nextId();
        event.setId(id);
        event.setGroupId(eventAddReq.getGroupId());
        event.setStationId(eventAddReq.getStationId());
        event.setEventType(CommonConstant.EventType.alarm);
        event.setTimeStamp(eventAddReq.getTs());
        event.setTargetDevice(eventAddReq.getSrcId());
        event.setDeviceType(eventAddReq.getDeviceType());
        event.setDeviceTypeId(eventAddReq.getDeviceTypeId());
        event.setSignal("polymerization");
        event.setIsRecovery(recoveryStatus);
        event.setCreateTime(new Date());
        List<Event> list = new ArrayList();
        list.add(event);
        this.eventMapper.insertBatch(list);
        return id;
    }

    private boolean isError(Map<String, AlarmConfig> alarmMap, Map<Object, Object> hgetall, boolean isError, Event event, EventAddReq eventAddReq) {
        String deviceName = eventAddReq.getDeviceName();
        Iterator var9 = alarmMap.entrySet().iterator();

        while(var9.hasNext()) {
            Map.Entry<String, AlarmConfig> entry = (Map.Entry)var9.next();
            String k = (String)entry.getKey();
            Object obj = hgetall.get(k);
            AlarmConfig alarmConfig = (AlarmConfig)entry.getValue();
            if (obj != null) {
                if (CommonConstant.EventSignal.SIGNAL.equals(alarmConfig.getSensType())) {
                    int value;
                    if (obj instanceof DeviceTransfer) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer)obj;
                        value = deviceTransfer.getValue().intValue();
                    } else {
                        value = Integer.parseInt(String.valueOf(obj));
                    }

                    if (eventAddReq.getDeviceType().contains("communicationStatus")) {
                        if (!CommonConstant.ONE.equals(value)) {
                            isError = true;
                            break;
                        }
                    } else if ("communicationStatus".equals(k)) {
                        if (CommonConstant.ZERO.equals(value)) {
                            isError = true;
                            break;
                        }
                    } else if (value > CommonConstant.ZERO) {
                        isError = true;
                        break;
                    }
                } else if (CommonConstant.EventSignal.TELEMETER.equals(alarmConfig.getSensType())) {
                    BigDecimal lowerLimit = alarmConfig.getLowerLimit();
                    BigDecimal upperLimit = alarmConfig.getUpperLimit();
                    DeviceTransfer deviceTransfer = (DeviceTransfer)obj;
                    BigDecimal value = deviceTransfer.getValue();
                    if (upperLimit != null && value.compareTo(upperLimit) > 0) {
                        isError = true;
                        break;
                    }

                    if (lowerLimit != null && value.compareTo(lowerLimit) < 0) {
                        isError = true;
                        break;
                    }
                }

                event.setEventLevel(alarmConfig.getAlarmLevel());
            }
        }
        String description = deviceName + "设备告警恢复";
        if (isError) {
            description = deviceName + "设备告警";
        }
        event.setDescription(description);
        TranslateName translate = eventService.getNameLanguage(description);
        event.setDescriptionEn(translate.getNameEn());
        event.setDescriptionFra(translate.getNameFra());
        event.setDescriptionSpa(translate.getNameSpa());
        event.setDescriptionDe(translate.getNameDe());
        event.setDescriptionPl(translate.getNamePl());
        event.setDescriptionAra(translate.getNameAra());

        return isError;
    }

    private void sendSms(Integer stationId, String content, Integer level) {
        SendSmsConfigQueryReq vo = new SendSmsConfigQueryReq();
        vo.setStationId(stationId);
        vo.setSmsType(CommonConstant.ONE);
        vo.setAlarmLevel(String.valueOf(level));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("siteName", this.getStationName(stationId));
        jsonObject.put("content", content);
        vo.setParam(jsonObject);
        this.sendSmsConfigService.sendSms(vo);
    }

    private String getStationName(Integer stationId) {
        String name = "";
        String key = "station:" + stationId;
        Station station = null;
        if (this.redisService.hasKey(key)) {
            station = (Station)this.redisService.get(key);
        } else {
            DataResult<Station> result = this.businessFeignClient.selectByStationId(stationId);
            station = (Station)result.getData();
        }

        if (null != station) {
            name = station.getName();
        }

        return name;
    }

    public Event getNotRecovered(AlarmConfigQueryVo stationStatusReq) {
        AlarmConfigQueryVo alarmConfigQueryVo = new AlarmConfigQueryVo();
        alarmConfigQueryVo.setStationId(stationStatusReq.getStationId());
        Event event = this.eventMapper.selectLastTime(alarmConfigQueryVo);
        return event;
    }

    public EventTypeAndLevelsReqVO getAlarmDataStatistics(AlarmConfigQueryVo vo) {
        String alarmNum = null;
        String alarmUnresolvedNum = null;
        EventTypeAndLevelsReqVO eventTypeAndLevelsReqVO = new EventTypeAndLevelsReqVO();
        if (!vo.getStationList().isEmpty() && vo.getStationId() == null) {
            Iterator var5 = vo.getStationList().iterator();

            while(var5.hasNext()) {
                Station station = (Station)var5.next();
                AlarmConfigQueryVo alarmConfigQueryVo = new AlarmConfigQueryVo();
                if (null == vo.getStartTime() && null == vo.getStartTime()) {
                    DateTime yesterday = DateUtil.yesterday();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String begin = sdf.format(DateUtil.beginOfDay(yesterday));
                    String endOfDay = sdf.format(DateUtil.endOfDay(yesterday));
                    alarmConfigQueryVo.setStartTime(begin);
                    alarmConfigQueryVo.setEndTime(endOfDay);
                } else {
                    alarmConfigQueryVo.setStartTime(vo.getStartTime());
                    alarmConfigQueryVo.setEndTime(vo.getEndTime());
                }

                List<Integer> list = new ArrayList();
                list.add(CommonConstant.EventLevel.accident);
                list.add(CommonConstant.EventLevel.abnormal);
                list.add(CommonConstant.EventLevel.overLimit);
                alarmConfigQueryVo.setStationId(station.getId());
                alarmConfigQueryVo.setEventLevelList(list);
                List<Event> events = this.eventMapper.selectByTargetDeviceAsc(alarmConfigQueryVo);
                List<Event> recovered = new ArrayList();
                List<Event> notRecovered = new ArrayList();
                Integer alarmOccurrencesNumber = 0;
                Integer alarmUnresolvedNumber = 0;
                Iterator var14 = events.iterator();

                Event event;
                while(var14.hasNext()) {
                    event = (Event)var14.next();
                    if (CommonConstant.ZERO.equals(event.getIsRecovery())) {
                        alarmOccurrencesNumber = alarmOccurrencesNumber + 1;
                        notRecovered.add(event);
                    }

                    if (CommonConstant.ONE.equals(event.getIsRecovery())) {
                        recovered.add(event);
                    }
                }

                var14 = notRecovered.iterator();

                while(var14.hasNext()) {
                    event = (Event)var14.next();
                    Event beforeEventId = this.eventMapper.selectByBeforeEventId(event.getId());
                    if (null == beforeEventId) {
                        alarmUnresolvedNumber = alarmUnresolvedNumber + 1;
                    }
                }

                eventTypeAndLevelsReqVO.setAlarmOccurrencesNumber(alarmOccurrencesNumber);
                eventTypeAndLevelsReqVO.setAlarmUnresolvedNumber(alarmUnresolvedNumber);
                alarmNum = alarmOccurrencesNumber.toString();
                alarmUnresolvedNum = alarmUnresolvedNumber.toString();
                String redisKey = "dmaintenance:" + station.getId();
                JSONObject modifyDataObject = new JSONObject();
                modifyDataObject.put("alarmNum", alarmNum);
                modifyDataObject.put("alarmUnresolvedNum", alarmUnresolvedNum);
                String format = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
                modifyDataObject.put("updateTime", format);
                this.redisService.hmset(redisKey, modifyDataObject);
                log.info("elecMeter.insert OK");
            }
        }

        return eventTypeAndLevelsReqVO;
    }

    @Async("flowThreadPoolExecutor")
    public DataResult addEvents(List<EventAddReq> list) {
        Iterator var2 = list.iterator();

        while(var2.hasNext()) {
            EventAddReq eventAddReq = (EventAddReq)var2.next();
            List<AlarmConfig> groupAlarmConfigs = this.alarmConfigService.selectListGroupCache(eventAddReq.getGroupId(), com.ho.flow.constant.FlowConstant.AlarmConfig.SCOPE_GROUP, eventAddReq.getDeviceType());
            List<AlarmConfig> stationAlarmConfigs = this.alarmConfigService.selectListCompanyCache(eventAddReq.getGroupId(), eventAddReq.getStationId(), com.ho.flow.constant.FlowConstant.AlarmConfig.SCOPE_STATION, eventAddReq.getDeviceType());
            Map<String, AlarmConfig> stationConfigMap = (Map)stationAlarmConfigs.stream().collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
                return AlarmConfig;
            }));
            Map<String, AlarmConfig> groupConfigMap = (Map)groupAlarmConfigs.stream().collect(Collectors.toMap(AlarmConfig::getCol, (AlarmConfig) -> {
                return AlarmConfig;
            }));
            JSONObject dataSet = eventAddReq.getDataSet();
            if (dataSet == null) {
                return DataResult.success();
            }

            this.polymerizationAlarm(eventAddReq, groupAlarmConfigs, stationAlarmConfigs);
            Map<String, List<Event>> resultMap = this.matchEventRecords(eventAddReq, dataSet, stationConfigMap, groupConfigMap);

            try {
                List<Event> events = (List)resultMap.get("events");
                if (events != null && !events.isEmpty()) {
                    log.info("电站id：{},设备id：{}, events. size: {} ", new Object[]{eventAddReq.getStationId(), eventAddReq.getSrcId(), events.size()});
                    this.eventService.insertEventBatch(events);
                    MovementDTO movementDTO = new MovementDTO();
                    movementDTO.setEvents(events);
                    if (this.flag == 1) {
                        this.monitor.setEvents(movementDTO);
                    }
                }

                List<Event> updateEvents = (List)resultMap.get("updateEvents");
                if (updateEvents != null && !updateEvents.isEmpty()) {
                    log.info("电站id：{},设备id：{}, updateEvents. size: {} ", new Object[]{eventAddReq.getStationId(), eventAddReq.getSrcId(), updateEvents.size()});
                    this.eventService.updateEventBatch(updateEvents);
                }

                List<Event> updateEventStatus = (List)resultMap.get("updateEventStatus");
                if (updateEventStatus != null && !updateEventStatus.isEmpty()) {
                    log.info("电站id：{},设备id：{}, updateEventStatus. size: {} ", new Object[]{eventAddReq.getStationId(), eventAddReq.getSrcId(), updateEventStatus.size()});
                    List<Long> ids = (List)updateEventStatus.stream().map(Event::getId).collect(Collectors.toList());
                    UserDetailRespVO userDetailRespVO = new UserDetailRespVO();
                    userDetailRespVO.setUsername("system");
                    this.eventService.updateById(ids, userDetailRespVO);
                }
            } catch (Exception var15) {
                log.error("新增告警入库异常,电站id：{},设备id：{},dataSet:{},异常信息：{}", new Object[]{eventAddReq.getStationId(), eventAddReq.getSrcId(), eventAddReq.getDataSet(), var15.getMessage()});
            }
        }

        return DataResult.success();
    }
}
