# HotelKpiWconnectSalesSourceListener.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.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.modelevent.salessource.MorSalesSourceEventBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiWconnectSalesSourceService;
    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.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;
    import java.util.function.Function;
    import java.util.stream.Collectors;

    /**
     * 事件监听: wconnect Sales Source
     *
     * @author zc
     * @date 2024/08/11
     */
    @Slf4j
    @Component
    public class HotelKpiWconnectSalesSourceListener {
        @Resource
        private IHotelKpiWconnectSalesSourceService wconnectSalesSourceService;
        @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;

        private static final String SUBJECT = MoudleEventSubjectEnum.MOR_SALES_SOURCE.getSubject();
        private static final String BUSINESS = BusinessEnum.HOTEL_KPI.getBusiness();

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

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

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

            // body 转换为对象
            List<MorSalesSourceEventBO> salesSourceEventBOList = JsonUtils.convertStringToList(objectMapper,
                    event.getBody(), MorSalesSourceEventBO.class);
            if (CollectionUtils.isEmpty(salesSourceEventBOList)) {
                return;
            }

            // 保存数据
            wconnectSalesSourceService.save(salesSourceEventBOList);

            // 过滤出有效的资产
            List<Integer> propertyIds = salesSourceEventBOList.stream().map(MorSalesSourceEventBO::getPropertyId).toList();
            List<PropertyDTO> propertyDTOList = propertyI18nRedisService.list(propertyIds).stream()
                    .filter(propertyDTO -> propertyDTO.getStatus()
                            && commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOTEL_KPI))
                    .toList();
            if (CollectionUtils.isEmpty(propertyDTOList)) {
                log.warn("HotelKpiWconnectSalesSourceListener.handle end... property is closed or has not opened the hotel kpi function.");
                return;
            }
            Map<Integer, PropertyDTO> effectiveProperty = propertyDTOList.stream()
                    .collect(Collectors.toMap(PropertyDTO::getId, Function.identity()));

            Map<Integer, List<MorSalesSourceEventBO>> propertyId2OvertimeList = salesSourceEventBOList.stream()
                    .collect(Collectors.groupingBy(MorSalesSourceEventBO::getPropertyId));
            try {
                for (Map.Entry<Integer, List<MorSalesSourceEventBO>> entry : propertyId2OvertimeList.entrySet()) {
                    PropertyDTO propertyDTO = effectiveProperty.get(entry.getKey());
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }

                    // 提取需要更新数据的日期
                    List<Long> dateList = entry.getValue().stream().map(MorSalesSourceEventBO::getDate).toList();

                    // 处理数据
                    handleData(propertyDTO, dateList);
                }

                log.info("HotelKpiWconnectSalesSourceListener.handle end...");
            } catch (Exception e) {
                String propertyAbbr = propertyDTOList.stream().map(PropertyDTO::getAbbr)
                        .sorted().collect(Collectors.joining(","));
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), event.getBody());
                }
                log.error("HotelKpiWconnectSalesSourceListener.handle end... Process error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param dateList    数据日期(yyyyMMdd)
         * @author zc
         * @date 2025/8/25
         */
        public void handleData(PropertyDTO propertyDTO, List<Long> dateList) {
            if (CollectionUtils.isEmpty(dateList)) {
                return;
            }
            long startDate = Collections.min(dateList);
            long endDate = Collections.max(dateList);

            List<Integer> metricsTypeList = Lists.newArrayList(HotelKpiMetricsEnum.OVERTIME_EXPENSE.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.OVERTIME,
                        startDate, endDate, metricsType);
            }
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @param eventBody        事件体
         * @author zc
         * @date 2025/8/7
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String eventBody) {
            String subject = "[Warning] - Handle the [W-connect Sales Source] 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 messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/9/30
         */
        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);
        }
    }