# SvaDailyOperatingStatisticsIndexListener.java

    package cloud.wconnect.workperformance.messagelistener.sva;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.m3.DailyOperatingStatisticsIndexEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.m3.DailyOperatingStatisticsIndexBO;
    import cloud.wconnect.commonlib.pojo.bo.m3.DailyOperatingStatisticsIndexValueBO;
    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.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperatingStatisticsReportEnhancerService;
    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.*;
    import java.util.concurrent.TimeUnit;
    import java.util.stream.Collectors;

    /**
     * 处理TotalRev指标监听器
     *
     * @author lichen
     * @date 2025/10/15
     */
    @Slf4j
    @Component
    public class SvaDailyOperatingStatisticsIndexListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private CommonService commonService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private IOperatingStatisticsReportEnhancerService operatingStatisticsReportEnhancerService;

        private static final String BUSINESS = BusinessEnum.SVA_OPERATING_STATISTICS.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author lichen
         * @date 2025/10/15
         */
        @Async
        @EventListener
        public void handleIndex(ModuleEvent event) {
            String moduleEventSubject = event.getSubject();
            //主题集合
            List<String> subjectList = DailyOperatingStatisticsIndexEnum.listSubject();
            if (StringUtils.isBlank(event.getSubject()) || !subjectList.contains(moduleEventSubject)) {
                return;
            }
            if (!preventConcurrency(event.getMessageId(), moduleEventSubject)) {
                return;
            }
            log.info("SvaDailyOperatingStatisticsIndexListener.handle start, moduleEventSubject:{}", moduleEventSubject);
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SvaDailyOperatingStatisticsIndexListener.handle end... event body is blank, moduleEventSubject:{}", moduleEventSubject);
                return;
            }
            String propertyAbbr = "";
            try {
                //消息转化为BO
                DailyOperatingStatisticsIndexBO dailyOperatingStatisticsIndexBO = JsonUtils.convertStringToObject(objectMapper, event.getBody(),
                        DailyOperatingStatisticsIndexBO.class);
                Integer propertyId = dailyOperatingStatisticsIndexBO.getPropertyId();
                List<DailyOperatingStatisticsIndexValueBO> indexValues = dailyOperatingStatisticsIndexBO.getIndexValues();
                if (CollectionUtils.isEmpty(indexValues)) {
                    log.warn("SvaDailyOperatingStatisticsIndexListener.handle end... indexValues is empty, moduleEventSubject:{}", moduleEventSubject);
                    return;
                }

                PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
                propertyAbbr = propertyDTO.getAbbr();
                if (!propertyDTO.getStatus()) return;
                //校验是否开通功能
                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.SCHEDULE_VS_ACTUAL)) {
                    log.warn("SvaDailyOperatingStatisticsIndexListener.handle end... the property has not opened the Schedule vs actual function;property:{},moduleEventSubject:{}",
                            propertyAbbr, moduleEventSubject);
                    return;
                }

                // 处理Operating statistics的原始数据
                operatingStatisticsReportEnhancerService.handleOperatingStatisticsOriginByM3Api(propertyDTO, dailyOperatingStatisticsIndexBO);

                List<Integer> dates = dailyOperatingStatisticsIndexBO.getIndexValues().stream().map(DailyOperatingStatisticsIndexValueBO::getDate).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(dates)) return;

                Integer max = Collections.max(dates);
                Integer min = Collections.min(dates);
                ArrayList<Long> dateRange = Lists.newArrayList((long)min,(long)max);
                HashMap<Integer, List<Long>> propertyId2DateRange = new HashMap<>();
                propertyId2DateRange.put(propertyId, dateRange);

                // 按优先级更新Operating statistics数据
                operatingStatisticsReportEnhancerService.updateOperatingStatisticsByPriority(Collections.singletonList(propertyDTO), propertyId2DateRange);
                log.info("SvaDailyOperatingStatisticsIndexListener.handle end, moduleEventSubject:{}", moduleEventSubject);
            } catch (Exception e) {
                log.error("SvaDailyOperatingStatisticsIndexListener.handle end... moduleEventSubject:{}, error:{}", moduleEventSubject, e.getMessage());
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, propertyAbbr, moduleEventSubject)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), moduleEventSubject);
                }
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId          消息事件 id
         * @param moudleEventSubject 消息主题
         * @return java.lang.Boolean
         * @author lichen
         * @date 2025/10/15
         */
        private Boolean preventConcurrency(String messageId, String moudleEventSubject) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(moudleEventSubject, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr       资产简称
         * @param exceptionMsg       报错内容
         * @param moudleEventSubject 主题
         * @author lichen
         * @date 2025/10/15
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String moudleEventSubject) {
            //主题
            String subject = "[Warning] - SVA Handle Daily Operating Statistics Index exception.";

            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}",
                    moudleEventSubject, BUSINESS, propertyAbbr, exceptionMsg);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }