# DbPmsMarketCodeStatisticsParseServiceByOther.java

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

    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.DbPmsManagerFlashItemBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsDataBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsParentGroupBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsSubGroupBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.database.IDbPmsManagerFlashService;
    import cloud.wconnect.workperformance.service.database.IDbPmsMarketCodeStatisticsService;
    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.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.Iterator;
    import java.util.List;

    /**
     * 解析 Other Market Code Statistics/Service 报告
     *
     * @author zc
     * @date 2025/12/15
     */
    @Component
    @DS("database")
    public class DbPmsMarketCodeStatisticsParseServiceByOther implements IDbPmsMarketCodeStatisticsParseService {
        @Resource
        private IDbPmsManagerFlashService managerFlashService;
        @Resource
        private IDbPmsMarketCodeStatisticsService marketCodeStatisticsService;
        @Resource
        private IDbReportImportLogService importLogService;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private I18nMessageUtils i18nMessageUtils;

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

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2025/12/15
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2025/12/15
         */
        @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 < 2) {
                    return;
                }

                // 提取前两行的标题
                List<String> firstTitleList = Lists.newArrayList();
                Row titleRow = sheet.getRow(0);
                for (int i = 0; i <= 1; i++) {
                    firstTitleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }
                List<String> secondTitleList = Lists.newArrayList();
                Row secondTitleRow = sheet.getRow(1);
                for (int i = 0; i <= 16; i++) {
                    secondTitleList.add(CellUtils.convertCellStr(secondTitleRow.getCell(i)));
                }

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

                    // 若第 2 列为空则表示是父级，反之是子级
                    String roomsStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(roomsStr)) {
                        // 校验 Market Segment
                        String marketSegmentStr = CellUtils.convertCellStr(row.getCell(0));
                        if (StringUtils.isBlank(marketSegmentStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(firstTitleList.get(0)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Market Segment cannot be blank");
                        }
                        // 校验 Market Segment Description
                        String marketSegmentDescriptionStr = CellUtils.convertCellStr(row.getCell(1));
                        if (StringUtils.isBlank(marketSegmentDescriptionStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(firstTitleList.get(1)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Market Segment Description cannot be blank");
                        }
                    } else {
                        // 校验 Rate Plan
                        String ratePlanStr = CellUtils.convertCellStr(row.getCell(0));
                        if (StringUtils.isBlank(ratePlanStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(secondTitleList.get(0)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Rate Plan cannot be blank");
                        }
                        // 校验 Rate Plan Description
                        String ratePlanDescriptionStr = CellUtils.convertCellStr(row.getCell(1));
                        if (StringUtils.isBlank(ratePlanDescriptionStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(secondTitleList.get(1)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Rate Plan Description cannot be blank");
                        }
                        // 校验 Day - Rooms
                        String dayRoomsStr = CellUtils.convertCellStr(row.getCell(2));
                        checkIntegerValue(secondTitleList.get(2), dayRoomsStr, 4);

                        // 校验 Day - Revenue
                        String dayRoomRevenueStr = CellUtils.convertCellStr(row.getCell(3));
                        checkBigDecimalValue(secondTitleList.get(3), dayRoomRevenueStr, 8);

                        // 校验 Day - ADR
                        String dayAdrStr = CellUtils.convertCellStr(row.getCell(4));
                        checkBigDecimalValue(secondTitleList.get(4), dayAdrStr, 6);

                        // 校验 Day - Occupancy
                        String dayOccStr = CellUtils.convertCellStr(row.getCell(5));
                        checkBigDecimalValue(secondTitleList.get(5), dayOccStr, 3);

                        // 校验 Day - Persons
                        String dayPersonsStr = CellUtils.convertCellStr(row.getCell(6));
                        checkIntegerValue(secondTitleList.get(6), dayPersonsStr, 4);

                        // 校验 MTD - Rooms
                        String mtdRoomsStr = CellUtils.convertCellStr(row.getCell(7));
                        checkIntegerValue(secondTitleList.get(7), mtdRoomsStr, 6);

                        // 校验 MTD - Revenue
                        String mtdRoomRevenueStr = CellUtils.convertCellStr(row.getCell(8));
                        checkBigDecimalValue(secondTitleList.get(8), mtdRoomRevenueStr, 10);

                        // 校验 MTD - ADR
                        String mtdAdrStr = CellUtils.convertCellStr(row.getCell(9));
                        checkBigDecimalValue(secondTitleList.get(9), mtdAdrStr, 6);

                        // 校验 MTD - Occupancy
                        String mtdOccStr = CellUtils.convertCellStr(row.getCell(10));
                        checkBigDecimalValue(secondTitleList.get(10), mtdOccStr, 3);

                        // 校验 MTD - Persons
                        String mtdPersonsStr = CellUtils.convertCellStr(row.getCell(11));
                        checkIntegerValue(secondTitleList.get(11), mtdPersonsStr, 6);

                        // 校验 YTD - Rooms
                        String ytdRoomsStr = CellUtils.convertCellStr(row.getCell(12));
                        checkIntegerValue(secondTitleList.get(12), ytdRoomsStr, 8);

                        // 校验 YTD - Revenue
                        String ytdRoomRevenueStr = CellUtils.convertCellStr(row.getCell(13));
                        checkBigDecimalValue(secondTitleList.get(13), ytdRoomRevenueStr, 12);

                        // 校验 YTD - ADR
                        String ytdAdrStr = CellUtils.convertCellStr(row.getCell(14));
                        checkBigDecimalValue(secondTitleList.get(14), ytdAdrStr, 6);

                        // 校验 YTD - Occupancy
                        String ytdOccStr = CellUtils.convertCellStr(row.getCell(15));
                        checkBigDecimalValue(secondTitleList.get(15), ytdOccStr, 3);

                        // 校验 YTD - Persons
                        String ytdPersonsStr = CellUtils.convertCellStr(row.getCell(16));
                        checkIntegerValue(secondTitleList.get(16), ytdPersonsStr, 8);
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Database Market Code Statistics Other report error.", e);
            }
        }

        /**
         * 校验 BigDecimal Value
         *
         * @param title    标题
         * @param valueStr 列内容
         * @param length   数值最大位数
         * @author zc
         * @date 2025/12/15
         */
        private void checkBigDecimalValue(String title, String valueStr, int length) {
            if (StringUtils.isBlank(valueStr)) {
                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} cannot be blank", title));
            }
            BigDecimal value;
            try {
                value = new BigDecimal(valueStr);
            } catch (NumberFormatException e) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} format is incorrect, content = {1}", title, valueStr));
            }
            int intLength = value.abs().toBigInteger().toString().length();
            if (intLength > length) {
                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title, 6),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} exceeds the limit {1}, content = {2}", title, length, valueStr));
            }
        }

        /**
         * 校验 Integer Value
         *
         * @param title    标题
         * @param valueStr 列内容
         * @param length   数值最大位数
         * @author zc
         * @date 2025/12/15
         */
        private void checkIntegerValue(String title, String valueStr, int length) {
            if (StringUtils.isBlank(valueStr)) {
                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} cannot be blank", title));
            }
            int value;
            try {
                value = Integer.parseInt(valueStr);
            } catch (NumberFormatException e) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} format is incorrect, content = {1}", title, valueStr));
            }
            if (String.valueOf(Math.abs(value)).length() > length) {
                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(title),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        MessageFormat.format("The {0} exceeds the limit {1}, content = {2}", title, length, valueStr));
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2025/12/15
         */
        @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);
                // 解析报告
                DbPmsMarketCodeStatisticsBO bo = parse(propertyDTO, in, List.of(importLog.getStartDate(), importLog.getEndDate()));
                // 保存数据
                marketCodeStatisticsService.handle(propertyDTO, bo, operatorId);
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Database Market Code Statistics Other report error.", e);
            } finally {
                importLogService.update(importLog.getId(), operatorId, s3Key, handleResult);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return DbPmsMarketCodeStatisticsBO
         * @author zc
         * @date 2025/12/15
         */
        @Override
        public DbPmsMarketCodeStatisticsBO parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            String dataDate = dateRange.get(0).toString();
            // 从 Manager Flash 中获取 SC Rooms
            DbPmsManagerFlashItemBO scRoomsBO = managerFlashService.getScRooms(propertyDTO, Long.parseLong(dataDate));

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                DbPmsMarketCodeStatisticsBO bo = new DbPmsMarketCodeStatisticsBO();
                LocalDate localDate = DateTimeUtils.strToLocalDate(dataDate, BaseConstant.DATE_FORMAT_YYYYMMDD);
                bo.setDateStr(localDate.format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD)));

                DbPmsMarketCodeStatisticsDataBO dataBO = convert2Bo(sheet, scRoomsBO, roundingMode);
                bo.setData(dataBO);
                return bo;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Database parse Market Code Statistics Other report error", e);
            }
        }

        /**
         * 转换为BO
         *
         * @param sheet        sheet
         * @param scRoomsBO    SC Rooms
         * @param roundingMode 舍入模式
         * @return PmsMarketCodeStatisticsDataBO
         * @author zc
         * @date 2025/12/15
         */
        private DbPmsMarketCodeStatisticsDataBO convert2Bo(Sheet sheet, DbPmsManagerFlashItemBO scRoomsBO,
                                                           RoundingMode roundingMode) throws IOException {
            Iterator<Row> iterator = sheet.iterator();
            // 跳过标题行
            iterator.next();
            iterator.next();

            // 解析数据为父子结构
            List<DbPmsMarketCodeStatisticsParentGroupBO> parentGroup = parseParentAndSubGroups(iterator);

            // 计算每个父级的小计
            IDbPmsMarketCodeStatisticsParseService.calculateParentSubtotals(parentGroup, scRoomsBO, roundingMode);

            // 计算总计
            DbPmsMarketCodeStatisticsDataBO bo = IDbPmsMarketCodeStatisticsParseService.calculateTotals(parentGroup, scRoomsBO, roundingMode);
            bo.setMarketCode(parentGroup);

            return bo;
        }

        /**
         * 解析父子结构数据
         *
         * @param iterator CSV记录迭代器
         * @return 父级组列表
         * @author zc
         * @date 2025/12/15
         */
        private List<DbPmsMarketCodeStatisticsParentGroupBO> parseParentAndSubGroups(Iterator<Row> iterator) {
            List<DbPmsMarketCodeStatisticsParentGroupBO> parentGroup = Lists.newArrayList();
            DbPmsMarketCodeStatisticsParentGroupBO currentParent = null;

            while (iterator.hasNext()) {
                Row row = iterator.next();

                // 若第 2 列为空则表示是父级，反之是子级
                String roomsStr = CellUtils.convertCellStr(row.getCell(2));

                if (StringUtils.isBlank(roomsStr)) {
                    // 父级 Market Segment
                    currentParent = new DbPmsMarketCodeStatisticsParentGroupBO();
                    List<DbPmsMarketCodeStatisticsSubGroupBO> subGroup = Lists.newArrayList();
                    currentParent.setRateCode(subGroup);

                    String marketSegmentStr = CellUtils.convertCellStr(row.getCell(0));
                    currentParent.setCode(marketSegmentStr);
                    String descriptionStr = CellUtils.convertCellStr(row.getCell(1));
                    currentParent.setDesc(descriptionStr);

                    parentGroup.add(currentParent);
                } else if (currentParent != null) {
                    // 子级 Market Segment
                    DbPmsMarketCodeStatisticsSubGroupBO subGroupBO = convert2SubBo(row);
                    currentParent.getRateCode().add(subGroupBO);
                }
            }

            return parentGroup;
        }

        /**
         * 转换为 Sub Group BO
         *
         * @param row Row
         * @return PmsMarketCodeStatisticsSubGroupBO
         * @author zc
         * @date 2025/12/15
         */
        private DbPmsMarketCodeStatisticsSubGroupBO convert2SubBo(Row row) {
            DbPmsMarketCodeStatisticsSubGroupBO subGroupBO = new DbPmsMarketCodeStatisticsSubGroupBO();
            subGroupBO.setCode(CellUtils.convertCellStr(row.getCell(0)));
            subGroupBO.setDesc(CellUtils.convertCellStr(row.getCell(1)));

            subGroupBO.setRmsDay(Integer.parseInt(CellUtils.convertCellStr(row.getCell(2))));
            subGroupBO.setRmRevDay(new BigDecimal(CellUtils.convertCellStr(row.getCell(3))));
            subGroupBO.setAdrDay(new BigDecimal(CellUtils.convertCellStr(row.getCell(4))));
            subGroupBO.setOccDay(new BigDecimal(CellUtils.convertCellStr(row.getCell(5))));
            subGroupBO.setGuestDay(Integer.parseInt(CellUtils.convertCellStr(row.getCell(6))));

            subGroupBO.setRmsMtd(Integer.parseInt(CellUtils.convertCellStr(row.getCell(7))));
            subGroupBO.setRmRevMtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(8))));
            subGroupBO.setAdrMtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(9))));
            subGroupBO.setOccMtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(10))));
            subGroupBO.setGuestMtd(Integer.parseInt(CellUtils.convertCellStr(row.getCell(11))));

            subGroupBO.setRmsYtd(Integer.parseInt(CellUtils.convertCellStr(row.getCell(12))));
            subGroupBO.setRmRevYtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(13))));
            subGroupBO.setAdrYtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(14))));
            subGroupBO.setOccYtd(new BigDecimal(CellUtils.convertCellStr(row.getCell(15))));
            subGroupBO.setGuestYtd(Integer.parseInt(CellUtils.convertCellStr(row.getCell(16))));

            return subGroupBO;
        }

    }