# ClcGuestInHouseListener.java

    package cloud.wconnect.frontoffice.messagelistener.clc;

    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.entity.clc.ClcGuestInhImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.clc.DataBO;
    import cloud.wconnect.frontoffice.pojo.bo.clc.GuestInHouseBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhImportLogService;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhService;
    import cloud.wconnect.frontoffice.service.clc.guestinhouse.IGuestInHouseParse;
    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.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
     * 2023/7/28
     */
    @Slf4j
    @Component
    public class ClcGuestInHouseListener {

        @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 IClcGuestInhImportLogService clcGuestInhImportLogService;
        @Resource
        private IClcGuestInhService clcGuestInhService;
        @Resource
        private CommonService commonService;

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

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

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

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

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

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.CLC)) {
                log.warn("ClcGuestInHouseListener.end... the property has not opened the clc 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.CLC_IMPORT_RECORD, inputStream, path);
                }

                // 解析报告数据
                DataBO<GuestInHouseBO> dataBO = parseReport(property, eventBodyDTO, parser);
                if (Objects.nonNull(dataBO)) {
                    clcGuestInhService.handleGuestInHouseData(property, uid, dataBO.getData());
                }
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), path);
                }
                log.error("ClcGuestInHouseListener.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) {
                    // 插入导入记录
                    clcGuestInhImportLogService.add(property.getId(), status, path, uid);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 更新导入记录
                        ClcGuestInhImportLog updateLog = new ClcGuestInhImportLog().setId(id).setStatus(status).setUrl(path);
                        clcGuestInhImportLogService.updateById(updateLog);
                    } else {
                        // 插入导入记录
                        clcGuestInhImportLogService.add(property.getId(), status, path, uid);
                    }
                }
            }
            log.info("ClcGuestInHouseListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/7/28
         */
        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 2023/7/28
         */
        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 source 来源
         * @return cloud.wconnect.frontoffice.service.clc.guestinhouse.IGuestInHouseParse
         * @author lichen
         * @date 2026/1/26
         */
        private IGuestInHouseParse getParser(String source) {
            IGuestInHouseParse parser = null;
            Map<String, IGuestInHouseParse> beansOfType = applicationContext.getBeansOfType(IGuestInHouseParse.class);
            for (IGuestInHouseParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    parser = bean;
                    break;
                }
            }
            return parser;
        }

        /**
         * 解析报告数据
         *
         * @param property     资产
         * @param eventBodyDTO 事件体
         * @return 入住信息
         * @author yyt
         * @date 2023/7/28
         */
        private DataBO<GuestInHouseBO> parseReport(PropertyDTO property, EventBodyDTO eventBodyDTO, IGuestInHouseParse parser) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            DataBO<GuestInHouseBO> dataBO;
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                List<GuestInHouseBO> guestInHouses = parser.parsReport(inputStream, property);
                dataBO = new DataBO<>();
                dataBO.setData(guestInHouses);
            } catch (Exception e) {
                throw new ListenerException("parse report error; source: " + source + "; path: " + path, e);
            }

            return dataBO;
        }

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

    }