# JournalByCashierAndTransactionCodeServiceListener.java

    package cloud.wconnect.frontoffice.messagelistener.adjustment;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.exception.*;
    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.commonlib.util.UpdateLogUtil;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.parsereport.adjustment.IParseJournalByCashierAndTransactionCodeService;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.adjustment.IAdRequestService;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    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.Service;

    import java.io.IOException;
    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.*;
    import java.util.concurrent.TimeUnit;

    /**
     * @author lichen
     * @description Journal by Cashier and Transaction Code/service 报告处理
     * 同步当日酒店的Journal报告中Debit为负值的数据，用于自动生成Adjustment Form
     * @date 2023/4/3 18:11
     */
    @Slf4j
    @Service
    public class JournalByCashierAndTransactionCodeServiceListener {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private IAdRequestService adRequestService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private CommonService commonService;

        private final static String SUBJECT = EventSubjectEnum.JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_SERVICE.getSubject();
        private final static String BUSINESS = BusinessEnum.ADJUSTMENT_REQUESTS.getBusiness();
        private static final String KEY_PREFIX_FOR_MESSAGE = "wconnect:event:message:";

        /**
         * 处理报告数据
         *
         * @param event 事件
         * @author lichen
         * @date 2024/1/9
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            log.info("JournalByCashierAndTransactionCodeService.start");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }

            if (StringUtils.isBlank(event.getBody())) {
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);
            //获取租户标识
            String tenantAbbr = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            //查询资产
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbrName, tenantAbbr);
            if (Objects.isNull(propertyDTO) || !propertyDTO.getStatus()) {
                log.warn("JournalByCashierAndTransactionCodeService.end The property is close or not exist; propertyAbbr: {}", propertyAbbrName);
                return;
            }
            //校验是否开通功能
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.ADJUSTMENT_REQUESTS)) {
                log.warn("JournalByCashierAndTransactionCodeService.end... the property has not opened the adjustment function;property:{}", propertyAbbrName);
                return;
            }

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

            try {
                //获取日期范围
                LocalDate localDate = LocalDate.now(ZoneId.of(propertyDTO.getTimezone()));
                Map<String, Long> dateRange = Maps.newHashMap();
                dateRange.put(JobParameterDTO.START_DATE, DateTimeUtils.localDateToLong(localDate, propertyDTO.getTimezone()));
                dateRange.put(JobParameterDTO.END_DATE, DateTimeUtils.localDateToLong(localDate, propertyDTO.getTimezone()));
                //解析报告
                List<JournalDTO> journalDTOS = parseReport(eventBodyDTO, propertyDTO, dateRange);
                //处理报告数据
                adRequestService.handleReportData(propertyDTO, journalDTOS, 0, dateRange);
                log.info("JournalByCashierAndTransactionCodeService.end success");
            } catch (Exception e) {
                //发送预警邮件
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), eventBodyDTO.getPath());
                }
                log.error("Adjustment Handle Journal Report error;", e);

            }
        }

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

        /**
         * 解析report报告
         *
         * @param eventBodyDTO 事件对象
         * @param propertyDTO  资产对象
         * @param dateRange    日期范围
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO>
         * @author lichen
         * @date 2024/1/9
         */
        private List<JournalDTO> parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO, Map<String, Long> dateRange) {
            //获取source
            String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
            //解析报告
            try (InputStream fileInputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                Map<String, IParseJournalByCashierAndTransactionCodeService> parseServiceMap = applicationContext.getBeansOfType(IParseJournalByCashierAndTransactionCodeService.class);
                Collection<IParseJournalByCashierAndTransactionCodeService> parseServiceList = parseServiceMap.values();
                for (IParseJournalByCashierAndTransactionCodeService parser : parseServiceList) {
                    if (parser.supports(source)) {
                        return parser.parse(fileInputStream, propertyDTO, dateRange);
                    }
                }
            } catch (IOException e) {
                throw new ListenerException("File acquisition failure", e);
            }
            throw new ListenerException("not find report parser");
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            //主题
            String subject = "[Warning] - Handle Journal Report error";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

    }