# SalesSourceOperatingStatisticsDailyPdfListener.java

    package cloud.wconnect.workperformance.messagelistener.mor;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    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.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.cons.S3BucketFunctionCons;
    import cloud.wconnect.workperformance.cons.operatingstatisticsdaily.OperatingStatisticsDatasourceEnum;
    import cloud.wconnect.workperformance.pojo.bo.mor.sales.SalesSourceOperatingStatisticsListBO;
    import cloud.wconnect.workperformance.pojo.dto.mor.sales.SalesImportReportDTO;
    import cloud.wconnect.workperformance.pojo.dto.pdf.OperatingStatisticsDailyPdfDTO;
    import cloud.wconnect.workperformance.pojo.dto.pdf.OperatingStatisticsPdfDTO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.mor.ISalesImportLogService;
    import cloud.wconnect.workperformance.service.mor.ISalesService;
    import cloud.wconnect.workperformance.service.pdf.DailyOperatingStatisticsParser;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    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.util.*;
    import java.util.concurrent.TimeUnit;
    import java.util.stream.Collectors;

    /**
     * 事件处理：Operating Statistics 报告 for Operating Statistics Daily PDF
     *
     * @author lichen
     * @date 2025/10/8
     */
    @Slf4j
    @Component
    public class SalesSourceOperatingStatisticsDailyPdfListener {
        @Resource
        private ISalesService salesService;
        @Resource
        private ISalesImportLogService importLogService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private DailyOperatingStatisticsParser dailyOperatingStatisticsParser;
        @Resource
        private CommonService commonService;

        private static final String SUBJECT = EventSubjectEnum.ACCOUNTING_OPERATING_STATISTICS_PDF.getSubject();
        private static final String BUSINESS = BusinessEnum.MOR_SALES.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件
         * @author lichen
         * @date 2025/10/8
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("SalesSourceOperatingStatisticsDailyPdfListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("SalesSourceOperatingStatisticsDailyPdfListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SalesSourceOperatingStatisticsDailyPdfListener.handle end... event body is blank.");
                return;
            }

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

            // 获取有效的资产数据
            List<PropertyDTO> propertyDTOList = listEffectiveProperty(tenantSymbol, propertyAbbrList);
            if (CollectionUtils.isEmpty(propertyDTOList)) {
                log.warn("SalesSourceOperatingStatisticsDailyPdfListener.handle end... propertyDTOList is empty.");
                return;
            }

            String path = eventBodyDTO.getPath();

            // 处理是否成功
            boolean handleResult = true;
            Map<Integer, Integer> propertyId2DataUpdateResult = new HashMap<>();
            Map<Integer, List<Long>> propertyId2DateRange = new HashMap<>();
            try (InputStream in = amazonS3Service.getFile(path)) {
                // 解析报告
                List<OperatingStatisticsPdfDTO> pdfDTOList = dailyOperatingStatisticsParser.parse(in);
                if (CollectionUtils.isNotEmpty(pdfDTOList)) {
                    // 转化为BO
                    List<SalesSourceOperatingStatisticsListBO> boList = dto2Bo(pdfDTOList);

                    // 获取资产对应的数据范围
                    propertyId2DateRange = getDateRangeMap(propertyDTOList, boList);

                    // 处理报告数据
                    propertyId2DataUpdateResult = salesService.handleOperatingStatistics(propertyDTOList, boList, 0, propertyId2DateRange,
                            OperatingStatisticsDatasourceEnum.PDF.getValue());
                }
                log.info("SalesSourceOperatingStatisticsDailyPdfListener.handle end...");
            } catch (Exception e) {
                handleResult = false;
                String propertyAbbr = propertyAbbrList.stream().sorted().collect(Collectors.joining(","));
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), path);
                }

                log.error("SalesSourceOperatingStatisticsDailyPdfListener.handle end... Process error.", e);
            } finally {
                // 上传报告，用于日志下载报告
                uploadReport(path);

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

                // 系统下发，新增导入日志
                importLogService.addBatch(propertyDTOList, propertyId2DateRange, SalesImportReportDTO.REPORT_TYPE_OPERATING, importResult,
                        0, path, propertyId2DataUpdateResult);
            }
        }

        /**
         * DTO转BO
         *
         * @param dtoList 数据集合
         * @return java.util.List<cloud.wconnect.workperformance.pojo.bo.mor.sales.SalesSourceOperatingStatisticsListBO>
         * @author lichen
         * @date 2025/10/8
         */
        public List<SalesSourceOperatingStatisticsListBO> dto2Bo(List<OperatingStatisticsPdfDTO> dtoList) {
            ArrayList<SalesSourceOperatingStatisticsListBO> list = Lists.newArrayList();

            for (OperatingStatisticsPdfDTO dto : dtoList) {
                List<OperatingStatisticsDailyPdfDTO> dailyPdfList = dto.getContent();
                for (OperatingStatisticsDailyPdfDTO dailyPdf : dailyPdfList) {
                    SalesSourceOperatingStatisticsListBO operatingStatisticsListBO = new SalesSourceOperatingStatisticsListBO();
                    operatingStatisticsListBO.setProperty(dto.getHotel());
                    operatingStatisticsListBO.setTheDay(dailyOperatingStatisticsParser.formatDate(dailyPdf.getDate()));
                    operatingStatisticsListBO.setTotalRev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getTotal_rev()));
                    list.add(operatingStatisticsListBO);
                }
            }
            return list;
        }

        /**
         * 上传报告，用于日志下载报告
         *
         * @param path S3 路径
         * @return void
         * @author lichen
         * @date 2025/10/8
         */
        private void uploadReport(String path) {
            // 上传报告，用于日志下载报告
            try (InputStream inputStream = amazonS3Service.getFile(path)) {
                amazonS3Service.uploadFile(S3BucketFunctionCons.SALES_IMPORT_RECORD, inputStream, path);
            } catch (Exception e) {
                log.error("SalesSourceOperatingStatisticsDailyPdfListener.handle end... Upload Operating statistics report exception.", e);
            }
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol     租户标识
         * @param propertyAbbrList 资产标识
         * @return java.util.List<cloud.wconnect.commonlib.pojo.dto.PropertyDTO>
         * @author lichen
         * @date 2025/10/8
         */
        private List<PropertyDTO> listEffectiveProperty(String tenantSymbol, List<String> propertyAbbrList) {
            if (CollectionUtils.isEmpty(propertyAbbrList)) {
                return Collections.emptyList();
            }

            // 获取资产数据
            return propertyInternalService.getProperty(propertyAbbrList, tenantSymbol).stream().filter(item ->
                    item.getStatus() && commonService.checkOpenFunction(item, FunctionIdConstant.MONTHLY_OT_REPORT)).toList();
        }

        /**
         * 提取报告数据日期范围
         *
         * @param propertyDTOList 资产集合
         * @param boList          数据集合
         * @return java.util.Map<java.lang.Integer, java.util.List < java.lang.Long>>
         * @author lichen
         * @date 2025/10/8
         */
        private Map<Integer, List<Long>> getDateRangeMap(List<PropertyDTO> propertyDTOList, List<SalesSourceOperatingStatisticsListBO> boList) {
            Map<String, List<SalesSourceOperatingStatisticsListBO>> property2BOList = boList.stream().collect(Collectors.groupingBy(SalesSourceOperatingStatisticsListBO::getProperty));

            Map<Integer, List<Long>> propertyId2DateRange = Maps.newHashMap();

            propertyDTOList.forEach(propertyDTO -> {
                List<SalesSourceOperatingStatisticsListBO> boListByProperty = property2BOList.get(propertyDTO.getAbbr());

                //跳过
                if (CollectionUtils.isEmpty(boListByProperty)) return;

                //日期集合
                List<Long> dates = boListByProperty.stream().map(item -> Long.parseLong(item.getTheDay().replaceAll("-", ""))).toList();

                long startDate = dates.get(0);
                long endDate = dates.get(dates.size() - 1);
                propertyId2DateRange.put(propertyDTO.getId(), Lists.newArrayList(startDate, endDate));
            });
            return propertyId2DateRange;
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @param s3Key            S3 键
         * @author lichen
         * @date 2025/10/8
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String s3Key) {
            String subject = "[Warning] - Sales Source Handle the Operating Statistics Daily PDF Report error";
            String content = "Process error: " + 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 java.lang.Boolean
         * @author lichen
         * @date 2025/10/8
         */
        private Boolean preventConcurrency(String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }

    }