# GmwrStrWeekListener.java

    package cloud.wconnect.workperformance.messagelistener.gmwr.str;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.cons.HandleReportDataStatusCons;
    import cloud.wconnect.workperformance.pojo.bo.gmwr.str.GmwrStrDataBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrStrDataService;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrStrService;
    import cloud.wconnect.workperformance.service.gmwr.str.GmwrStrWeekParseService;
    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.Service;

    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 报告处理：Str week
     *
     * @author zc
     * @date 2025/8/22
     */
    @Slf4j
    @Service
    public class GmwrStrWeekListener {

        @Resource
        private IGmwrStrService strService;
        @Resource
        private IGmwrStrDataService strDataService;
        @Resource
        private GmwrStrWeekParseService strWeekParseService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private CommonService commonService;

        private final String SUBJECT = EventSubjectEnum.STR_WEEK.getSubject();
        private final String BUSINESS = BusinessEnum.GM_WEEKLY_REPORT.getBusiness();

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

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

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

            // 解析事件体内容
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbr = abbrNameList.get(0);

            // 获取有效的资产数据
            PropertyDTO propertyDTO = getEffectiveProperty(tenantSymbol, propertyAbbr);
            if (Objects.isNull(propertyDTO)) {
                return;
            }
            // Str Data id
            Object idObject = parameter.get(EventBodyParamEnum.ID.getDesc());
            Integer strDataId = Objects.isNull(idObject) ? null : Integer.parseInt(idObject.toString());
            // 报告文件地址
            String path = eventBodyDTO.getPath();

            // 处理是否成功
            boolean handleResult = true;
            try (InputStream in = amazonS3Service.getFile(path)) {
                // 解析报告数据
                GmwrStrDataBO bo = strWeekParseService.parse(propertyDTO, in);
                // 存储报告数据
                strService.handleStrWeekReport(propertyDTO, bo, path);
                // 处理 Str Data 数据
                strDataService.handleStrWeekReport(propertyDTO, strDataId, bo, path);
            } catch (Exception e) {
                handleResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }
                log.error("GmwrStrWeekListener.handle end... Process error.", e);
            } finally {
                if (Objects.nonNull(strDataId)) {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        String status = handleResult ? HandleReportDataStatusCons.SUCCESS : HandleReportDataStatusCons.FAILED;
                        strDataService.updateStatus(strDataId, status);
                    }
                }
            }

            log.info("GmwrStrWeekListener.handle end...");
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author zc
         * @date 2025/8/22
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("GmwrStrWeekListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("GmwrStrWeekListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.GM_WEEKLY_REPORT)) {
                log.warn("GmwrStrWeekListener.handle end... The property:{} has not opened hotel kpi function", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产简称
         * @param exceptionMessage 异常信息
         * @param s3Key            s3路径
         * @author zc
         * @date 2025/8/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Str week Report error";
            String content = "Process error: " + exceptionMessage;
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, content, s3Key);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

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