# OccupancySummaryReportListener.java

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

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.exception.ListenerException;
    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.bo.gmwr.OccupancySummaryReportBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrHistoryAndForecastService;
    import cloud.wconnect.workperformance.service.gmwr.occupancysummary.IOccupancySummaryParse;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.context.ApplicationContext;
    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.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     *  Occupancy Summary Report 事件处理
     *
     * @author: yyt
     * 2026-02-05
     */
    @RequiredArgsConstructor
    @Slf4j
    @Service
    public class OccupancySummaryReportListener {

        private final MailInternalService mailInternalService;
        private final IGmwrHistoryAndForecastService historyAndForecastService;
        private final PropertyInternalService propertyInternalService;
        private final RedisTemplate<String, Object> redisTemplate;
        private final ApplicationContext applicationContext;
        private final AmazonS3Service amazonS3Service;
        private final CommonService commonService;
        private final ObjectMapper objectMapper;

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

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author yyt
         * @date 2026/2/5
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("OccupancySummaryReportListener.start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("OccupancySummaryReportListener.end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("OccupancySummaryReportListener.handle end... event body is blank.");
                return;
            }
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            // 资产标识
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);
            // 获取租户标识
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantSymbol);
            if (Objects.isNull(property)) {
                log.warn("OccupancySummaryReportListener.handle end... The property is not exist; abbr name: {}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("OccupancySummaryReportListener.handle end...  The property is closed; abbr name: {}", propertyAbbrName);
                return;
            }
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if (!property.getPmsType().equals(source)) {
                log.warn("OccupancySummaryReportListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        property.getId(), property.getPmsType(), source);
                return;
            }
            if (!commonService.checkOpenFunction(property, FunctionIdConstant.GM_WEEKLY_REPORT)) {
                log.warn("OccupancySummaryReportListener.end... the property has not opened the end of shift function;property:{}", propertyAbbrName);
                return;
            }

            int operatorId = Integer.parseInt(parameter.get(EventBodyParamEnum.UID.getDesc()).toString());

            // 获取数据日期范围
            List<Long> dateRange = historyAndForecastService.getDateRange(property, parameter, operatorId);
            if (CollectionUtils.isEmpty(dateRange)) {
                log.warn("GmwrHistoryAndForecastListener.handle end... date range is empty.");
                return;
            }

            try (InputStream in = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                List<OccupancySummaryReportBO> occupancySummaryReportBOList = parseReport(in, source, property, dateRange);

                historyAndForecastService.updateOccupancySummaryData(property, occupancySummaryReportBOList);

                log.info("OccupancySummaryReportListener.handle end...");
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("OccupancySummaryReportListener.handle end... Process error.", e);
            }
        }

        /**
         * 解析报告
         *
         * @param in        文件
         * @param source    数据源平台
         * @param property  资产
         * @param dateRange 日期范围
         * @return OccupancySummaryReportBO
         * @author yyt
         * @date 2026/2/5
         */
        private List<OccupancySummaryReportBO> parseReport(InputStream in, String source, PropertyDTO property, List<Long> dateRange) {
            Map<String, IOccupancySummaryParse> beansOfType = applicationContext.getBeansOfType(IOccupancySummaryParse.class);
            Collection<IOccupancySummaryParse> parsers = beansOfType.values();
            for (IOccupancySummaryParse parser : parsers) {
                if (parser.supports(source)) {
                    return parser.parse(in, property, dateRange);
                }
            }
            throw new ListenerException("OccupancySummaryReportListener not find report parser");
        }
        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @author yyt
         * @date 2026/2/5
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle Occupancy Summary Exception";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author yyt
         * @date 2026/2/5
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

    }