# ReservationsMadeYesterdayServiceListener.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.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * Reservations – made Yesterday/service 报告处理
     *
     * @author lichen
     * @date 2023/12/28
     */
    @Slf4j
    @Component
    public class ReservationsMadeYesterdayServiceListener {

        //subject
        private final static String SUBJECT = EventSubjectEnum.RESERVATIONS_MADE_YESTERDAY_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("ReservationsMadeYesterdayServiceListener.start....");
            if (!preventConcurrency(event.getMessageId())) {
                log.info("ReservationsMadeYesterdayServiceListener.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("ReservationsMadeYesterdayServiceListener.end The property is not exist; abbr name: {}", propertyAbbrName);
                return;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("ReservationsMadeYesterdayServiceListener.end The property is off; abbr name: {}", propertyAbbrName);
                return;
            }

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

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

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return java.lang.Boolean
         * @author lichen
         * @date 2023/12/28
         */
        private Boolean preventConcurrency(String messageId) {
            return redisTemplate.opsForValue().setIfAbsent(
                    KEY_PREFIX_FOR_MESSAGE + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."),
                    0L, 1, TimeUnit.DAYS);
        }

        /**
         * 解析report报告
         *
         * @param eventBodyDTO 事件DTO
         * @param propertyDTO  资产DTO
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO>
         * @author lichen
         * @date 2023/12/28
         */
        private List<GuestInHouseDTO> parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO) {
            String path = eventBodyDTO.getPath();
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                Map<String, IParseFileService> beanName2Class = applicationContext.getBeansOfType(IParseFileService.class);
                Collection<IParseFileService> parseList = beanName2Class.values();
                for (IParseFileService parser : parseList) {
                    String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
                    if (parser.supports(source, BgReportTypeEnum.RESERVATIONS_MADE_YESTERDAY_SERVICE.getType())) {
                        return parser.parse(inputStream, propertyDTO);
                    }
                }
            } catch (IOException e) {
                throw new ListenerException("File acquisition failure", e);
            }
            throw new ListenerException("not find report 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] - Handel Reservations – made Yesterday/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)));
        }

    }