# WeeklyPlanListener.java

    package cloud.wconnect.workperformance.messagelistener.monthlyreport;

    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.weeklyplan.WeeklySalesPlanBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    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.service.monthlyreport.IMonthlyReportWeeklySalesPlanDetailService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    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.concurrent.TimeUnit;

    /**
     * 事件监听：Weekly Plan
     *
     * @author lichen
     * @date 2024/12/9
     */
    @Slf4j
    @Component
    public class WeeklyPlanListener{

        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private IMonthlyReportWeeklySalesPlanDetailService monthlyReportWeeklySalesPlanDetailService;
        /**
         * 事件主题
         */
        private static final String SUBJECT = MoudleEventSubjectEnum.WEEKLY_SALES_PLAN.getSubject();
        /**
         * 业务名称
         */
        private static final String BUSINESS = BusinessEnum.MONTHLY_REPORT.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author lichen
         * @date 2024/12/09
         */
        @Async
        @EventListener
        public void handle(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("WeeklyPlanListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("WeeklyPlanListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("WeeklyPlanListener.handle end... event body is blank.");
                return;
            }
            log.info("WeeklyPlanListener.body = " + event.getBody());
            // body 转换为对象
            WeeklySalesPlanBO weeklySalesPlanBO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), WeeklySalesPlanBO.class);

            PropertyDTO propertyDTO = propertyI18nRedisService.get(weeklySalesPlanBO.getPropertyId());
            if (!propertyDTO.getStatus()) {
                log.warn("WeeklyPlanListener.handle end... property is close.");
                return;
            }
            try {
                //处理数据
                monthlyReportWeeklySalesPlanDetailService.handleData(propertyDTO, weeklySalesPlanBO);
                log.info("WeeklyPlanListener.handle end...");
            } catch (Exception e) {
                String propertyAbbr = propertyDTO.getAbbr();
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage());
                }
                log.error("WeeklyPlanListener.handle end... Process error.", e);
            }
        }

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

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @author lichen
         * @date 2024/12/9
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage) {
            String subject = "[Warning] - Handle the [W-connect Weekly Sales Plan] event data is exception.";
            String content = "Handle the [W-connect Weekly Sales Plan] event data is exception: " + exceptionMessage;
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}",
                    SUBJECT, BUSINESS, propertyAbbr, content);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }
    }