# PastReservationCreditLimitListener.java

    package cloud.wconnect.frontoffice.messagelistener.pastreservation;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    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.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.KeyPrefixEnum;
    import cloud.wconnect.frontoffice.cons.S3BucketFunctionCons;
    import cloud.wconnect.frontoffice.cons.pastreservation.PastReservationReportTypeCons;
    import cloud.wconnect.frontoffice.entity.pastreservation.PastReservationImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.pastreservation.CreditLimitInfoBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationCreditLimitService;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationImportLogService;
    import cloud.wconnect.frontoffice.service.pastreservation.report.listener.creditlimit.IPastReservationCreditLImitParse;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    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.beans.factory.annotation.Value;
    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.Component;

    import java.io.IOException;
    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;

    /**
     * Credit Limit 报告处理事件
     *
     * @author yyt
     * 2024/12/12
     */
    @Slf4j
    @Component
    public class PastReservationCreditLimitListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private IPastReservationImportLogService pastReservationImportLogService;
        @Resource
        private IPastReservationCreditLimitService pastReservationCreditLimitService;
        @Resource
        private CommonService commonService;

        @Value("${default.timezone}")
        private String defaultTimezone;

        private static final String SUBJECT = EventSubjectEnum.CREDIT_LIMIT.getSubject();

        private final String BUSINESS = BusinessEnum.PAST_RESERVATION.getBusiness();

        /**
         * 监听 credit limit 报告
         *
         * @author yyt
         * @date 2024/12/12
         */
        @Async
        @EventListener
        public void handleCreditLimitReport(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("PastReservationCreditLimitListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("PastReservationCreditLimitListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("PastReservationCreditLimitListener.end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            String tenantAbbrName = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            String propertyAbbrName = ((List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc())).get(0);
            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantAbbrName);
            if (Objects.isNull(property)) {
                log.warn("PastReservationCreditLimitListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("PastReservationCreditLimitListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }

            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if(!property.getPmsType().equals(source)){
                log.warn("PastReservationCreditLimitListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        property.getId(), property.getPmsType(), source);
                return;
            }

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.PAST_RESERVATION)) {
                log.warn("PastReservationCreditLimitListener.end... the property has not opened the past reservation function;property:{}", propertyAbbrName);
                return;
            }

            boolean importResult = true;
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            uid = Objects.isNull(uid) ? 0 : uid;
            Integer id = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Integer.parseInt(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());
            String path = eventBodyDTO.getPath();
            try {
                try (InputStream inputStream = amazonS3Service.getFile(path)) {
                    amazonS3Service.uploadFile(S3BucketFunctionCons.PAST_RESERVATION_IMPORT_RECORD, inputStream, path);
                }

                // 解析报告数据
                List<CreditLimitInfoBO> dataBO = parseReport(property, eventBodyDTO);
                pastReservationCreditLimitService.handleCreditLimitData(property, dataBO, uid);
            }catch (Exception e){
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("PastReservationCreditLimitListener.end... handle import credit limit report report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                int status = importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL;
                if (uid == 0) {
                    // 插入导入记录
                    pastReservationImportLogService.add(property.getId(), PastReservationReportTypeCons.CREDIT_LIMIT, status, path, uid);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 更新导入记录
                        PastReservationImportLog updateLog = new PastReservationImportLog().setId(id).setStatus(status).setUrl(path);
                        pastReservationImportLogService.updateById(updateLog);
                    } else {
                        // 插入导入记录
                        pastReservationImportLogService.add(property.getId(), PastReservationReportTypeCons.CREDIT_LIMIT, status, path, uid);
                    }
                }
            }
            log.info("PastReservationCreditLimitListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2024/12/12
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle Credit Limit Report Exception";
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, abbrName, content, path);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author yyt
         * @date 2024/12/12
         */
        private void updateLastTime(String abbrName) {
            jsonRedisTemplate.opsForValue().set(KeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                            StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

        /**
         * 解析报告数据
         *
         * @param property     资产
         * @param eventBodyDTO 事件体
         * @return 入住信息
         * @author yyt
         * @date 2024/12/12
         */
        private List<CreditLimitInfoBO> parseReport(PropertyDTO property, EventBodyDTO eventBodyDTO) throws IOException {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            List<CreditLimitInfoBO> dataBO = null;
            Map<String, IPastReservationCreditLImitParse> beansOfType = applicationContext.getBeansOfType(IPastReservationCreditLImitParse.class);
            for (IPastReservationCreditLImitParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(path)) {
                        dataBO = bean.parsReport(inputStream, property);
                    }
                    break;
                }
            }
            if (Objects.isNull(dataBO)) {
                throw new ListenerException("the source is not exist; source: " + source);
            }

            return dataBO;
        }

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

    }