# HotelKpiMonthlyReportListener.java

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

    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.commonlib.util.RedissonLockUtil;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMonthlyReportCons;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.entity.hotelkpi.HotelKpiWconnectMonthlyReport;
    import cloud.wconnect.workperformance.pojo.bo.modelevent.monthlyreport.MonthlyReportEventBO;
    import cloud.wconnect.workperformance.pojo.bo.modelevent.monthlyreport.MonthlyReportEventDataBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiWconnectMonthlyReportService;
    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.collections4.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.redisson.api.RedissonClient;
    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.text.MessageFormat;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    import java.util.stream.Collectors;

    /**
     * 事件监听：Monthly Report
     *
     * @author zc
     * @date 2025/08/26
     */
    @Slf4j
    @Service
    public class HotelKpiMonthlyReportListener {
        @Resource
        private IHotelKpiWconnectMonthlyReportService monthlyReportService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private CommonService commonService;
        @Resource
        private RedissonClient redissonClient;

        private static final String SUBJECT_MONTHLY_REPORT_PROFIT = MoudleEventSubjectEnum.MONTHLY_REPORT_PROFIT.getSubject();
        private static final String SUBJECT_MONTHLY_REPORT_ROOM_REVENUE = MoudleEventSubjectEnum.MONTHLY_REPORT_ROOM_REVENUE.getSubject();
        private static final List<String> SUBJECT_LIST = Lists.newArrayList(SUBJECT_MONTHLY_REPORT_PROFIT, SUBJECT_MONTHLY_REPORT_ROOM_REVENUE);
        private static final String BUSINESS = BusinessEnum.HOTEL_KPI.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2025/8/26
         */
        @Async
        @EventListener
        public void handle(ModuleEvent event) {
            if (!SUBJECT_LIST.contains(event.getSubject())) {
                return;
            }

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

            if (!preventConcurrency(event.getSubject(), event.getMessageId())) {
                log.warn("HotelKpiMonthlyReportListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HotelKpiMonthlyReportListener.handle end... event body is blank.");
                return;
            }

            // body 转换为对象
            MonthlyReportEventBO eventBO = JsonUtils.convertStringToObject(objectMapper,
                    event.getBody(), MonthlyReportEventBO.class);

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

            try {
                int type = SUBJECT_MONTHLY_REPORT_PROFIT.equals(event.getSubject()) ?
                        HotelKpiMonthlyReportCons.PROFIT : HotelKpiMonthlyReportCons.ROOM_REVENUE;
                // 保存数据
                saveData(propertyDTO, type, eventBO.getList());

                // 处理 Profit 数据
                handleData(propertyDTO, type, eventBO.getList());

                log.info("HotelKpiMonthlyReportListener.handle end...");
            } catch (Exception e) {
                String propertyAbbr = propertyDTO.getAbbr();
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), event.getSubject(), event.getBody());
                }
                log.error("HotelKpiMonthlyReportListener.handle end... Process error.", e);
            }
        }

        /**
         * 保存数据
         *
         * @param propertyDTO 资产
         * @param type        数据类型
         * @param boList      数据
         * @author zc
         * @date 2026/2/14
         */
        public void saveData(PropertyDTO propertyDTO, int type, List<MonthlyReportEventDataBO> boList) {
            if (CollectionUtils.isEmpty(boList)) {
                return;
            }

            // 1. 按 month 分组
            Map<Long, List<MonthlyReportEventDataBO>> groupedByMonth = boList.stream()
                    .collect(Collectors.groupingBy(MonthlyReportEventDataBO::getYearMonth));

            // 2. 逐组处理（串行）
            for (Map.Entry<Long, List<MonthlyReportEventDataBO>> entry : groupedByMonth.entrySet()) {
                long month = entry.getKey();
                List<MonthlyReportEventDataBO> monthBoList = entry.getValue();

                // 构建该 month 的实体
                List<HotelKpiWconnectMonthlyReport> entityList = monthlyReportService.buildEntityList(propertyDTO, type, monthBoList);
                if (entityList.isEmpty()) {
                    continue;
                }

                // 生成锁 key: wconnect:hotel-kpi:handle-monthly-report:{property id}:{month}
                String lockKey = HotelKpiCons.HANDLE_MONTHLY_REPORT_KEY + propertyDTO.getId() + ":" + month;

                // 加锁并执行事务
                RedissonLockUtil.execute(redissonClient, lockKey, 3, 5, () ->
                        monthlyReportService.saveData(entityList));
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param type        数据类型
         * @param list        数据
         * @author zc
         * @date 2025/8/26
         */
        public void handleData(PropertyDTO propertyDTO, int type, List<MonthlyReportEventDataBO> list) {
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            List<Long> dateList = list.stream().map(MonthlyReportEventDataBO::getYearMonth).toList();
            long startDate = Collections.min(dateList);
            long endDate = Collections.max(dateList);

            List<Integer> metricsTypeList = (type == HotelKpiMonthlyReportCons.PROFIT) ?
                    List.of(HotelKpiMetricsEnum.GOP.getMetricsType()) :
                    List.of(HotelKpiMetricsEnum.OCC.getMetricsType(), HotelKpiMetricsEnum.ADR.getMetricsType(),
                            HotelKpiMetricsEnum.RM_REVENUE.getMetricsType(), HotelKpiMetricsEnum.TOTAL_REVENUE.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.MONTHLY_REPORT,
                        startDate, endDate, metricsType);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @param propertyId 资产 id
         * @return PropertyDTO
         * @author zc
         * @date 2025/8/23
         */
        private PropertyDTO getEffectiveProperty(int propertyId) {
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            if (Objects.isNull(propertyDTO)) {
                log.warn("HotelKpiMonthlyReportListener.handle end... The property:{} is not exist", propertyId);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("HotelKpiMonthlyReportListener.handle end...  The property:{} is closed", propertyId);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOTEL_KPI)) {
                log.warn("HotelKpiMonthlyReportListener.handle end... The property:{} has not opened hotel kpi function", propertyId);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param eventSubject     事件主题
         * @param eventBody        事件体
         * @author zc
         * @date 2025/8/23
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String eventSubject, String eventBody) {
            String subject = "[Warning] - Handle [W-connect Monthly Report] data error";
            String content = "Process error: " + exceptionMessage;
            String mailContent = MessageFormat.format("Module SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>EventBody:{4}",
                    eventSubject, BUSINESS, propertyAbbr, content, eventBody);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param eventSubject 事件主题
         * @param messageId    消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2025/8/23
         */
        private Boolean preventConcurrency(String eventSubject, String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(eventSubject, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }
    }