# HistoryAndForecastForEndOfShiftReportListener.java

    package cloud.wconnect.frontoffice.messagelistener.endofshift;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.exception.ListenerException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.KeyPrefixEnum;
    import cloud.wconnect.frontoffice.parsereport.endofshift.IHistoryAndForecastService;
    import cloud.wconnect.frontoffice.pojo.dto.endofshift.report.HistoryAndForecastForEndOfShiftReportDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.endofshift.IShiftReportInfoService;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;

    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * History And Forecast for End of Shift Report 事件处理
     *
     * @author zc
     * @date 2023/2/8
     */
    @Slf4j
    @Service
    public class HistoryAndForecastForEndOfShiftReportListener {
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private IShiftReportInfoService shiftReportInfoService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Resource
        private CommonService commonService;

        /**
         * subject
         */
        private final String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject();

        /**
         * 业务名称
         */
        private final String BUSINESS = BusinessEnum.END_OF_SHIFT_REPORT.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2023/2/9
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) throws Exception {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("HistoryAndForecastForEndOfShiftReportListener.start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.handle end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);

            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());

            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantSymbol);
            if (Objects.isNull(property)) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.handle end... The property is not exist; abbr name: {}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.handle end...  The property is closed; abbr name: {}", propertyAbbrName);
                return;
            }

            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if (!property.getPmsType().equals(source)) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        property.getId(), property.getPmsType(), source);
                return;
            }

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.END_OF_SHIFT)) {
                log.warn("HistoryAndForecastForEndOfShiftReportListener.end... the property has not opened the end of shift function;property:{}", propertyAbbrName);
                return;
            }

            try (InputStream in = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                // 将报告中的数据映射为 History And Forecast 实体类
                HistoryAndForecastForEndOfShiftReportDTO historyAndForecast = parseReport(in, source, property);
                if (Objects.isNull(historyAndForecast)) {
                    log.warn("HistoryAndForecastForEndOfShiftReportListener.handle end... The report data is empty");
                    return;
                }

                // 更新History And Forecast 数据
                shiftReportInfoService.updateHistoryAndForecastData(property, historyAndForecast);

                // 每次有效处理后，将【最近处理时刻】保存在 redis 中
                updateLastTime(propertyAbbrName);

                log.info("HistoryAndForecastForEndOfShiftReportListener.handle end...");
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("HistoryAndForecastForEndOfShiftReportListener.handle end... Process error.", e);
            }
        }

        /**
         * 解析报告
         *
         * @param in       文件
         * @param source   数据源平台
         * @param property 资产
         * @return HistoryAndForecastForEndOfShiftReportDTO
         * @author zc
         * @date 2023/6/1
         */
        private HistoryAndForecastForEndOfShiftReportDTO parseReport(InputStream in, String source, PropertyDTO property) {
            Map<String, IHistoryAndForecastService> beansOfType = applicationContext.getBeansOfType(IHistoryAndForecastService.class);
            Collection<IHistoryAndForecastService> parsers = beansOfType.values();
            for (IHistoryAndForecastService parser : parsers) {
                if (parser.supports(source)) {
                    return parser.parse(in, property);
                }
            }
            throw new ListenerException("HistoryAndForecastForEndOfShiftReportListener not find report parser");
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle History And Forecast Exception";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/6/1
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    KeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author zc
         * @date 2023/6/1
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            redisTemplate.opsForValue().set(
                    KeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }
    }