# 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.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.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    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.database.IDbReportService;
    import com.google.common.collect.Lists;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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.List;

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

        private final IDbReportService reportService;

        public DbPmsManagerFlashParseServiceByPep(IDbReportService reportService) {
            this.reportService = reportService;
        }

        @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) {
            reportService.sendReportEvent(propertyDTO, file, importLog, operatorId, s3FilePath,
                    EventSubjectEnum.MANAGER_FLASH_SERVICE_MTD_YESTERDAY.getSubject());
        }

        /**
         * 解析报告
         *
         * @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;
        }

    }