# SvaDailyOperatingStatisticsIndexListener.java

    package cloud.wconnect.workperformance.messagelistener.sva;

    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.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.commonlib.util.RedissonLockUtil;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.sva.SvaConstant;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperatingStatisticsService;
    import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
    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.lang3.StringUtils;
    import org.redisson.api.RLock;
    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.Component;

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

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

        @Resource
        private IOperatingStatisticsService operatingStatisticsService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private CommonService commonService;
        @Resource
        private PropertyI18nRedisService propertyI18nRedisService;
        @Resource
        private RedissonClient redissonClient;

        private static final String BUSINESS = BusinessEnum.SVA_OPERATING_STATISTICS.getBusiness();
        /**
         * 最大自旋次数
         */
        private static final int MAXIMUM = 10;

        /**
         * 异步监听事件处理
         *
         * @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;
                }

                //处理指标数据
                doHandleIndex(propertyDTO, dailyOperatingStatisticsIndexBO);
                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 propertyDTO                     资产DTO
         * @param dailyOperatingStatisticsIndexBO 指标BO
         * @author lichen
         * @date 2025/10/15
         */
        private void doHandleIndex(PropertyDTO propertyDTO, DailyOperatingStatisticsIndexBO dailyOperatingStatisticsIndexBO) {
            List<String> keys = dailyOperatingStatisticsIndexBO.getIndexValues().stream().map(item -> {
                Integer date = item.getDate();
                return MessageFormat.format(SvaConstant.HANDLE_DAILY_OPERATING_STATISTICS_KEY, propertyDTO.getId(), date.toString());
            }).toList();
            //锁集合
            RLock[] locks = keys.stream().map(redissonClient::getLock).toList().toArray(new RLock[keys.size()]);

            //获取锁
            RLock multiLock = redissonClient.getMultiLock(locks);

            if (RedissonLockUtil.getLock(multiLock, MAXIMUM, 2)) {
                try {
                    // 更新指标数据
                    operatingStatisticsService.updateOperatingStatisticsIndexByM3Api(propertyDTO, dailyOperatingStatisticsIndexBO, 0);
                } finally {
                    if (multiLock.isHeldByCurrentThread()) {
                        multiLock.unlock();  // 释放锁
                    }
                }
            } else {
                throw new RuntimeException("SvaDailyOperatingStatisticsIndexListener handle error, The number of execution failures reached the upper limit");
            }
        }

        /**
         * 防止并发操作
         *
         * @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);
        }

    }