# JournalListener.java

    package cloud.wconnect.finance.messagelistener.chargeback;

    import cloud.wconnect.commonlib.cons.*;
    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.finance.cons.BusinessEnum;
    import cloud.wconnect.finance.cons.EventSubjectEnum;
    import cloud.wconnect.finance.cons.S3BucketFunctionCons;
    import cloud.wconnect.finance.pojo.bo.chargeback.JournalListBO;
    import cloud.wconnect.finance.pojo.dto.chargeback.CbCaseSchedulerDTO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.chargeback.ICbCaseSchedulerJobService;
    import cloud.wconnect.finance.service.chargeback.ICbJournalImportLogService;
    import cloud.wconnect.finance.service.chargeback.ICbJournalService;
    import cloud.wconnect.finance.service.parsereport.chargeback.IJournalFileParse;
    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;

    /**
     * Journal
     *
     * @author yyt
     * 2023/9/8
     */
    @Slf4j
    @Component
    public class JournalListener {

        @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 ICbJournalImportLogService cbJournalImportLogService;
        @Resource
        private ICbJournalService cbJournalService;
        @Resource
        private ICbCaseSchedulerJobService schedulerJobService;
        @Resource
        private CommonService commonService;

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

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

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

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

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

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

            boolean importResult = true;
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            // 默认前一天
            Long date = schedulerJobService.getDateRange(property, CbCaseSchedulerDTO.MISSING_JOURNAL_REPORT);
            if (uid != 0) {
                Object dateObj = parameter.get(EventBodyParamEnum.DATE.getDesc());
                if (Objects.isNull(dateObj)) {
                    log.warn("JournalListener.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.CHARGEBACK_IMPORT_RECORD, inputStream, path);
                }

                // 解析报告数据
                List<JournalListBO> journals = parseReport(property, date, eventBodyDTO);
                String dateStr = DateTimeUtils.toZonedDateTime(date, property.getTimezone())
                        .format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                cbJournalService.handleJournalData(property, uid, dateStr, journals);
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), event.getBody());
                }
                log.error("JournalListener.end... handle import journal report error.", e);
            } finally {
                // 自动导入报告时插入处理时机，用于定时检查报告缺失逻辑
                if (uid == 0) {
                    updateLastTime(propertyAbbrName);
                }

                if (Objects.isNull(id)) {
                    // 生成导入记录
                    cbJournalImportLogService.saveRecord(property.getId(), date,
                            importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                    ReportImportResultCons.IMPORT_RESULT_FAIL, path, uid);
                } else {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        // 修改导入记录状态
                        cbJournalImportLogService.updateLogStatus(id, importResult, path, uid);
                    } else {
                        cbJournalImportLogService.saveRecord(property.getId(), date,
                                importResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS :
                                        ReportImportResultCons.IMPORT_RESULT_FAIL, path, uid);
                    }
                }
            }
            log.info("JournalListener.end...");
        }

        /**
         * 发送预警邮件
         *
         * @param abbrName property abbr
         * @param content  邮件内容
         * @param s3Key    文件路径
         * @author yyt
         * @date 2023/9/8
         */
        private void sendAlertEmail(String abbrName, String content, String s3Key) {
            String subject = "[Warning] - Handle Journal 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, s3Key);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author yyt
         * @date 2023/9/8
         */
        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)));
        }

        /**
         * 解析报告数据
         *
         * @param property     资产
         * @param date         日期
         * @param eventBodyDTO 事件体
         * @return journal 数据
         * @author yyt
         * @date 2023/9/8
         */
        private List<JournalListBO> parseReport(PropertyDTO property, Long date, EventBodyDTO eventBodyDTO) {
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            String path = eventBodyDTO.getPath();
            List<JournalListBO> journalList = null;
            Map<String, IJournalFileParse> beansOfType = applicationContext.getBeansOfType(IJournalFileParse.class);
            for (IJournalFileParse bean : beansOfType.values()) {
                if (bean.supports(source)) {
                    try (InputStream inputStream = amazonS3Service.getFile(path)) {
                        journalList = bean.parsReport(property, inputStream, date);
                        break;
                    } catch (Exception e) {
                        throw new ListenerException("parse journal report error", e);
                    }
                }
            }
            if (Objects.isNull(journalList)) {
                throw new ListenerException("the source is not exist; source: " + source);
            }

            return journalList;
        }

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

    }