# WMRevenueManagerFlashTwoDayAgoListener.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.WMRevenueManagerFlashBO;
    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.managerflash.IWMRevenueManagerFlashParseService;
    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.Component;

    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;

    /**
     * 处理manager-flash/service-2d报告监听器
     *
     * @author lichen
     * @date 2025/12/12
     */
    @Slf4j
    @Component
    public class WMRevenueManagerFlashTwoDayAgoListener {

        @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.MANAGER_FLASH_TWO_DAY_AGO.getSubject();
        private final String BUSINESS = BusinessEnum.WEEKLY_MONTHLY_REVENUE.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件对象
         * @author lichen
         * @date 2025/12/12
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("WMRevenueManagerFlashTwoDayAgoListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("WMRevenueManagerFlashTwoDayAgoListener.handle end... event body is blank.");
                return;
            }
            log.info("WMRevenueManagerFlashTwoDayAgoListener.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("WMRevenueManagerFlashTwoDayAgoListener.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("WMRevenueManagerFlashTwoDayAgoListener.handle end... Property not support this PMS type, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

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

            // 报告数据类型
            int category = MonthlyRevenueImportCategoryCons.HISTORY;
            // 获取文件路径
            String path = eventBodyDTO.getPath();

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

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

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

                log.info("WMRevenueManagerFlashTwoDayAgoListener.handle end...");
            } catch (Exception e) {
                handleResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }
                log.error("WMRevenueManagerFlashTwoDayAgoListener.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.MANAGER_FLASH.getCategory(), 0);
            }
        }

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

        /**
         * 处理缺少营业日期的情况
         *
         * @param propertyDTO    资产信息
         * @param path           文件路径
         * @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.MANAGER_FLASH_TWO_DAY_AGO.getDateRange());

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

        /**
         * 上传报告，用于日志下载报告
         *
         * @param path S3 路径
         * @author lichen
         * @date 2025/12/12
         */
        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("WMRevenueManagerFlashTwoDayAgoListener.handle end... Upload report error.", e);
            }
        }

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

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param s3Key            s3路径
         * @author lichen
         * @date 2025/12/12
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Manager Flash -2 days 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 lichen
         * @date 2025/12/12
         */
        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 lichen
         * @date 2025/12/12
         */
        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)));
        }

    }