# DbPmsManagerFlashParseServiceByShiji.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.Iterator;
    import java.util.List;

    /**
     * 解析 Shiji Manager Flash/Service 报告
     *
     * @author zc
     * @date 2025/12/02
     */
    @Component
    public class DbPmsManagerFlashParseServiceByShiji implements IDbPmsManagerFlashParseService {

        private final IDbReportService reportService;

        public DbPmsManagerFlashParseServiceByShiji(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 2025/12/02
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                ShijiFileCheckUtils.checkManagerFlash(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Database Manager Flash Shiji report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/12/02
         */
        @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 2025/12/02
         */
        @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);
                Iterator<CSVRecord> iterator = iterable.iterator();
                // 跳过标题行
                iterator.next();
                while (iterator.hasNext()) {
                    CSVRecord csvRecord = iterator.next();
                    String monthCyStr = ShijiFileCheckUtils.get(csvRecord, "C");
                    // 最后一行是 资产名称 + 日期，若 C 列为空则直接跳出
                    if (StringUtils.isBlank(monthCyStr)) {
                        break;
                    }
                    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 Manager Flash Shiji report error.", e);
            }
        }

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

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

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

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