# DbPmsManagerFlashParseServiceByPep.java

    package cloud.wconnect.workperformance.service.database.managerflash;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.managerflash.DbPmsManagerFlashBO;
    import cloud.wconnect.workperformance.pojo.bo.database.managerflash.DbPmsManagerFlashItemBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.HashMap;
    import java.util.List;

    /**
     * 解析 PEP Manager Flash/Service 报告
     *
     * @author zc
     * @date 2026/01/29
     */
    @Component
    public class DbPmsManagerFlashParseServiceByPep implements IDbPmsManagerFlashParseService {

        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.database.manager-flash}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.database}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2026/1/29
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.PEP.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2026/1/29
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                PepFileCheckUtils.checkHotelStatistics(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Database [Hotel Statistics] PEP report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2026/1/29
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());

                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), List.of(propertyDTO.getAbbr()));
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.DATABASE.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.PEP.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), importLog.getId());
                parameter.put(EventBodyParamEnum.BUSINESS_DATE.getDesc(), importLog.getBusinessDate());
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), importLog.getStartDate());
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), importLog.getEndDate());

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.MANAGER_FLASH_SERVICE_MTD_YESTERDAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Database [Hotel Statistics] PEP report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return DbPmsManagerFlashBO 集合
         * @author zc
         * @date 2026/1/29
         */
        @Override
        public DbPmsManagerFlashBO parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<DbPmsManagerFlashItemBO> boList = Lists.newArrayList();
                // 获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);

                for (CSVRecord csvRecord : iterable) {
                    // 若当前行的 A 列为空 或 B 列内容是标题[Actual Today]，则直接跳出
                    String aStr = CsvFileUtils.get(csvRecord, "A");
                    String bStr = CsvFileUtils.get(csvRecord, "B");
                    if (StringUtils.isBlank(aStr) || "Actual Today".equals(bStr)) {
                        continue;
                    }
                    boList.add(convert2Bo(csvRecord, roundingMode));
                }

                DbPmsManagerFlashBO bo = new DbPmsManagerFlashBO();
                LocalDate localDate = DateTimeUtils.strToLocalDate(dateRange.get(0).toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
                bo.setDateStr(localDate.format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD)));
                bo.setData(boList);
                return bo;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Database [Hotel Statistics] PEP report error.", e);
            }
        }

        /**
         * 转换为BO
         *
         * @param csvRecord    CSV数据行
         * @param roundingMode 舍入模式
         * @return DbPmsManagerFlashItemBO
         * @author zc
         * @date 2026/1/29
         */
        private DbPmsManagerFlashItemBO convert2Bo(CSVRecord csvRecord, RoundingMode roundingMode) {
            DbPmsManagerFlashItemBO itemBO = new DbPmsManagerFlashItemBO();
            itemBO.setDesc(CsvFileUtils.get(csvRecord, "A"));

            String recordDayStr = CsvFileUtils.getAndFormatNumber(csvRecord, "B");
            itemBO.setDay(StringUtils.isBlank(recordDayStr) ? null : new BigDecimal(recordDayStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            String recordMtdStr = CsvFileUtils.getAndFormatNumber(csvRecord, "C");
            itemBO.setMtd(StringUtils.isBlank(recordMtdStr) ? null : new BigDecimal(recordMtdStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));

            String recordYtdStr = CsvFileUtils.getAndFormatNumber(csvRecord, "E");
            itemBO.setYtd(StringUtils.isBlank(recordYtdStr) ? null : new BigDecimal(recordYtdStr)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode));
            return itemBO;
        }

    }