# RevenueHistoryAndForecastYesterdayAndNinetyListener.java

    package cloud.wconnect.rateshop.messagelistener.revenue;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.exception.ListenerException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    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.KeyPrefixEnum;
    import cloud.wconnect.rateshop.cons.S3BucketFunctionCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueImportCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueDailySummary;
    import cloud.wconnect.rateshop.entity.revenue.RevenueImportLog;
    import cloud.wconnect.rateshop.pojo.bo.revenue.DailySummaryBO;
    import cloud.wconnect.rateshop.pojo.bo.revenue.HistoryAndForecastOccJumpAlertBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastDailySummaryDTO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.revenue.IOccForecastService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueImportLogService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueSchedulerJobService;
    import cloud.wconnect.rateshop.service.revenue.historyandforecast.IDailySummaryHistoryAndForecastParse;
    import cloud.wconnect.rateshop.service.revenue.historyandforecast.IOccJumpAlertHistoryAndForecastParseService;
    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.CollectionUtils;
    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.Component;

    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZonedDateTime;
    import java.util.*;
    import java.util.concurrent.TimeUnit;

    /**
     * Revenue功能History And Forecast -1,90 报告处理
     *
     * @author lichen
     * @date 2024/3/25
     */
    @Slf4j
    @Component
    public class RevenueHistoryAndForecastYesterdayAndNinetyListener {

        @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 IRevenueImportLogService revenueImportLogService;
        @Autowired
        private IRevenueSchedulerJobService schedulerJobService;
        @Autowired
        private IRevenueDailySummaryService revenueDailySummaryService;
        @Autowired
        private IOccForecastService occForecastService;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private CommonService commonService;
        /**
         * subject
         */
        private final String SUBJECT = EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_YESTERDAY_NINETY_DAY.getSubject();
        /**
         * 业务名称
         */
        private final String BUSINESS = BusinessEnum.REVENUE.getBusiness();

        /**
         * 处理报告监听器
         *
         * @param event 事件对象
         * @return void
         * @author lichen
         * @date 2024/3/26
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("Revenue Process HistoryAndForecast.start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("Revenue Process HistoryAndForecast.end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("Revenue Process HistoryAndForecast.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 propertyAbbr = abbrNameList.get(0);
            //获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            PropertyDTO propertyDTO = getEffectiveProperty(tenantSymbol, propertyAbbr);
            if (Objects.isNull(propertyDTO)) {
                return;
            }

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

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

            String timezone = propertyDTO.getTimezone();
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            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("RevenueHistoryAndForecastYesterdayAndNinetyListener.handle end... The dateRange is empty, property:{}", propertyAbbr);
                return;
            }
            boolean importResult = true;
            try (InputStream fileInputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                //上传文件到功能对应的桶中
                amazonS3Service.uploadFile(S3BucketFunctionCons.REVENUE_IMPORT_RECORD, fileInputStream, eventBodyDTO.getPath());

                //报告中的数据
                List<HistoryAndForecastDailySummaryDTO> historyAndForecastDailySummaryDTOS = parseReport(eventBodyDTO, propertyDTO, dateRange.get(JobParameterDTO.START_DATE),
                        dateRange.get(JobParameterDTO.END_DATE), parser);
                //过滤和转化数据
                List<DailySummaryBO> dailySummaryBOList = filterAndTransform(propertyDTO, uid, logId, historyAndForecastDailySummaryDTOS);
                //保存Daily Summary数据
                if (CollectionUtils.isNotEmpty(dailySummaryBOList)) {
                    revenueDailySummaryService.saveOrUpdate(propertyDTO, dailySummaryBOList);
                }

                /*
                 * uid==0,表示自动导入，只有自动导入时，才处理occ forecast数据
                 * 因为手动导入时，【导入的时刻】和【PMS平台生成报告的时刻】可能不一致
                 */
                if (uid == 0) {
                    // 处理 occ forecast
                    List<HistoryAndForecastOccJumpAlertBO> occJumpAlertBOList = parseReportForOccJumpAlert(eventBodyDTO, propertyDTO,
                            dateRange.get(JobParameterDTO.START_DATE), dateRange.get(JobParameterDTO.END_DATE));
                    occForecastService.saveOccForecast(propertyDTO, uid, occJumpAlertBOList);
                }
                log.info("Revenue Process HistoryAndForecast.end...");
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("Revenue Process HistoryAndForecast.end... Process error.", e);
            } finally {
                if (uid == 0) {
                    updateLastTime(propertyAbbr);
                }

                if (Objects.isNull(logId)) {
                    // 生成导入记录
                    revenueImportLogService.handleSaveSystemImportRecord(propertyDTO, RevenueImportCons.HISTORY_AND_FORECAST_YESTERDAY_AND_NEXT_NINETY_DAYS,
                            DateTimeUtils.localDateToLong(BusinessDateUtil.getBusinessDate(timezone), timezone), dateRange.get(JobParameterDTO.START_DATE), dateRange.get(JobParameterDTO.END_DATE),
                            importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL, eventBodyDTO.getPath());
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        revenueImportLogService.updateLogStatus(logId, importResult, eventBodyDTO.getPath(), uid);
                    } else {
                        // 生成导入记录
                        ZonedDateTime dateNow = DateTimeUtils.dateNow(propertyDTO.getTimezone());
                        revenueImportLogService.handleSaveSystemImportRecord(propertyDTO, RevenueImportCons.HISTORY_AND_FORECAST_YESTERDAY_AND_NEXT_NINETY_DAYS,
                                dateNow.toEpochSecond(), dateRange.get(JobParameterDTO.START_DATE), dateRange.get(JobParameterDTO.END_DATE),
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL, eventBodyDTO.getPath());
                    }
                }
            }
        }

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

        /**
         * 过滤和转化数据
         *
         * @param propertyDTO                        资产DTO
         * @param uid                                用户ID
         * @param logId                              日志id
         * @param historyAndForecastDailySummaryDTOS 数据
         * @return java.util.List<cloud.wconnect.rateshop.pojo.bo.revenue.DailySummaryBO>
         * @author lichen
         * @date 2025/11/19
         */
        private List<DailySummaryBO> filterAndTransform(PropertyDTO propertyDTO, Integer uid, Long logId,
                                                        List<HistoryAndForecastDailySummaryDTO> historyAndForecastDailySummaryDTOS) {
            if (CollectionUtils.isEmpty(historyAndForecastDailySummaryDTOS)) {
                return Collections.emptyList();
            }

            String timezone = propertyDTO.getTimezone();
            ZonedDateTime zonedDateTime = DateTimeUtils.dateNow(timezone);
            //当天
            long currentDate = zonedDateTime.toEpochSecond();
            //前一天
            long yesterdayLong = zonedDateTime.minusDays(1).toEpochSecond();
            //转化为BO
            List<DailySummaryBO> dailySummaryBOS = beanMapper.mapList(historyAndForecastDailySummaryDTOS, DailySummaryBO.class);

            List<DailySummaryBO> filterList;
            /*
             * 1. uid==0表示自动导入
             *    (1)5:00 AM以后，保存昨天（当前日期-1）的Final时刻、当天数据
             *    (2)5:00 AM以前，保存当天数据
             * 2. uid > 0表示手动导入，保存businessDate-1天的Final时刻
             *    手动导入时，已限制只能导入businessDate-1天的数据，所以只需要把hour设置为final即可
             */
            if (uid == 0) {
                //当前时刻
                int hour = DateTimeUtils.dateTimeNow(timezone).getHour();
                if (hour < 5) {
                    //5:00 AM以前，保存当天数据
                    filterList = dailySummaryBOS.stream().filter(item -> item.getTheDate() == currentDate).toList();
                } else {
                    //5:00 AM以后，保存昨天（当前日期-1）的Final时刻、当天数据
                    filterList = dailySummaryBOS.stream()
                            .filter(item -> item.getTheDate() == yesterdayLong || item.getTheDate() == currentDate)
                            .peek(bo -> {
                                if (bo.getTheDate() == yesterdayLong) {
                                    //把前一天的数据设置成Final
                                    bo.setTheHour(RevenueDailySummary.FINAL_HOUR);
                                }
                            }).toList();
                }
            } else {
                //获取businessDate - 1天
                RevenueImportLog importLog = revenueImportLogService.getById(logId);
                Long businessDate = importLog.getTheDate();
                LocalDate beforeDateOfBusinessDate = DateTimeUtils.longToLocalDate(businessDate, timezone).minusDays(1);
                long beforeDateLong = DateTimeUtils.localDateToLong(beforeDateOfBusinessDate, timezone);

                filterList = dailySummaryBOS.stream()
                        .filter(item -> item.getTheDate() == beforeDateLong)
                        .peek(bo -> bo.setTheHour(RevenueDailySummary.FINAL_HOUR)).toList();
            }
            return filterList;
        }

        /**
         * 解析报告
         *
         * @param eventBodyDTO 事件体
         * @param propertyDTO  资产DTO
         * @param startDate    数据开始日期
         * @param endDate      数据结束日期
         * @param parser       报告解析器
         * @return java.util.List<cloud.wconnect.rateshop.pojo.dto.revenue.HourSummaryDTO>
         * @author lichen
         * @date 2024/3/26
         */
        private List<HistoryAndForecastDailySummaryDTO> parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO,
                                                                    Long startDate, Long endDate,
                                                                    IDailySummaryHistoryAndForecastParse parser) throws ParseReportException {
            try (InputStream inputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                return parser.parse(inputStream, propertyDTO, startDate, endDate);
            } catch (Exception e) {
                throw new ListenerException("parse history and forecast report error", e);
            }
        }

        /**
         * 解析报告 for Occ Jump Alert
         *
         * @param eventBodyDTO 事件体
         * @param propertyDTO  资产DTO
         * @param startDate    数据开始日期
         * @param endDate      数据结束日期
         * @return HistoryAndForecastOccJumpAlertBO 集合
         * @author zc
         * @date 2024/4/17
         */
        private List<HistoryAndForecastOccJumpAlertBO> parseReportForOccJumpAlert(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO, Long startDate, Long endDate) throws ParseReportException {
            String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
            Map<String, IOccJumpAlertHistoryAndForecastParseService> beansOfType = applicationContext.getBeansOfType(IOccJumpAlertHistoryAndForecastParseService.class);
            Collection<IOccJumpAlertHistoryAndForecastParseService> parsers = beansOfType.values();
            for (IOccJumpAlertHistoryAndForecastParseService parser : parsers) {
                if (parser.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                        return parser.parse(inputStream, propertyDTO, startDate, endDate);
                    } catch (Exception e) {
                        throw new ListenerException("parse history and forecast report error", e);
                    }
                }
            }
            throw new ListenerException("Not found report parser");
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/3/26
         */
        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 2024/3/26
         */
        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 2024/3/26
         */
        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)));
        }

        /**
         * 获取报告数据日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param logId       日志 id
         * @return 数据日期范围
         * @author lichen
         * @date 2024/6/1
         */
        private Map<String, Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            // 自动下发
            if (Objects.isNull(logId)) {
                //报告数据日期
                return schedulerJobService.getDateRange(propertyDTO, RevenueImportCons.HISTORY_AND_FORECAST_YESTERDAY_AND_NEXT_NINETY_DAYS);
            }
            // 手动导入
            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 lichen
         * @date 2024/6/1
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("RevenueHistoryAndForecastYesterdayAndNinetyListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("RevenueHistoryAndForecastYesterdayAndNinetyListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.REVENUE)) {
                log.warn("RevenueHistoryAndForecastYesterdayAndNinetyListener.handle end... The property:{} has not opened daily revenue function", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }
    }