# GuestsInHouseComplimentaryListener.java

    package cloud.wconnect.frontoffice.messagelistener.comproom;

    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.redis.PropertyBusinessDateRedisService;
    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.entity.comproom.CompRoomReportLog;
    import cloud.wconnect.frontoffice.parsereport.comproom.IParseGuestsInHouseComplimentary;
    import cloud.wconnect.frontoffice.pojo.bo.comproom.GuestsInHouseComplimentaryBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomComplimentaryService;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomReportLogService;
    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.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 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;

    /**
     * 处理Guests In-House Complimentary报告的监听器
     * Guests In-House Complimentary报告中包含酒店免费房间的详细记录
     * 报告预估的下发时间：9:30 AM、11:30 AM、11:30 PM
     * 下发数据规则：当天数据
     *
     * @author lichen
     * @date 2023/8/4
     */
    @Slf4j
    @Component
    public class GuestsInHouseComplimentaryListener {

        //subject
        private final static String SUBJECT = EventSubjectEnum.GUESTS_IN_HOUSE_COMPLIMENTARY.getSubject();
        //业务名称
        private final static String BUSINESS = BusinessEnum.COMP_ROOM.getBusiness();

        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private ICompRoomComplimentaryService compRoomComplimentaryService;
        @Autowired
        private ICompRoomReportLogService reportLogService;
        @Resource
        private CommonService commonService;
        @Autowired
        private PropertyBusinessDateRedisService propertyBusinessDateRedisService;

        /**
         * 监听器
         *
         * @param event 事件
         * @return void
         * @author lichen
         * @date 2023/8/7
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            //获取资产简称
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);
            //获取租户标识
            String tenantAbbr = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            //远程调用basic模块查询资产信息
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbrName, tenantAbbr);
            if (Objects.isNull(propertyDTO) || !propertyDTO.getStatus()) {
                return;
            }

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

            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.COMP_ROOM)) {
                log.warn("GuestsInHouseComplimentaryListener.end... the property has not opened the comp room function;property:{}", propertyAbbrName);
                return;
            }
            // 获取有效的业务时间
            Long effectiveBusinessDate = propertyBusinessDateRedisService.getEffectiveBusinessDate(propertyDTO.getId(), propertyDTO.getTimezone());
            if(Objects.isNull(effectiveBusinessDate)){
                log.warn("GuestsInHouseComplimentaryListener.end... the property has not effective business date;property:{}", propertyAbbrName);
                return;
            }

            try {
                //解析报告中的数据
                List<GuestsInHouseComplimentaryBO> boList = parseReport(eventBodyDTO);
                //处理报告数据
                compRoomComplimentaryService.handleGuestsInHouseComplimentaryData(propertyDTO, boList, effectiveBusinessDate);
                //更新报告处理时间
                reportLogService.save(propertyDTO, CompRoomReportLog.REPORT_TYPE_GUESTS_IN_HOUSE_COMPLIMENTARY, 0);
                //更新缓存中的时间
                updateLastTime(propertyAbbrName);
            } catch (Exception e) {
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("handle import guest in house complimentary report error ", e);
            }
        }

        /**
         * 解析报告中的数据
         *
         * @param eventBodyDTO 事件参数对象
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.bo.comproom.GuestsInHouseComplimentaryBO>
         * @author lichen
         * @date 2023/8/7
         */
        private List<GuestsInHouseComplimentaryBO> parseReport(EventBodyDTO eventBodyDTO) {
            try (InputStream inputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                Map<String, IParseGuestsInHouseComplimentary> parseMap = applicationContext.getBeansOfType(IParseGuestsInHouseComplimentary.class);
                Collection<IParseGuestsInHouseComplimentary> parseList = parseMap.values();
                for (IParseGuestsInHouseComplimentary parser : parseList) {
                    String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
                    if (parser.supports(source)) {
                        return parser.parse(inputStream);
                    }
                }
            } catch (IOException e) {
                throw new ListenerException("File acquisition failure", e);
            }
            throw new ListenerException("not find report parser");
        }

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

        /**
         * 发送预警邮件
         *
         * @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 Guest In House Complimentary Report Exception";
            //邮件内容
            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/8/7
         */
        private void updateLastTime(String abbrName) {
            redisTemplate.opsForValue().set(KeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc() +
                            StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

    }