# ArrivalsDetailedServiceListener.java

    package cloud.wconnect.frontoffice.messagelistener.badguest;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    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.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.badguest.BgReportTypeEnum;
    import cloud.wconnect.frontoffice.parsereport.badguest.IParseFileService;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.badguest.IBadGuestNotifyService;
    import cloud.wconnect.frontoffice.service.badguest.IBgReportLogService;
    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.Autowired;
    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 org.springframework.util.CollectionUtils;

    import java.io.IOException;
    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.*;
    import java.util.concurrent.TimeUnit;

    /**
     * @author lichen
     * @description Arrivals Detailed/service 报告处理
     * 同步各个酒店的Arrivals报告数据，根据入住客人的姓名，对比W-Connect中的客人黑名单，如果匹配到黑名单中的客人，则向酒店预警
     * @date 2023/3/23 13:59
     */
    @Slf4j
    @Component
    public class ArrivalsDetailedServiceListener {

        //subject
        private final static String SUBJECT = EventSubjectEnum.ARRIVALS_DETAILED_SERVICE.getSubject();
        //业务名称
        private final static String BUSINESS = BusinessEnum.GUESTS_BLACKLIST.getBusiness();
        //事件key
        private static final String KEY_PREFIX_FOR_MESSAGE = "wconnect:event:message:";
        //事件执行结果key
        private static final String KEY_PREFIX_FOR_PROCESSING = "wconnect:event:processing:";
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private IBadGuestNotifyService notifyService;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private IBgReportLogService bgReportLogService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private CommonService commonService;

        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            log.info("ArrivalsDetailedServiceListener.start....");
            if (!preventConcurrency(event.getMessageId())) {
                log.info("ArrivalsDetailedServiceListener.end, A machine has been executed");
                return;
            }

            //获取资产简称
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            List<String> propertyAbbrs = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = propertyAbbrs.get(0);
            //获取租户标识
            String tenantAbbr = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            //查询租户信息
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbrName, tenantAbbr);
            if (Objects.isNull(propertyDTO)) {
                log.warn("ArrivalsDetailedServiceListener.end The property is not exist; abbr name: {}", propertyAbbrName);
                return;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("ArrivalsDetailedServiceListener.end The property is off; abbr name: {}", propertyAbbrName);
                return;
            }

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

            //校验是否开通功能
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.GUEST_BLACK_LIST)) {
                log.warn("ArrivalsDetailedServiceListener.end... the property has not opened the DNR(Do Not Rent) function;property:{}", propertyAbbrName);
                return;
            }
            try {
                //解析报告中的数据
                List<GuestInHouseDTO> guestInHouseDTOS = parseReport(eventBodyDTO, propertyDTO, parser);
                if (CollectionUtils.isEmpty(guestInHouseDTOS)) {
                    log.info("ArrivalsDetailedServiceListener.end handle file finish,the guest in house is empty; abbr name : {}", propertyAbbrName);
                } else {
                    notifyService.notifyBadGuestCheckIn(guestInHouseDTOS, propertyDTO);
                }
                updateLastTime(propertyAbbrName);
                //保存报告处理成功的时间
                bgReportLogService.save(propertyDTO, BgReportTypeEnum.ARRIVALS_DETAILED_SERVICE.getType(), BaseConstant.ZERO);
                log.info("ArrivalsDetailedServiceListener.end");
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), event.getBody());
                }
                log.error("ArrivalsDetailedServiceListener handle error ", e);
            }
        }

        /**
         * @param messageId 消息事件 id
         * @return java.lang.Boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @description 防止并发操作
         * @author lichen
         * @date 2023/3/23 18:03
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    KEY_PREFIX_FOR_MESSAGE + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

        /**
         * 解析报告
         *
         * @param eventBodyDTO 事件体
         * @param propertyDTO  资产DTO
         * @param parser       解析器
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO>
         * @author lichen
         * @date 2026/1/26
         */
        private List<GuestInHouseDTO> parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO, IParseFileService parser) {
            String path = eventBodyDTO.getPath();
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                return parser.parse(inputStream, propertyDTO);
            } catch (IOException e) {
                throw new ListenerException("File acquisition failure", e);
            }
        }

        /**
         * 获取解析器
         *
         * @param source 来源
         * @return cloud.wconnect.frontoffice.parsereport.badguest.IParseFileService
         * @author lichen
         * @date 2026/1/26
         */
        private IParseFileService getParser(String source) {
            IParseFileService parser = null;
            Map<String, IParseFileService> parseMap = applicationContext.getBeansOfType(IParseFileService.class);
            for (IParseFileService bean : parseMap.values()) {
                if (bean.supports(source, BgReportTypeEnum.ARRIVALS_DETAILED_SERVICE.getType())) {
                    parser = bean;
                    break;
                }
            }
            return parser;
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            String subject = "[Warning] - Handle Arrivals Detailed/service error";
            //邮件内容
            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 abbrName 资产标识
         * @return void
         * @author lichen
         * @date 2023/5/20
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            redisTemplate.opsForValue().set(
                    KEY_PREFIX_FOR_PROCESSING + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }
    }