# TaOtaListener.java

    package cloud.wconnect.finance.messagelistener.ta;

    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    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.finance.cons.BusinessEnum;
    import cloud.wconnect.finance.cons.EventSubjectEnum;
    import cloud.wconnect.finance.cons.S3BucketFunctionCons;
    import cloud.wconnect.finance.cons.ta.TaNotifyTypeEnum;
    import cloud.wconnect.finance.cons.ta.TaReportTypeCons;
    import cloud.wconnect.finance.pojo.bo.ta.ota.TaOtaBO;
    import cloud.wconnect.finance.pojo.bo.ta.ota.TaOtaListBO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.ta.ITaCompareOtaService;
    import cloud.wconnect.finance.service.ta.ITaImportLogService;
    import cloud.wconnect.finance.service.ta.ITaOtaService;
    import cloud.wconnect.finance.service.ta.ITaSchedulerService;
    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.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.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * 事件处理：OTA for Travelliance (TA) Commission
     *
     * @author zc
     * @date 2023/07/19
     */
    @Slf4j
    @Component
    public class TaOtaListener {
        @Resource
        private ITaOtaService taOtaService;
        @Resource
        private ITaCompareOtaService taCompareOtaService;
        @Resource
        private ITaImportLogService importLogService;
        @Resource
        private ITaSchedulerService schedulerService;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private CommonService commonService;
        @Value("${default.timezone}")
        private String defaultTimezone;

        private static final String SUBJECT = EventSubjectEnum.OTA.getSubject();
        private static final String BUSINESS = BusinessEnum.TA.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2023/7/19
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            log.info("TaOtaListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("TaOtaListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("TaOtaListener.handle end... event body is blank.");
                return;
            }

            // 解析事件体
            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String tenantSymbol = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbr = abbrNameList.get(0);

            PropertyDTO propertyDTO = getEffectiveProperty(tenantSymbol, propertyAbbr);
            if (Objects.isNull(propertyDTO)) {
                return;
            }
            String source = parameter.get(EventBodyParamEnum.SOURCE.getDesc()).toString();

            // 校验事件 PMS 类型是否与资产配置匹配
            if (!StringUtils.equals(propertyDTO.getPmsType(), source)) {
                log.warn("TaOtaListener.handle end... Property not support this PMS type, " +
                                "property:{}, supportPMSType:{}, currentPMSType:{}",
                        propertyDTO.getAbbr(), propertyDTO.getPmsType(), source);
                return;
            }

            Long logId = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Long.parseLong(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());

            int operatorId = Integer.parseInt(parameter.get(EventBodyParamEnum.UID.getDesc()).toString());
            String path = eventBodyDTO.getPath();

            // 获取数据日期
            long dataDate = getDataDate(propertyDTO, parameter, operatorId);

            // 处理是否成功
            boolean handleResult = true;
            try (InputStream in = amazonS3Service.getFile(path)) {
                // 解析报告
                List<TaOtaListBO> taOtaList = taOtaService.parseReport(propertyDTO, source, in);

                TaOtaBO taOtaBO = TaOtaBO.builder()
                        .dataDate(DateTimeUtils.timestampToStr(dataDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone()))
                        .list(taOtaList).build();
                // 处理报告
                taCompareOtaService.handleOtaReport(propertyDTO, taOtaBO);

                log.info("TaOtaListener.handle end...");
            } catch (Exception e) {
                handleResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), eventBodyDTO.getPath());
                }

                log.error("TaOtaListener.handle end... Process error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (operatorId == 0) {
                    updateLastTime(propertyAbbr);
                }

                // 上传报告，用于日志下载报告
                uploadReport(path);

                int importResult = handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                        ReportImportResultCons.IMPORT_RESULT_FAIL;

                // 系统下发
                if (Objects.isNull(logId)) {
                    // 系统下发，新增导入日志
                    importLogService.add(propertyDTO, dataDate, TaReportTypeCons.OTA,
                            importResult, operatorId, path);
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        importLogService.update(logId, handleResult, operatorId, path);
                    } else {
                        importLogService.add(propertyDTO, dataDate, TaReportTypeCons.OTA,
                                importResult, operatorId, path);
                    }
                }
            }
        }

        /**
         * 上传报告，用于日志下载报告
         *
         * @param path S3 路径
         * @author zc
         * @date 2024/8/22
         */
        private void uploadReport(String path) {
            // 上传报告，用于日志下载报告
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                amazonS3Service.uploadFile(S3BucketFunctionCons.TA_IMPORT_RECORD, inputStream, path);
            } catch (Exception e) {
                log.error("TaOtaListener.handle end... Upload TA - OTA report exception.", e);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author zc
         * @date 2024/5/1
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("TaOtaListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("TaOtaListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.TRAVELLIANCE_COMMISSION)) {
                log.warn("TaOtaListener.handle end... The property:{} has not opened this function", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 获取报告数据日期
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param operatorId  操作人 id
         * @return 数据日期
         * @author zc
         * @date 2024/3/15
         */
        private long getDataDate(PropertyDTO propertyDTO, Map<String, Object> parameter, int operatorId) {
            /*
             * 处理数据日期范围：
             * 1、自动导入报告时，取调度配置的数据日期范围
             * 2、手动导入报告（解决异常、手动导入）时，取事件体的日期范围
             */
            if (operatorId == 0) {
                Map<String, Long> dateRange = schedulerService.getDateRange(propertyDTO,
                        TaNotifyTypeEnum.MISSING_REPORT_OTA.getType());
                return dateRange.get(JobParameterDTO.START_DATE);
            }
            Object theDateObj = parameter.get(EventBodyParamEnum.DATE.getDesc());
            return Long.parseLong(theDateObj.toString());
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @param s3Key            文件路径
         * @author zc
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Handle the TA OTA report Exception.";
            String content = "Handle the TA OTA report Exception." + exceptionMessage;
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, content, s3Key);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/2/8
         */
        private Boolean preventConcurrency(String messageId) {
            return jsonRedisTemplate.opsForValue().setIfAbsent(EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc()
                    + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), "."), 0L, 1, TimeUnit.DAYS);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author zc
         * @date 2023/6/1
         */
        private void updateLastTime(String abbrName) {
            jsonRedisTemplate.opsForValue().set(EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_PROCESSING.getDesc()
                            + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }
    }