# HotelKpiQuoreFWHotelPMListener.java

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

    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.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiQuoreReportService;
    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;

    /**
     * 报告处理：quore-FW Hotel
     *
     * @author zc
     * @date 2024/7/16
     */
    @Slf4j
    @Service
    public class HotelKpiQuoreFWHotelPMListener {

        @Resource
        private IHotelKpiQuoreReportService quoreReportService;
        @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.QUORE_FW_HOTEL.getSubject();
        private final String BUSINESS = BusinessEnum.HOTEL_KPI.getBusiness();

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

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

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("HotelKpiQuoreFWHotelPMListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("HotelKpiQuoreFWHotelPMListener.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;
            }
            String path = eventBodyDTO.getPath();

            try (InputStream in = amazonS3Service.getFile(path)) {
                // 处理报告数据
                quoreReportService.handleQuoreReport(propertyDTO, in, path,
                        HotelKpiMetricsEnum.FW_INSPECTION_HOTEL.getMetricsType());
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }
                log.error("HotelKpiQuoreFWHotelPMListener.handle end... Process error.", e);
            }

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

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author zc
         * @date 2024/7/16
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("HotelKpiQuoreFWHotelPMListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("HotelKpiQuoreFWHotelPMListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.HOTEL_KPI)) {
                log.warn("HotelKpiQuoreFWHotelPMListener.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 2024/7/16
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Quore FW Hotel 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 2024/7/16
         */
        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);
        }
    }