# HotelKpiMedalliaResponseIhgListener.java

    package cloud.wconnect.workperformance.messagelistener.hotelkpi.medallia;

    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.pojo.dto.hotelkpi.originkpi.HotelKpiParseValueDTO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiMedalliaResponseService;
    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;

    /**
     * 报告处理: Medallia Response IHG
     *
     * @author zc
     * @date 2025/08/24
     */
    @Slf4j
    @Service
    public class HotelKpiMedalliaResponseIhgListener {

        @Resource
        private IHotelKpiMedalliaResponseService medalliaResponseService;
        @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.MEDALLIA_RESPONSE_IHG.getSubject();
        private final String BUSINESS = BusinessEnum.HOTEL_KPI.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("HotelKpiMedalliaResponseIhgListener.handle start...");

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("HotelKpiMedalliaResponseIhgListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HotelKpiMedalliaResponseIhgListener.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;
            }
            // 报告下载日期
            long fileDate = Long.parseLong(parameter.get(EventBodyParamEnum.DATE.getDesc()).toString());
            // 日期类型（1:Weekly;2:Monthly;3:Quarterly;4:Yearly）
            int dateType = Integer.parseInt(parameter.get(EventBodyParamEnum.BASE_ON.getDesc()).toString());
            // 报告数据开始日期
            long dataDate = Long.parseLong(parameter.get(EventBodyParamEnum.START_DATE.getDesc()).toString());
            String path = eventBodyDTO.getPath();

            try (InputStream in = amazonS3Service.getFile(path)) {
                // 解析报告数据
                HotelKpiParseValueDTO parseValueDTO = medalliaResponseService.parseReport(propertyDTO, fileDate, in);
                // 处理报告数据
                medalliaResponseService.handleData(propertyDTO, parseValueDTO, path, dateType, dataDate);

                log.info("HotelKpiMedalliaResponseIhgListener.handle end...");
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }
                log.error("HotelKpiMedalliaResponseIhgListener.handle end... Process error.", e);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @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("HotelKpiMedalliaResponseIhgListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("HotelKpiMedalliaResponseIhgListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOTEL_KPI)) {
                log.warn("HotelKpiMedalliaResponseIhgListener.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 Medallia Response IHG 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);
        }
    }