# ClcArrivalListener.java

    package cloud.wconnect.frontoffice.messagelistener.clc;

    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.clc.ClcMissingReport;
    import cloud.wconnect.frontoffice.pojo.bo.clc.ArrivalBO;
    import cloud.wconnect.frontoffice.pojo.bo.clc.DataBO;
    import cloud.wconnect.frontoffice.pojo.dto.clc.ClcSchedulerDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.clc.IClcArrivalDetailedService;
    import cloud.wconnect.frontoffice.service.clc.IClcMissingReportService;
    import cloud.wconnect.frontoffice.service.clc.IClcSchedulerService;
    import cloud.wconnect.frontoffice.service.clc.arrival.IArrivalFileParse;
    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.collections.CollectionUtils;
    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.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * arrival 报告事件处理
     *
     * @author yyt
     * 2023/7/26
     */
    @Slf4j
    @Component
    public class ClcArrivalListener {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private ApplicationContext applicationContext;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private IClcMissingReportService clcMissingReportService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private IClcArrivalDetailedService clcArrivalDetailedService;
        @Resource
        private IClcSchedulerService clcSchedulerService;
        @Resource
        private CommonService commonService;

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

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

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

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

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

            if (!commonService.checkOpenFunction(property, FunctionIdConstant.CLC)) {
                log.warn("ClcArrivalListener.end... the property has not opened the clc function;property:{}", propertyAbbrName);
                return;
            }

            boolean importResult = true;
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());

            // 读取定时任务配置的数据范围
            Long dataDate = clcSchedulerService.getDateRange(property, ClcSchedulerDTO.MISSING_ARRIVAL_REPORT);
            Long date;
            if (uid == BaseConstant.ZERO) {
                date = dataDate;
            } else {
                Object dateObj = parameter.get(EventBodyParamEnum.DATE.getDesc());
                if (Objects.isNull(dateObj)) {
                    log.warn("ClcArrivalListener.end... the date is null, no processing required;property:{}", propertyAbbrName);
                    return;
                }

                date = Long.parseLong(dateObj.toString());
            }

            Long id = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Long.parseLong(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<ArrivalBO> dataBO = parseReport(property, date, eventBodyDTO, property.getTimezone(), parser);
                if (CollectionUtils.isNotEmpty(dataBO.getData())) {
                    clcArrivalDetailedService.handleArrivalData(property, uid, dataBO);
                }
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), event.getBody());
                }
                log.error("ClcArrivalListener.end... handle import arrival report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                long now = DateTimeUtils.nowTimestamp();
                // 系统自动导入
                if (Objects.isNull(id)) {
                    // 插入导入记录
                    clcMissingReportService.saveOrUpdateRewrite(new ClcMissingReport()
                            .setPropertyId(property.getId())
                            .setTheDate(DateTimeUtils.dateNow(property.getTimezone()).minusDays(1).toEpochSecond())
                            .setReportType(ClcMissingReport.REPORT_TYPE_ARRIVALS)
                            .setCreatedBy(BaseConstant.ZERO)
                            .setCreatedTime(now)
                            .setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL)
                            .setResolvedBy(0)
                            .setResolvedTime(0L)
                            .setUrl(path));
                } else {
                    String eventBusiness = parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc()).toString();
                    if (BUSINESS.equals(eventBusiness)) {
                        // 更新导入记录
                        ClcMissingReport updateLog = new ClcMissingReport();
                        updateLog.setId(id).setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                ReportImportResultCons.IMPORT_RESULT_FAIL).setUrl(path);

                        ClcMissingReport importLog = clcMissingReportService.getById(id);
                        if (importLog.getStatus() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                            // 如果是 修复中状态,
                            // 导入成功，更新解决人
                            // 导入失败，不更新解决人
                            updateLog.setResolvedBy(importResult ? uid : BaseConstant.ZERO);
                            updateLog.setResolvedTime(importResult ? now : BaseConstant.LONG_ZERO);
                            updateLog.setUrl(path);
                        }
                        clcMissingReportService.updateById(updateLog);
                    } else {
                        clcMissingReportService.saveOrUpdateRewrite(new ClcMissingReport()
                                .setPropertyId(property.getId())
                                .setTheDate(date)
                                .setReportType(ClcMissingReport.REPORT_TYPE_ARRIVALS)
                                .setStatus(importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                        ReportImportResultCons.IMPORT_RESULT_FAIL)
                                .setUrl(path)
                                .setCreatedBy(uid)
                                .setCreatedTime(now)
                                .setResolvedBy(BaseConstant.ZERO)
                                .setResolvedTime(BaseConstant.LONG_ZERO));
                    }
                }
            }
            log.info("ClcArrivalListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param path     文件路径
         * @author yyt
         * @date 2023/7/27
         */
        private void sendAlertEmail(String abbrName, String content, String path) {
            String subject = "[Warning] - Handle Arrival 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/27
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            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 入住信息
         * @author yyt
         * @date 2023/7/27
         */
        private DataBO<ArrivalBO> parseReport(PropertyDTO property, Long date, EventBodyDTO eventBodyDTO, String timeZone, IArrivalFileParse parser) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();

            DataBO<ArrivalBO> dataBO = new DataBO<>();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String timezone = property.getTimezone();

            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                List<ArrivalBO> arrivalBOList = parser.parsReport(property.getId(), date, inputStream, timeZone);
                if (CollectionUtils.isNotEmpty(arrivalBOList)) {
                    dataBO.setDate(dateTimeFormatter.format(DateTimeUtils.toZonedDateTime(date, timezone)));
                    dataBO.setData(arrivalBOList);
                }
            } catch (Exception e) {
                throw new ListenerException("parse report error; source: " + source + ", path: " + path, e);
            }
            return dataBO;
        }

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

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

    }