# DbPmsManagerFlashParseServiceByOther.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.CommonErrorI18nConstant;
    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.S3BucketFunctionCons;
    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 cloud.wconnect.workperformance.service.database.IDbPmsManagerFlashService;
    import cloud.wconnect.workperformance.service.database.IDbReportImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

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

    /**
     * 解析 Other Manager Flash/Service 报告
     *
     * @author zc
     * @date 2025/12/02
     */
    @Component
    @DS("database")
    public class DbPmsManagerFlashParseServiceByOther implements IDbPmsManagerFlashParseService {
        @Resource
        private IDbPmsManagerFlashService managerFlashService;
        @Resource
        private IDbReportImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @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.OTHER.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("xls", "xlsx"));

            try (InputStream in = file.getInputStream(); Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                // 若只包含标题，直接返回
                if (lastRowNum < 1) {
                    return;
                }

                // 提取标题
                List<String> titleList = Lists.newArrayList();
                Row titleRow = sheet.getRow(0);
                for (int i = 0; i <= 3; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    // 校验 Description
                    String descriptionStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(descriptionStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Description cannot be blank");
                    }
                    for (int j = 1; j <= 3; j++) {
                        String recordStr = CellUtils.convertCellStr(row.getCell(j));
                        if (StringUtils.isBlank(recordStr)) {
                            continue;
                        }
                        BigDecimal recordValue;
                        try {
                            recordValue = new BigDecimal(recordStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(j)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Record Value format is incorrect, Record Value = " + recordStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = recordValue.abs().toBigInteger().toString().length();
                        if (intLength > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(j), 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Record Value exceeds the limit, Record Value = " + recordStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Database Manager Flash Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/12/02
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            // 处理是否成功
            boolean handleResult = true;
            // 获取报告 S3 Key
            String s3Key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                    + UploadUtils.getRandomFileName(file.getOriginalFilename());

            try (InputStream in = file.getInputStream()) {
                // 上传报告到 S3，用于导入记录下载报告
                amazonS3Service.uploadFile(S3BucketFunctionCons.DATABASE_IMPORT_RECORD, file, s3Key);
                // 解析报告
                DbPmsManagerFlashBO bo = parse(propertyDTO, in, List.of(importLog.getStartDate(), importLog.getEndDate()));
                // 保存数据
                managerFlashService.handle(propertyDTO, bo, operatorId);
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Database Manager Flash Other report error.", e);
            } finally {
                importLogService.update(importLog.getId(), operatorId, s3Key, handleResult);
            }
        }

        /**
         * 解析报告
         *
         * @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 (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                List<DbPmsManagerFlashItemBO> boList = Lists.newArrayList();
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    boList.add(convert2Bo(row, 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 Other report error.", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param row          行数据
         * @param roundingMode 舍入模式
         * @return DbPmsManagerFlashItemBO
         * @author zc
         * @date 2025/12/02
         */
        private DbPmsManagerFlashItemBO convert2Bo(Row row, RoundingMode roundingMode) {
            DbPmsManagerFlashItemBO itemBO = new DbPmsManagerFlashItemBO();
            itemBO.setDesc(CellUtils.convertCellStr(row.getCell(0)));
            String recordDayStr = CellUtils.convertCellStr(row.getCell(1));
            itemBO.setDay(StringUtils.isBlank(recordDayStr) ? null :
                    new BigDecimal(recordDayStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordMtdStr = CellUtils.convertCellStr(row.getCell(2));
            itemBO.setMtd(StringUtils.isBlank(recordMtdStr) ? null :
                    new BigDecimal(recordMtdStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            String recordYtdStr = CellUtils.convertCellStr(row.getCell(3));
            itemBO.setYtd(StringUtils.isBlank(recordYtdStr) ? null :
                    new BigDecimal(recordYtdStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            return itemBO;
        }
    }