# GmwrManagerFlashListener.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    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.DateTimeUtils;
    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.GmwrManagerFlashBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrManagerFlashService;
    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.time.LocalDate;
    import java.time.ZoneId;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 报告处理：manager-flash/service-last-month
     *
     * @author zc
     * @date 2024/10/17
     */
    @Slf4j
    @Service
    public class GmwrManagerFlashListener {
        @Resource
        private IGmwrManagerFlashService managerFlashService;
        @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.MANAGER_FLASH_SERVICE_LAST_MONTH.getSubject();
        private final String BUSINESS = BusinessEnum.GM_WEEKLY_REPORT.getBusiness();

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

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

            if (!preventConcurrency(event.getMessageId())) {
                log.warn("GmwrManagerFlashListener.handle end... A machine has been executed");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("GmwrManagerFlashListener.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;
            }
            // 获取资产 PMS 类型
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());

            // 校验事件 PMS 类型是否与资产配置匹配
            if (!StringUtils.equals(propertyDTO.getPmsType(), source)) {
                log.warn("GmwrManagerFlashListener.handle end... Property not support this PMS type, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

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

            // 获取数据日期范围
            Long dateRange = getDateRange(propertyDTO, parameter, operatorId);
            if (Objects.isNull(dateRange)) {
                log.warn("GmwrManagerFlashListener.handle end... date range is empty.");
                return;
            }

            try (InputStream in = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                // 解析报告
                GmwrManagerFlashBO managerFlashBO = managerFlashService.parseReport(propertyDTO, in, source);
                // 处理报告数据
                managerFlashService.handleManagerFlash(propertyDTO, managerFlashBO, dateRange);

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

        /**
         * 获取日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param operatorId  操作人 id
         * @return 日期范围
         * @author zc
         * @date 2025/7/25
         */
        private Long getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, int operatorId) {
            if (operatorId == 0) {
                // 系统下发
                LocalDate nowLocalDate = LocalDate.now(ZoneId.of(propertyDTO.getTimezone()));
                // 数据范围是上个月
                return Long.parseLong(DateTimeUtils.localDateToStr(nowLocalDate.minusMonths(1),
                        BaseConstant.DATE_FORMAT_YYYYMM));
            }
            // 手动导入
            Object dateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
            if (Objects.isNull(dateObj)) {
                return null;
            }
            return Long.parseLong(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(dateObj.toString(),
                    BaseConstant.DATE_FORMAT_YYYYMMDD), BaseConstant.DATE_FORMAT_YYYYMM));
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author zc
         * @date 2024/10/17
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("GmwrManagerFlashListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("GmwrManagerFlashListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.GM_WEEKLY_REPORT)) {
                log.warn("GmwrManagerFlashListener.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/10/17
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle Manager Flash current month last year 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 boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2025/8/7
         */
        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);
        }
    }