# SalesSourceTotalRevIndexListener.java

    package cloud.wconnect.workperformance.messagelistener.mor;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    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.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.pojo.bo.mor.sales.SalesSourceOperatingStatisticsListBO;
    import cloud.wconnect.workperformance.service.mor.ISalesService;
    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.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.time.LocalDate;
    import java.util.List;
    import java.util.concurrent.TimeUnit;

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

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

        private static final String SUBJECT = MoudleEventSubjectEnum.M3_OPERATING_STATISTICS_TOTAL_REV.getSubject();
        private static final String BUSINESS = BusinessEnum.MOR_SALES.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author lichen
         * @date 2025/10/15
         */
        @Async
        @EventListener
        public void handleTotalRevIndex(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }
            log.info("SalesSourceTotalRevIndexListener.handle start");
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SalesSourceTotalRevIndexListener.handle end... event body is blank.");
                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("SalesSourceTotalRevIndexListener.handle end... indexValues is empty.");
                    return;
                }

                PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
                propertyAbbr = propertyDTO.getAbbr();
                if (!propertyDTO.getStatus()) return;
                //校验是否开通功能
                if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.MONTHLY_OT_REPORT)) {
                    log.warn("SalesSourceTotalRevIndexListener.handle end... the property has not opened the monthly OT report function;property:{}", propertyAbbr);
                    return;
                }
                // 转化为BO
                List<SalesSourceOperatingStatisticsListBO> boList = indexValues.stream().map(indexValue -> {
                    SalesSourceOperatingStatisticsListBO bo = new SalesSourceOperatingStatisticsListBO();
                    bo.setProperty(propertyDTO.getAbbr());
                    bo.setTotalRev(indexValue.getIndexValue());
                    //yyyyMMdd转换成yyyy-MM-dd
                    LocalDate localDate = DateTimeUtils.strToLocalDate(indexValue.getDate().toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
                    String theDay = DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    bo.setTheDay(theDay);
                    return bo;
                }).toList();

                //处理totalRev数据
                salesService.handleOperatingStatisticsByM3Api(propertyDTO, boList, 0);
                log.info("SalesSourceTotalRevIndexListener.handle end");
            } catch (Exception e) {
                log.error("SalesSourceTotalRevIndexListener.handle end... error:{}", e.getMessage());
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage());
                }
            }
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return java.lang.Boolean
         * @author lichen
         * @date 2025/10/15
         */
        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);
        }

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

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

    }