# WMRevenueReservationForecastListener.java

    package cloud.wconnect.rateshop.messagelistener.weeklymonthlyrevenue.pms;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    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.redis.PropertyBusinessDateRedisService;
    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.S3BucketFunctionCons;
    import cloud.wconnect.rateshop.cons.weeklymonthlyrevenue.MonthlyRevenueImportCategoryCons;
    import cloud.wconnect.rateshop.cons.weeklymonthlyrevenue.MonthlyRevenueReportCategoryEnum;
    import cloud.wconnect.rateshop.cons.weeklymonthlyrevenue.MonthlyRevenueReportDateRangeEnum;
    import cloud.wconnect.rateshop.pojo.bo.weeklymonthlyrevenue.WMRevenueReservationForecastBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.weeklymonthlyrevenue.IWeeklyMonthlyRevenueImportLogService;
    import cloud.wconnect.rateshop.service.weeklymonthlyrevenue.IWeeklyMonthlyRevenueReportService;
    import cloud.wconnect.rateshop.service.weeklymonthlyrevenue.reservationforecast.IWMRevenueReservationForecastParseService;
    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.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    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.IOException;
    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;

    /**
     * 报告处理：reservation-forecast
     *
     * @author zc
     * @date 2024/5/20
     */
    @Slf4j
    @Service
    public class WMRevenueReservationForecastListener {

        @Resource
        private IWeeklyMonthlyRevenueReportService reportService;
        @Resource
        private IWeeklyMonthlyRevenueImportLogService importLogService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private CommonService commonService;
        @Resource
        private PropertyBusinessDateRedisService propertyBusinessDateRedisService;
        @Resource
        private ApplicationContext applicationContext;

        private final String SUBJECT = EventSubjectEnum.RESERVATION_FORECAST_TODAY_ONE_HUNDRED_DAYS.getSubject();
        private final String BUSINESS = BusinessEnum.WEEKLY_MONTHLY_REVENUE.getBusiness();

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

            // 解析事件体内容
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            int operatorId = Integer.parseInt(parameter.get(EventBodyParamEnum.UID.getDesc()).toString());
            if (operatorId != 0) {
                //只处理自动下发的事件
                log.warn("WMRevenueReservationForecastListener.handle end... operatorId is not 0");
                return;
            }

            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbr = abbrNameList.get(0);

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

            // 获取资产 PMS 类型
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());

            // 校验事件 PMS 类型是否与资产配置匹配
            if (!StringUtils.equals(propertyDTO.getPmsType(), source)) {
                log.warn("WMRevenueReservationForecastListener.handle end... Property not support this PMS type, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

            IWMRevenueReservationForecastParseService parser = getReportParser(source);
            if (Objects.isNull(parser)) {
                log.warn("WMRevenueReservationForecastListener.handle end... parser not find, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

            String path = eventBodyDTO.getPath();
            int category = MonthlyRevenueImportCategoryCons.FORECAST;

            // 获取资产业务日期
            Long businessDate = propertyBusinessDateRedisService.getEffectiveBusinessDate(propertyDTO.getId(), propertyDTO.getTimezone());
            if (Objects.isNull(businessDate)) {
                log.error("WMRevenueReservationForecastListener.handle end... property businessDate is null or invalid.");
                // 处理营业日期失效或为空的情况
                handleMissingBusinessDate(propertyDTO, path, category);
                return;
            }

            // 获取数据日期范围
            List<Long> dateRange = reportService.getReportDateRangeByCategory(businessDate, propertyDTO.getTimezone(),
                    MonthlyRevenueReportDateRangeEnum.RESERVATION_FORECAST.getDateRange());
            if (CollectionUtils.isEmpty(dateRange)) {
                log.warn("WMRevenueReservationForecastListener.handle end... date range is empty.");
                return;
            }

            // 处理是否成功
            boolean handleResult = true;
            try (InputStream in = amazonS3Service.getFile(path)) {
                // 解析报告
                List<WMRevenueReservationForecastBO> boList = reportService.parseReservationForecastReport(propertyDTO, in, source, dateRange);
                // 处理报告数据
                reportService.handleReservationForecast(propertyDTO, boList, businessDate, operatorId);

                log.info("WMRevenueReservationForecastListener.handle end...");
            } catch (Exception e) {
                handleResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }

                log.error("WMRevenueReservationForecastListener.handle end... Process error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                updateLastTime(propertyAbbr);

                // 上传报告，用于日志下载报告
                uploadReport(path);

                int importResult = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                        ReportImportResultCons.IMPORT_RESULT_FAIL;
                // 生成导入记录
                importLogService.save(propertyDTO, category, businessDate, dateRange, path, importResult,
                        MonthlyRevenueReportCategoryEnum.RESERVATION_FORECAST.getCategory(), 0);
            }
        }

        /**
         * 获取报告解析器
         *
         * @param source 来源
         * @return 解析器
         * @author zc
         * @date 2026/2/7
         */
        private IWMRevenueReservationForecastParseService getReportParser(String source) {
            Collection<IWMRevenueReservationForecastParseService> parserList = applicationContext
                    .getBeansOfType(IWMRevenueReservationForecastParseService.class).values();
            for (IWMRevenueReservationForecastParseService item : parserList) {
                if (item.supports(source)) {
                    return item;
                }
            }
            return null;
        }

        /**
         * 处理营业日期失效或为空的情况
         *
         * @param propertyDTO    资产DTO
         * @param path           s3 文件路径
         * @param importCategory 导入分类
         * @author lichen
         * @date 2025/12/12
         */
        private void handleMissingBusinessDate(PropertyDTO propertyDTO, String path, int importCategory) {
            // 更新报告下发时间
            updateLastTime(propertyDTO.getAbbr());

            // 上传报告，用于日志下载报告
            uploadReport(path);

            // 获取当前时间作为 BusinessDate
            Long businessDate = Long.parseLong(DateTimeUtils.dateNowStr(propertyDTO.getTimezone(), BaseConstant.DATE_FORMAT_YYYYMMDD));

            // 获取数据日期范围
            List<Long> dateRange = reportService.getReportDateRangeByCategory(businessDate, propertyDTO.getTimezone(),
                    MonthlyRevenueReportDateRangeEnum.RESERVATION_FORECAST.getDateRange());

            //插入报告失败记录
            importLogService.save(propertyDTO, importCategory, businessDate,
                    dateRange, path, ReportImportResultCons.IMPORT_RESULT_MISSED,
                    MonthlyRevenueReportCategoryEnum.RESERVATION_FORECAST.getCategory(), 0);
        }

        /**
         * 上传报告，用于日志下载报告
         *
         * @param path S3 路径
         * @author zc
         * @date 2024/5/29
         */
        private void uploadReport(String path) {
            // 上传报告，用于日志下载报告
            try (InputStream in = amazonS3Service.getFile(path)) {
                amazonS3Service.uploadFile(S3BucketFunctionCons.WEEKLY_MONTHLY_REVENUE_IMPORT_RECORD, in, path);
            } catch (IOException e) {
                log.error("WMRevenueReservationForecastListener.handle end... Upload report error.", e);
            }
        }

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

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param s3Key            s3路径
         * @author zc
         * @date 2024/5/20
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Reservation Forecast Report error";
            String content = "Process error: " + exceptionMessage;
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, content, s3Key);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return java.lang.Boolean
         * @author zc
         * @date 2024/5/20
         */
        private Boolean preventConcurrency(String messageId) {
            return jsonRedisTemplate.opsForValue().setIfAbsent(
                    KeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

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