# HotelKpiManagerFlashListener.java

    package cloud.wconnect.workperformance.messagelistener.hotelkpi.pms;

    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.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    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.sns.http.entity.SnsHttpEvent;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiNotifyTypeEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiReportCategoryEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiManagerFlashBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiImportLogService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiManagerFlashService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiReportService;
    import cloud.wconnect.workperformance.service.hotelkpi.managerflash.IHotelKpiManagerFlashParseService;
    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.*;
    import java.util.concurrent.TimeUnit;

    /**
     * 报告处理：manager-flash/service-mtd--1d
     *
     * @author zc
     * @date 2025/7/23
     */
    @Slf4j
    @Service
    public class HotelKpiManagerFlashListener {

        @Resource
        private IHotelKpiReportService reportService;
        @Resource
        private IHotelKpiManagerFlashService managerFlashService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private IHotelKpiImportLogService 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 ApplicationContext applicationContext;

        private final String SUBJECT = EventSubjectEnum.MANAGER_FLASH_SERVICE_MTD_YESTERDAY.getSubject();
        private final String BUSINESS = BusinessEnum.HOTEL_KPI.getBusiness();

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

            log.info("HotelKpiManagerFlashListener.handle start...");

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("HotelKpiManagerFlashListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HotelKpiManagerFlashListener.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 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("HotelKpiManagerFlashListener.handle end... Property not support this PMS type, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }
            IHotelKpiManagerFlashParseService parser = getParser(source);
            if (Objects.isNull(parser)) {
                log.warn("HotelKpiManagerFlashListener.handle end... parser not find, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

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

            // 获取数据日期范围
            List<Long> dateRange = getDateRange(propertyDTO, parameter, logId);
            if (CollectionUtils.isEmpty(dateRange)) {
                log.warn("HotelKpiManagerFlashListener.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 in = amazonS3Service.getFile(path)) {
                // 解析报告
                List<HotelKpiManagerFlashBO> boList = reportService.parseManagerFlashReport(propertyDTO, in, source);
                // 保存数据
                managerFlashService.insertOrUpdateBatch(propertyDTO.getId(), dateRange.get(0), boList);
                // 处理数据
                handleData(propertyDTO, dateRange.get(0));
            } catch (Exception e) {
                handleResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }

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

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

                int importResult = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                        ReportImportResultCons.IMPORT_RESULT_FAIL;
                if (Objects.isNull(logId)) {
                    // 生成导入记录
                    importLogService.save(propertyDTO, dateRange, path, importResult,
                            HotelKpiReportCategoryEnum.MANAGER_FLASH.getCategory(), 0);
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        importLogService.update(logId, operatorId, path, handleResult);
                    } else {
                        importLogService.save(propertyDTO, dateRange, path, importResult,
                                HotelKpiReportCategoryEnum.MANAGER_FLASH.getCategory(), operatorId);
                    }
                }
            }

            log.info("HotelKpiManagerFlashListener.handle end...");
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param reportDate  报告数据日期(yyyyMMdd)
         * @author zc
         * @date 2025/8/25
         */
        public void handleData(PropertyDTO propertyDTO, long reportDate) {
            List<Integer> metricsTypeList = Lists.newArrayList(HotelKpiMetricsEnum.OCC.getMetricsType(),
                    HotelKpiMetricsEnum.ADR.getMetricsType(), HotelKpiMetricsEnum.RM_REVENUE.getMetricsType(),
                    HotelKpiMetricsEnum.TOTAL_REVENUE.getMetricsType(), HotelKpiMetricsEnum.KIPSU_CONVERSATION.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.MANAGER_FLASH,
                        reportDate, reportDate, metricsType);
            }
        }

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

        /**
         * 获取报告数据日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param logId       日志 id
         * @return 数据日期范围
         * @author zc
         * @date 2025/7/23
         */
        private List<Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            if (Objects.isNull(logId)) {
                // 自动下发
                return reportService.getDateRange(propertyDTO.getTimezone(),
                        HotelKpiNotifyTypeEnum.MISSING_REPORT_MANAGER_FLASH.getType());
            }
            // 手动导入
            Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
            Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
            if (Objects.isNull(startDateObj) || Objects.isNull(endDateObj)) {
                return Collections.emptyList();
            }
            return List.of(Long.parseLong(startDateObj.toString()), Long.parseLong(endDateObj.toString()));
        }

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

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param s3Key            s3路径
         * @author zc
         * @date 2025/7/23
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Manager Flash MTD -1d 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 2025/7/23
         */
        private Boolean preventConcurrency(String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param propertyAbbr 资产标识
         * @author zc
         * @date 2025/7/23
         */
        private void updateLastTime(String propertyAbbr) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, propertyAbbr), ".");
            String value = String.valueOf(DateTimeUtils.dateTimeNow(defaultTimezone).toEpochSecond());
            jsonRedisTemplate.opsForValue().set(key, value);
        }

        /**
         * 获取解析器
         *
         * @param source 来源标识
         * @return cloud.wconnect.workperformance.service.hotelkpi.managerflash.IHotelKpiManagerFlashParseService
         * @author lichen
         * @date 2026/1/26
         */
        public IHotelKpiManagerFlashParseService getParser(String source) {
            IHotelKpiManagerFlashParseService parser = null;
            Collection<IHotelKpiManagerFlashParseService> parserList = applicationContext.getBeansOfType(IHotelKpiManagerFlashParseService.class).values();
            for (IHotelKpiManagerFlashParseService bean : parserList) {
                if (bean.supports(source)) {
                    parser = bean;
                    break;
                }
            }
            return parser;
        }
    }