# HistoryAndForecastListener.java

    package cloud.wconnect.rateshop.messagelistener.rateshop;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    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.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.KeyPrefixEnum;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopNotifyConfigTypeEnum;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopOccForecastService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopSchedulerService;
    import cloud.wconnect.rateshop.service.rateshop.IReportImportLogService;
    import cloud.wconnect.rateshop.service.rateshop.historyandforecast.IRateShopHistoryAndForecastService;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.MapUtils;
    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 报告处理
     */
    @Slf4j
    @Service
    public class HistoryAndForecastListener {

        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private ApplicationContext applicationContext;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private IReportImportLogService reportImportLogService;
        @Autowired
        private IPropertyOperationService propertyOperationService;
        @Autowired
        private IRateShopSchedulerService schedulerService;
        @Autowired
        private IRateShopOccForecastService rateShopOccForecastService;
        @Autowired
        private CommonService commonService;
        /**
         * subject
         */
        private final String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject();
        /**
         * 业务名称
         */
        private final String BUSINESS = BusinessEnum.RATE_SHOP.getBusiness();

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

            // 解析事件体内容
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);

            // 获取有效的资产数据
            PropertyDTO propertyDTO = getEffectiveProperty(tenantSymbol, propertyAbbrName);
            if (Objects.isNull(propertyDTO)) {
                return;
            }

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

            // 获取报告解析器，未配置，则不处理
            IRateShopHistoryAndForecastService reportParser = getHistoryAndForecastPase(source);
            if (Objects.isNull(reportParser)) {
                log.warn("HistoryAndForecastListener.handle end... no parser for this source, property:{}, supportPmsType:{}, currentPmsType:{}", propertyAbbrName,
                        propertyDTO.getPmsType(), source);
                return;
            }

            Long logId = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Long.parseLong(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());

            // 获取数据日期范围
            Map<String, Long> dateRange = getDateRange(propertyDTO, parameter, logId);
            if (MapUtils.isEmpty(dateRange)) {
                log.warn("HistoryAndForecastListener.handle end... date range is empty.");
                return;
            }

            int operatorId = Integer.parseInt(parameter.get(EventBodyParamEnum.UID.getDesc()).toString());
            String path = eventBodyDTO.getPath();

            // 处理是否成功
            boolean handleResult = true;
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                long startDate = dateRange.get(JobParameterDTO.START_DATE);
                long endDate = dateRange.get(JobParameterDTO.END_DATE);
                // 解析报告
                List<HistoryAndForecastForRateShopBO> boList = reportParser.parse(inputStream, propertyDTO, startDate, endDate);

                // 保存数据
                propertyOperationService.saveHistoryAndForecastReportData(propertyDTO, operatorId, boList);
                // 保存occ数据
                rateShopOccForecastService.saveOccForecast(propertyDTO, operatorId, boList);

                log.info("HistoryAndForecastListener.handle end...");
            } catch (Exception e) {
                handleResult = false;
                log.error("HistoryAndForecastListener.handle end... Process error.", e);
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), path);
                }
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (operatorId == 0) {
                    updateLastTime(propertyAbbrName);
                }
                int importResult = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                        ReportImportResultCons.IMPORT_RESULT_FAIL;
                if (Objects.isNull(logId)) {
                    // 生成导入记录
                    reportImportLogService.save(propertyDTO, dateRange, "", importResult,
                            RateShopNotifyConfigTypeEnum.HISTORY_AND_FORECAST_REPORT_MISSED.getType(), 0);
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态，由于报告每小时来一次，频率太高，所以不再保存报告到 S3 服务器了
                        reportImportLogService.updateLog(logId, operatorId, "", handleResult);
                    } else {
                        reportImportLogService.save(propertyDTO, dateRange, "", importResult,
                                RateShopNotifyConfigTypeEnum.HISTORY_AND_FORECAST_REPORT_MISSED.getType(), operatorId);
                    }
                }
            }
        }

        /**
         * 获取报告解析器
         *
         * @param source 报告来源
         * @return 报告解析器
         * @author yyt
         * @date 2026/2/4
         **/
        private IRateShopHistoryAndForecastService getHistoryAndForecastPase(String source) {
            Map<String, IRateShopHistoryAndForecastService> beansOfType = applicationContext.getBeansOfType(IRateShopHistoryAndForecastService.class);
            Collection<IRateShopHistoryAndForecastService> parsers = beansOfType.values();
            for (IRateShopHistoryAndForecastService parser : parsers) {
                if (parser.supports(source)) {
                    return parser;
                }
            }
            return null;
        }

        /**
         * 获取报告数据日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param logId       日志 id
         * @return 数据日期范围
         * @author zc
         * @date 2024/5/2
         */
        private Map<String, Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            // 自动下发
            if (Objects.isNull(logId)) {
                return schedulerService.getDateRange(propertyDTO, RateShopNotifyConfigTypeEnum.HISTORY_AND_FORECAST_REPORT_MISSED.getType());
            }
            // 手动导入
            Map<String, Long> dateRange = Maps.newHashMap();
            Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
            Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
            if (Objects.nonNull(startDateObj) && Objects.nonNull(endDateObj)) {
                dateRange.put(EventBodyParamEnum.START_DATE.getDesc(), Long.parseLong(startDateObj.toString()));
                dateRange.put(EventBodyParamEnum.END_DATE.getDesc(), Long.parseLong(endDateObj.toString()));
            }
            return dateRange;
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author zc
         * @date 2024/4/30
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("HistoryAndForecastListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("HistoryAndForecastListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.RATE_SHOP)) {
                log.warn("HistoryAndForecastListener.handle end... The property:{} has not opened rate shop function", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 发送预警邮件
         *
         * @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 Report error";
            //邮件内容
            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 java.lang.Boolean
         * @author lichen
         * @date 2023/6/15
         */
        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 资产标识
         * @return void
         * @author lichen
         * @date 2023/6/15
         */
        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)));
        }
    }