# RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.java

    package cloud.wconnect.rateshop.messagelistener.revenue;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.exception.ListenerException;
    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.BusinessDateUtil;
    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.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSchedulerJobService;
    import cloud.wconnect.rateshop.service.revenue.historyandforecast.history.IHFHistoryDataListenerFileParse;
    import cloud.wconnect.rateshop.service.revenue.report.IRevenueReportCommonService;
    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.Component;

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

    /**
     * History and Forecast from thirty days ago to yesterday
     *
     * @author lichen
     * 2025/08/05
     */
    @Slf4j
    @Component
    public class RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private IRevenueImportLogService revenueImportLogService;
        @Resource
        private CommonService commonService;
        @Resource
        private IRevenueSchedulerJobService schedulerJobService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private IRevenueReportCommonService revenueReportCommonService;

        private static final String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_FROM_THIRTY_DAYS_AGO_TO_YESTERDAY.getSubject();

        private static final String BUSINESS = BusinessEnum.REVENUE.getBusiness();

        /**
         * 监听 History and Forecast from thirty days ago to yesterday 报告
         *
         * @author lichen
         * @date 2025/08/05
         */
        @Async
        @EventListener
        public void handleHistoryAndForecastReport(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... event body is blank.");
                return;
            }

            Integer id = null;
            int uid = 0;
            boolean importResult = true;
            Long startDate = null;
            Long endDate = null;

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            String path = eventBodyDTO.getPath();
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            List<String> propertyAbbrNames = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = propertyAbbrNames.get(0);
            String tenantAbbrName = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantAbbrName);
            if (Objects.isNull(property)) {
                log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }
            if (!commonService.checkOpenFunction(property, FunctionIdConstant.REVENUE)) {
                log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... the property has not opened the daily revenue function;property:{}", propertyAbbrName);
                return;
            }
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if (!source.equals(property.getPmsType())) {
                log.info("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... pms is not supported;property:{},propertyPms:{},eventPms:{}", propertyAbbrName, property.getPmsType(), source);
                return;
            }

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

            try {
                uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
                id = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                        Integer.parseInt(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());

                if (Objects.isNull(id)) {
                    //报告数据日期
                    Map<String, Long> dateRange = schedulerJobService.getDateRange(property, RevenueImportCons.HISTORY_AND_FORECAST_FROM_THIRTY_DAYS_AGO_TO_YESTERDAY);
                    startDate = dateRange.get(JobParameterDTO.START_DATE);
                    endDate = dateRange.get(JobParameterDTO.END_DATE);
                } else {
                    Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
                    Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
                    if (Objects.isNull(startDateObj) || Objects.isNull(endDateObj)) {
                        log.warn("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... the date、startDate、endDate is null, no processing required;property:{}", propertyAbbrName);
                        return;
                    }
                    startDate = Long.parseLong(startDateObj.toString());
                    endDate = Long.parseLong(endDateObj.toString());
                }

                revenueReportCommonService.toS3(path);

                 // 处理文件
                 handleReport(property, eventBodyDTO, startDate, endDate, parser, uid);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end... handle import history and forecast last year report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                if (Objects.isNull(id)) {
                    // 生成导入记录
                    String timezone = property.getTimezone();
                    revenueImportLogService.handleSaveSystemImportRecord(property, RevenueImportCons.HISTORY_AND_FORECAST_FROM_THIRTY_DAYS_AGO_TO_YESTERDAY,
                            DateTimeUtils.localDateToLong(BusinessDateUtil.getBusinessDate(timezone), timezone), startDate, endDate,
                            importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL, path);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        revenueImportLogService.updateLogStatus(id, importResult, path, uid);
                    } else {
                        // 生成导入记录
                        ZonedDateTime dateNow = DateTimeUtils.dateNow(property.getTimezone());
                        revenueImportLogService.handleSaveSystemImportRecord(property, RevenueImportCons.HISTORY_AND_FORECAST_FROM_THIRTY_DAYS_AGO_TO_YESTERDAY,
                                dateNow.toEpochSecond(), startDate, endDate,
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL, eventBodyDTO.getPath());
                    }
                }
            }
            log.info("RevenueHistoryAndForecastFromThirtyDaysAgoToYesterdayListener.end...");
        }

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

        /**
         * 处理 History and Forecast from thirty days ago to yesterday 报告
         *
         * @param property     资产
         * @param eventBodyDTO 事件体
         * @param startDate    开始日期
         * @param endDate      结束日期
         * @param parser       报告解析器
         * @author lichen
         * @date 2025/8/5
         */
        private void handleReport(PropertyDTO property, EventBodyDTO eventBodyDTO, Long startDate, Long endDate, IHFHistoryDataListenerFileParse parser, int uid) {
            String path = eventBodyDTO.getPath();
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                 parser.saveReportData(property, parser.parseReport(property, inputStream, startDate, endDate), uid);
            } catch (Exception e) {
                throw new ListenerException("parse history and forecast last year report error", e);
            }
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/11/2
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle History and Forecast from thirty days ago to yesterday Exception";
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, abbrName, content, path);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author yyt
         * @date 2023/11/2
         */
        private void updateLastTime(String abbrName) {
            jsonRedisTemplate.opsForValue().set(EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                            StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return true / false
         * @author yyt
         * @date 2023/11/2
         */
        private Boolean preventConcurrency(String messageId) {
            return jsonRedisTemplate.opsForValue().setIfAbsent(
                    EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                            StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

    }