# PastReservationGuestInHouseListener.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.GuestInHouseBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationImportLogService;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationOpGuestinHouseService;
    import cloud.wconnect.frontoffice.service.pastreservation.report.listener.guestinhouse.IPastReservationGuestInHouseParse;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    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 jakarta.annotation.Resource;

    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;

    /**
     * Guest In House 报告处理事件
     *
     * @author yyt
     * 2024/10/3
     */
    @Slf4j
    @Component
    public class PastReservationGuestInHouseListener {

        @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 IPastReservationOpGuestinHouseService pastReservationOpGuestinHouseService;
        @Resource
        private CommonService commonService;

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

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

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

        /**
         * 监听 guest in house 报告
         *
         * @author yyt
         * @date 2024/10/3
         */
        @Async
        @EventListener
        public void handleGuestInHouseReport(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("PastReservationGuestInHouseListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("PastReservationGuestInHouseListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("PastReservationGuestInHouseListener.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("PastReservationGuestInHouseListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("PastReservationGuestInHouseListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }

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

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.PAST_RESERVATION)) {
                log.warn("PastReservationGuestInHouseListener.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<GuestInHouseBO> dataBO = parseReport(property, eventBodyDTO, parser);
                pastReservationOpGuestinHouseService.handleGuestInHouseData(property, dataBO, uid);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("PastReservationGuestInHouseListener.end... handle import guest in house 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.GUEST_IN_HOUSE, 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.GUEST_IN_HOUSE, status, path, uid);
                    }
                }
            }
            log.info("PastReservationGuestInHouseListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2024/10/3
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle Guest In House 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/10/3
         */
        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 事件体
         * @param parser       解析器
         * @return 入住信息
         * @author yyt
         * @date 2024/10/3
         */
        private List<GuestInHouseBO> parseReport(PropertyDTO property, EventBodyDTO eventBodyDTO, IPastReservationGuestInHouseParse parser) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                return parser.parsReport(inputStream, property);
            } catch (Exception e) {
                throw new ListenerException("parse report error; source: " + source, e);
            }
        }

        /**
         * 获取解析器
         *
         * @param source 来源
         * @return cloud.wconnect.frontoffice.service.pastreservation.report.listener.guestinhouse.IPastReservationGuestInHouseParse
         * @author lichen
         * @date 2026/1/26
         */
        private IPastReservationGuestInHouseParse getParser(String source) {
            IPastReservationGuestInHouseParse parser = null;
            Map<String, IPastReservationGuestInHouseParse> beansOfType = applicationContext.getBeansOfType(IPastReservationGuestInHouseParse.class);
            for (IPastReservationGuestInHouseParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    parser = bean;
                    break;
                }
            }
            return parser;
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author yyt
         * @date 2024/10/3
         */
        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);
        }

    }