# SvaOperatingStatisticsDailyPdfListener.java

    package cloud.wconnect.workperformance.messagelistener.sva;

    import cloud.wconnect.commonlib.cons.*;
    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.sva.operatingstatistics.OperatingStatisticsListBO;
    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.pdf.DailyOperatingStatisticsParser;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperStatisImportLogService;
    import cloud.wconnect.workperformance.service.sva.operatingstatistics.IOperatingStatisticsReportEnhancerService;
    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.math.BigDecimal;
    import java.math.RoundingMode;
    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 SvaOperatingStatisticsDailyPdfListener {
        @Resource
        private IOperStatisImportLogService 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;
        @Resource
        private IOperatingStatisticsReportEnhancerService operatingStatisticsReportEnhancerService;

        private static final String SUBJECT = EventSubjectEnum.ACCOUNTING_OPERATING_STATISTICS_PDF.getSubject();
        private static final String BUSINESS = BusinessEnum.SVA_OPERATING_STATISTICS.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("SvaOperatingStatisticsDailyPdfListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("SvaOperatingStatisticsDailyPdfListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SvaOperatingStatisticsDailyPdfListener.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("SvaOperatingStatisticsDailyPdfListener.handle end... propertyDTOList is empty.");
                return;
            }

            String path = eventBodyDTO.getPath();

            // 处理是否成功
            boolean handleResult = true;
            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<OperatingStatisticsListBO> boList = dto2Bo(pdfDTOList);

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

                    // 处理Operating statistics original数据
                    operatingStatisticsReportEnhancerService.handleOperatingStatisticsOriginByNonM3Api(propertyDTOList, boList,
                            0, propertyId2DateRange, OperatingStatisticsDatasourceEnum.PDF.getValue());

                    // 按优先级更新Operating statistics数据
                    operatingStatisticsReportEnhancerService.updateOperatingStatisticsByPriority(propertyDTOList, propertyId2DateRange);
                }
                log.info("SvaOperatingStatisticsDailyPdfListener.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("SvaOperatingStatisticsDailyPdfListener.handle end... Process error.", e);
            } finally {
                // 上传报告，用于日志下载报告
                uploadReport(path);

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

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

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

            for (OperatingStatisticsPdfDTO dto : dtoList) {
                List<OperatingStatisticsDailyPdfDTO> dailyPdfList = dto.getContent();
                for (OperatingStatisticsDailyPdfDTO dailyPdf : dailyPdfList) {
                    OperatingStatisticsListBO operatingStatisticsListBO = new OperatingStatisticsListBO();
                    operatingStatisticsListBO.setProperty(dto.getHotel());
                    operatingStatisticsListBO.setTheDay(dailyOperatingStatisticsParser.formatDate(dailyPdf.getDate()));
                    operatingStatisticsListBO.setRoomsRented(dailyPdf.getRooms_rented());

                    //Occ数据除以100
                    BigDecimal occPercent = dailyOperatingStatisticsParser.formatPercent(dailyPdf.getOcc_percent());
                    if(Objects.nonNull(occPercent)){
                        //除以100
                        occPercent = occPercent.divide(new BigDecimal(100),BaseConstant.DATA_PRECISION, RoundingMode.HALF_UP);
                    }

                    operatingStatisticsListBO.setOccPercent(occPercent);
                    operatingStatisticsListBO.setAdr(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getAdr()));
                    operatingStatisticsListBO.setRevPar(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getRevPAR()));
                    operatingStatisticsListBO.setRoomRev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getRoom_rev()));
                    operatingStatisticsListBO.setFoodRev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getFood_rev()));
                    operatingStatisticsListBO.setFb2Rev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getFb2_rev()));
                    operatingStatisticsListBO.setBevRev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getBeverage_rev()));
                    operatingStatisticsListBO.setOtherRev(dailyOperatingStatisticsParser.formatAmount(dailyPdf.getOther_rev()));
                    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.SVA_OPERATING_IMPORT_RECORD, inputStream, path);
            } catch (Exception e) {
                log.error("SvaOperatingStatisticsDailyPdfListener.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.SCHEDULE_VS_ACTUAL)).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<OperatingStatisticsListBO> boList) {
            Map<String, List<OperatingStatisticsListBO>> property2BOList = boList.stream().collect(Collectors.groupingBy(OperatingStatisticsListBO::getProperty));

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

            propertyDTOList.forEach(propertyDTO -> {
                List<OperatingStatisticsListBO> 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] - SVA 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);
        }

    }