# HotelKpiM3MonthlyReportTotalsListener.java

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

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    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.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.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.m3.HotelKpiM3MonthlyReportTotalsBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiM3MonthService;
    import cloud.wconnect.workperformance.service.hotelkpi.m3.HotelKpiM3MonthlyReportTotalsParseService;
    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.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;

    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 监听器：M3 Monthly Report Totals
     *
     * @author zc
     * @date 2025/08/27
     */
    @Slf4j
    @Service
    public class HotelKpiM3MonthlyReportTotalsListener {

        @Resource
        private HotelKpiM3MonthlyReportTotalsParseService m3MonthlyReportTotalsParseService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private IHotelKpiM3MonthService m3MonthService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private CommonService commonService;
        @Value("${default.timezone}")
        private String defaultTimezone;

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

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

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

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("HotelKpiM3MonthlyReportTotalsListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HotelKpiM3MonthlyReportTotalsListener.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> propertyAbbrList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            // 获取有效的资产数据
            List<PropertyDTO> propertyDTOList = listEffectiveProperty(tenantSymbol, propertyAbbrList);
            if (CollectionUtils.isEmpty(propertyDTOList)) {
                log.warn("HotelKpiM3MonthlyReportTotalsListener.handle end... propertyDTOList is empty.");
                return;
            }

            String path = eventBodyDTO.getPath();

            try (InputStream in = amazonS3Service.getFile(path)) {
                LocalDate nowLocalDate = LocalDate.now(ZoneId.of(defaultTimezone));
                // 解析报告数据
                Map<Integer, HotelKpiM3MonthlyReportTotalsBO> propertyId2Bo = m3MonthlyReportTotalsParseService.parse(propertyDTOList, in).stream()
                        .collect(Collectors.toMap(HotelKpiM3MonthlyReportTotalsBO::getPropertyId, Function.identity()));
                propertyDTOList.forEach(propertyDTO -> {
                    HotelKpiM3MonthlyReportTotalsBO bo = propertyId2Bo.get(propertyDTO.getId());
                    if (Objects.isNull(bo)) {
                        return;
                    }
                    // 保存报告数据
                    long dataDate = m3MonthService.saveData(propertyDTO, nowLocalDate, bo, path);
                    // 处理报告数据
                    handleData(propertyDTO, dataDate);
                });
            } catch (Exception e) {
                String propertyAbbr = propertyAbbrList.stream().sorted().collect(Collectors.joining(","));
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }
                log.error("HotelKpiM3MonthlyReportTotalsListener.handle end... Process error.", e);
            }

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

        /**
         * 处理报告数据
         *
         * @param propertyDTO 资产数据
         * @param dataDate    数据日期(yyyyMM)
         * @author zc
         * @date 2025/8/27
         */
        public void handleData(PropertyDTO propertyDTO, long dataDate) {
            List<Integer> metricsTypeList = List.of(HotelKpiMetricsEnum.FB_RESTAURANT.getMetricsType(),
                    HotelKpiMetricsEnum.FB_BANQUET.getMetricsType(), HotelKpiMetricsEnum.OTHER_REVENUE.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.M3_MONTH,
                        dataDate, dataDate, metricsType);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol     租户标识
         * @param propertyAbbrList 资产标识
         * @return PropertyDTO 集合
         * @author zc
         * @date 2025/8/27
         */
        private List<PropertyDTO> listEffectiveProperty(String tenantSymbol, List<String> propertyAbbrList) {
            if (CollectionUtils.isEmpty(propertyAbbrList)) {
                return Collections.emptyList();
            }

            // 获取资产数据
            return propertyInternalService.getProperty(propertyAbbrList, tenantSymbol).stream().filter(item ->
                    item.getStatus() && commonService.checkOpenFunction(item, FunctionIdConstant.HOTEL_KPI)).toList();
        }

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