# SalesKpiMonthlyByRoomRevenueListener.java

    package cloud.wconnect.workperformance.messagelistener.saleskpi;

    import cloud.wconnect.commonlib.component.BeanMapper;
    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.workperformance.pojo.bo.modelevent.monthlyreport.MonthlyReportEventDataBO;
    import cloud.wconnect.workperformance.pojo.bo.modelevent.monthlyreport.MonthlyReportEventBO;
    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.commonlib.util.YearMonthUtils;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.saleskpi.SalesKpiMonthlyDataSourceCons;
    import cloud.wconnect.workperformance.pojo.dto.saleskpi.config.SalesConfigMonthlyRoomRevenueDTO;
    import cloud.wconnect.workperformance.pojo.dto.saleskpi.monthly.trans.SalesKpiTransMonthlyDTO;
    import cloud.wconnect.workperformance.pojo.dto.saleskpi.monthly.trans.SalesKpiTransMonthlyDataDTO;
    import cloud.wconnect.workperformance.service.saleskpi.ISalesKpiMonthlyReportService;
    import cloud.wconnect.workperformance.service.saleskpi.ISalesKpiMonthlyRevenueConfigService;
    import cloud.wconnect.workperformance.service.saleskpi.ISalesKpiMonthlyService;
    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.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    import java.text.MessageFormat;
    import java.util.Collections;
    import java.util.List;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 事件处理：Sales KPI Monthly By Room Revenue
     *
     * @author zc
     * @date 2023/09/12
     */
    @Slf4j
    @Component
    public class SalesKpiMonthlyByRoomRevenueListener {
        @Resource
        private ISalesKpiMonthlyService salesKpiMonthlyService;
        @Resource
        private ISalesKpiMonthlyRevenueConfigService salesKpiMonthlyRevenueConfigService;
        @Resource
        private ISalesKpiMonthlyReportService salesKpiMonthlyReportService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private BeanMapper beanMapper;
        @Resource
        private CommonService commonService;

        private static final String SUBJECT = MoudleEventSubjectEnum.MONTHLY_REPORT_ROOM_REVENUE.getSubject();
        private static final String BUSINESS = BusinessEnum.SALES_KPI.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2023/4/3
         */
        @Async
        @EventListener
        public void handle(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("SalesKpiMonthlyByRoomRevenueListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end... event body is blank.");
                return;
            }

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

            PropertyDTO propertyDTO = propertyInternalService.getOne(monthlyReportEventBO.getPropertyId());
            if (!propertyDTO.getStatus()) {
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end... property is closed.");
                return;
            }
            if(!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.SALES_KPI)){
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end...property not open sales kpi function.");
                return;
            }
            try {
                // 格式化 Room Revenue 指标数据
                List<SalesKpiTransMonthlyDTO> transMonthlyDTOList = extractTransMonthlyData(monthlyReportEventBO);
                // 保存采集的 Room Revenue 指标数据
                salesKpiMonthlyReportService.saveBatch(monthlyReportEventBO.getPropertyId(), transMonthlyDTOList);
                // 提取受影响的月份集合
                List<Long> theMonthList = transMonthlyDTOList.stream().map(SalesKpiTransMonthlyDTO::getMonthly).toList();
                // 更新受影响的月份数据
                salesKpiMonthlyService.handleRoomRevenueData(propertyDTO, theMonthList);

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

                log.error("SalesKpiMonthlyByRoomRevenueListener.handle end... Process error.", e);
            }
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @param eventBody        事件体
         * @author zc
         * @date 2025/8/12
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String eventBody) {
            String subject = "[Warning] - Handle the [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}",
                    SUBJECT, BUSINESS, propertyAbbr, content, eventBody);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 提取指标数据
         *
         * @param monthlyReportEventBO Room Revenue 指标数据
         * @return 指标数据
         * @author zc
         * @date 2023/9/13
         */
        private List<SalesKpiTransMonthlyDTO> extractTransMonthlyData(MonthlyReportEventBO monthlyReportEventBO) {
            List<MonthlyReportEventDataBO> monthlyRoomRevenueList = monthlyReportEventBO.getList();
            if (CollectionUtils.isEmpty(monthlyRoomRevenueList)) {
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end... monthlyRoomRevenueList is empty.");
                return Collections.emptyList();
            }

            // 获取配置
            SalesConfigMonthlyRoomRevenueDTO roomRevenueDTO = salesKpiMonthlyRevenueConfigService
                    .getByPropertyId(monthlyReportEventBO.getPropertyId());
            if (Objects.isNull(roomRevenueDTO)) {
                log.warn("SalesKpiMonthlyByRoomRevenueListener.handle end... roomRevenueDTO is null.");
                return Collections.emptyList();
            }

            List<SalesKpiTransMonthlyDTO> resultList = Lists.newArrayList();
            monthlyRoomRevenueList.forEach(revenue -> {
                List<SalesKpiTransMonthlyDataDTO> transMonthlyDataList = Lists.newArrayList();
                revenue.getData().forEach(item -> {
                    // 将item映射为SalesKpiEventMonthlyDataDTO对象
                    SalesKpiTransMonthlyDataDTO transMonthlyData = beanMapper.map(item, SalesKpiTransMonthlyDataDTO.class);
                    if (roomRevenueDTO.getRooms().equals(item.getCategoryName())) {
                        // 根据categoryName设置dataSource
                        transMonthlyData.setDataSource(SalesKpiMonthlyDataSourceCons.DATA_SOURCE_HOTEL_ACHIEVEMENT_ROOMS);
                    } else if (roomRevenueDTO.getFb().equals(item.getCategoryName())) {
                        transMonthlyData.setDataSource(SalesKpiMonthlyDataSourceCons.DATA_SOURCE_HOTEL_ACHIEVEMENT_FB);
                    } else if (roomRevenueDTO.getRevpar().equals(item.getCategoryName())) {
                        transMonthlyData.setDataSource(SalesKpiMonthlyDataSourceCons.DATA_SOURCE_REVPAR);
                    } else {
                        return;
                    }
                    transMonthlyDataList.add(transMonthlyData);
                });
                if (CollectionUtils.isEmpty(transMonthlyDataList)) {
                    return;
                }
                SalesKpiTransMonthlyDTO transMonthlyDTO = beanMapper.map(revenue, SalesKpiTransMonthlyDTO.class, dto -> {
                    // 将年份和月份解析为long类型的整数
                    dto.setMonthly(YearMonthUtils.parseYearMonthToLong(YearMonthUtils.getYearMonth(revenue.getYearMonth().toString())));
                    dto.setData(transMonthlyDataList);
                });
                resultList.add(transMonthlyDTO);
            });
            return resultList;
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/9/13
         */
        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);
        }
    }