# OutOfOrderListener.java

    package cloud.wconnect.frontoffice.messagelistener.oooroom;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    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.oooroom.OooImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.clc.DataBO;
    import cloud.wconnect.frontoffice.pojo.bo.oooroom.OutOfOrderBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.oooroom.IOooImportLogService;
    import cloud.wconnect.frontoffice.service.oooroom.IOooRoomService;
    import cloud.wconnect.frontoffice.service.oooroom.outoforder.IOutOfOrderFileParse;
    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.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * Out Of Order
     *
     * @author yyt
     * 2023/8/9
     */
    @Slf4j
    @Component
    public class OutOfOrderListener {

        @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 IOooImportLogService oooImportLogService;
        @Resource
        private IOooRoomService oooRoomService;
        @Resource
        private CommonService commonService;

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

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

        private static final String BUSINESS = BusinessEnum.OUT_OF_ORDER.getBusiness();

        /**
         * 监听 out of order  报告
         *
         * @author yyt
         * @date 2023/8/9
         */
        @Async
        @EventListener
        public void handleOutOfOrderReport(SnsHttpEvent event) {
            // 校验 subject
            if (!StringUtils.equals(event.getSubject(), SUBJECT)) {
                return;
            }
            log.info("OutOfOrderListener.start...");
            // 防止并发
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("OutOfOrderListener.end... a machine has been executed.");
                return;
            }
            // 校验 事件体 信息
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("OutOfOrderListener.end... event body is blank.");
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();

            List<String> propertyAbbrNames = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = propertyAbbrNames.get(0);
            String tenantAbbrName = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            PropertyDTO property = propertyInternalService.getOne(propertyAbbrName, tenantAbbrName);
            if (Objects.isNull(property)) {
                log.warn("OutOfOrderListener.end... the property is not exist;property:{}", propertyAbbrName);
                return;
            }
            if (!property.getStatus()) {
                log.warn("OutOfOrderListener.end... the property is closed;property:{}", propertyAbbrName);
                return;
            }

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

            IOutOfOrderFileParse parser = getParser(source);
            if (Objects.isNull(parser)) {
                log.warn("OutOfOrderListener.handle end...parser not find, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        property.getId(), property.getPmsType(), source);
                return;
            }

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.OOO_ROOM)) {
                log.warn("OutOfOrderListener.end... the property has not opened the ooo room function;property:{}", propertyAbbrName);
                return;
            }

            boolean importResult = true;
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            Long date = null;
            if (uid == 0) {
                date = DateTimeUtils.dateNowTimestamp(property.getTimezone());
            } else {
                Object dateObj = parameter.get(EventBodyParamEnum.DATE.getDesc());
                if (Objects.isNull(dateObj)) {
                    log.warn("OutOfOrderListener.end... the date is null, no processing required;property:{}", propertyAbbrName);
                    return;
                }
                date = Long.parseLong(dateObj.toString());
            }

            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.OOO_ROOM_IMPORT_RECORD, inputStream, path);
                }

                // 解析报告数据
                DataBO<OutOfOrderBO> dataBO = parseReport(property, date, eventBodyDTO, property.getTimezone(), parser);
                oooRoomService.handleOooRoomData(property, uid, dataBO);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("OutOfOrderListener.end... handle import out of order report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                long now = DateTimeUtils.nowTimestamp();
                // 系统自动导入
                if (Objects.isNull(id)) {
                    // 生成导入记录
                    oooImportLogService.saveRecord(property.getId(), date,
                            importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                    ReportImportResultCons.IMPORT_RESULT_FAIL, path, BaseConstant.ZERO);
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        OooImportLog update = new OooImportLog();
                        update.setId(id).setUrl(path)
                                .setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                        ReportImportResultCons.IMPORT_RESULT_FAIL);

                        OooImportLog importLog = oooImportLogService.getById(id);
                        if (importLog.getStatus() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                            update.setResolvedBy(importResult ? uid : BaseConstant.ZERO)
                                    .setResolvedTime(importResult ? now : BaseConstant.LONG_ZERO);
                        }

                        oooImportLogService.updateById(update);
                    } else {
                        oooImportLogService.saveRecord(property.getId(), date,
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                        ReportImportResultCons.IMPORT_RESULT_FAIL, path, uid);
                    }
                }
            }
            log.info("OutOfOrderListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/8/9
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle Out Of Order 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/8/9
         */
        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 date         日期
         * @param eventBodyDTO 事件体
         * @param timeZone     时区
         * @param parser       解析器
         * @return ooo 数据
         * @author yyt
         * @date 2023/8/9
         */
        private DataBO<OutOfOrderBO> parseReport(PropertyDTO property, Long date, EventBodyDTO eventBodyDTO, String timeZone, IOutOfOrderFileParse parser) {
            String path = eventBodyDTO.getPath();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String timezone = property.getTimezone();

            DataBO<OutOfOrderBO> dataBO = new DataBO<>();
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                List<OutOfOrderBO> outOfOrderBOList = parser.parsReport(property.getId(), inputStream, timeZone);
                dataBO.setDate(dateTimeFormatter.format(DateTimeUtils.toZonedDateTime(date, timezone)));
                dataBO.setData(outOfOrderBOList);
            } catch (Exception e) {
                throw new ListenerException("parse out of order report error", e);
            }

            return dataBO;
        }

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

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return true / false
         * @author yyt
         * @date 2023/8/9
         */
        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);
        }

    }