# ParseHFNextMonthExcelByShiJiServiceImpl.java

    package cloud.wconnect.rateshop.service.revenue.report.historyandforecast.nextmonth;

    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.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.CellUtils;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueAdrConfig;
    import cloud.wconnect.rateshop.pojo.bo.revenue.OtbAndTransientGroupBO;
    import cloud.wconnect.rateshop.pojo.bo.revenue.OtbRevenueBO;
    import cloud.wconnect.rateshop.pojo.bo.revenue.TransientGroupBO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueAdrConfigService;
    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.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    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.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Objects;

    /**
     * @author: yyt
     * 2025-07-05
     */
    @Service
    @DS("rate_shop")
    public class ParseHFNextMonthExcelByShiJiServiceImpl implements IParseHFNextMonthExcelService {

        @Resource
        private RoomsConfigInternalService roomsConfigInternalService;
        @Resource
        private IRevenueAdrConfigService revenueAdrConfigService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        @Override
        public boolean supports(String source) {
            return source.equals(SystemPlatformEnum.SHI_JI.getDesc());
        }

        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            try (InputStream in = file.getInputStream();
                 Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row revenueRow = sheet.getRow(0);
                if (Objects.isNull(revenueRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                String revenueTitle = CellUtils.convertCellStr(revenueRow.getCell(0));
                Cell revenueCell = revenueRow.getCell(1);
                if (Objects.nonNull(revenueCell) && StringUtils.isNotBlank(revenueCell.toString())) {
                    BigDecimal revenue;
                    try {
                        revenue = new BigDecimal(CellUtils.convertCellStr(revenueCell));
                    } catch (Exception e) {
                        throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(revenueTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The revenue must be a number");
                    }
                    // 整数 10 位
                    if (revenue.toBigInteger().toString().length() > 10) {
                        throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(revenueTitle, 10),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The revenue exceed the limit");
                    }
                }

                Row listTitleRow = sheet.getRow(1);
                String dateTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "A"));
                String listRoomsTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "B"));
                String listOccTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "C"));
                String listRateTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "D"));
                String oooRoomsTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "E"));
                String transientDeductRoomsTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "F"));
                String transientDeductRevenueTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "G"));
                String groupDeductRoomsTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "H"));
                String groupDeductRevenueTitle = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(listTitleRow, "I"));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell dateCell = CellUtils.getCellByColumnLetter(row, "A");
                    if (Objects.isNull(dateCell) || StringUtils.isBlank(dateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(dateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(dateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The date format error");
                        }
                    }

                    Cell roomsCell = CellUtils.getCellByColumnLetter(row, "B");
                    if (Objects.nonNull(roomsCell) && StringUtils.isNotBlank(roomsCell.toString())) {
                        BigDecimal rooms;
                        try {
                            rooms = new BigDecimal(CellUtils.convertCellStr(roomsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listRoomsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms must be a number");
                        }
                        if (rooms.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listRoomsTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rooms exceed the limit");
                        }
                    }

                    Cell occCell = CellUtils.getCellByColumnLetter(row, "C");
                    if (Objects.nonNull(occCell) && StringUtils.isNotBlank(occCell.toString())) {
                        BigDecimal occ;
                        try {
                            occ = new BigDecimal(CellUtils.convertCellStr(occCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listOccTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The occ must be a number");
                        }
                        if (occ.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listOccTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The occ exceed the limit");
                        }
                    }

                    Cell rateCell = CellUtils.getCellByColumnLetter(row, "D");
                    if (Objects.nonNull(rateCell) && StringUtils.isNotBlank(rateCell.toString())) {
                        BigDecimal rate;
                        try {
                            rate = new BigDecimal(CellUtils.convertCellStr(rateCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listRateTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rate must be a number");
                        }
                        if (rate.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(listRateTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rate exceed the limit");
                        }
                    }

                    Cell oooRoomsCell = CellUtils.getCellByColumnLetter(row, "E");
                    if (Objects.nonNull(oooRoomsCell) && StringUtils.isNotBlank(oooRoomsCell.toString())) {
                        BigDecimal oooRooms;
                        try {
                            oooRooms = new BigDecimal(CellUtils.convertCellStr(oooRoomsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(oooRoomsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The ooo rooms must be a number");
                        }
                        if (oooRooms.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(oooRoomsTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The ooo rooms exceed the limit");
                        }
                    }

                    Cell transientDeductRoomsCell = CellUtils.getCellByColumnLetter(row, "F");
                    if (Objects.nonNull(transientDeductRoomsCell) && StringUtils.isNotBlank(transientDeductRoomsCell.toString())) {
                        BigDecimal transientDeductRooms;
                        try {
                            transientDeductRooms = new BigDecimal(CellUtils.convertCellStr(transientDeductRoomsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transientDeductRoomsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transient deduct rooms must be a number");
                        }
                        if (transientDeductRooms.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transientDeductRoomsTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transient deduct rooms exceed the limit");
                        }
                    }

                    Cell transientDeductRevenueCell = CellUtils.getCellByColumnLetter(row, "G");
                    if (Objects.nonNull(transientDeductRevenueCell) && StringUtils.isNotBlank(transientDeductRevenueCell.toString())) {
                        BigDecimal transientDeductRevenue;
                        try {
                            transientDeductRevenue = new BigDecimal(CellUtils.convertCellStr(transientDeductRevenueCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transientDeductRevenueTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transient deduct revenue must be a number");
                        }
                        if (transientDeductRevenue.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transientDeductRevenueTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transient deduct rooms exceed the limit");
                        }
                    }

                    Cell groupDeductRoomsCell = CellUtils.getCellByColumnLetter(row, "H");
                    if (Objects.nonNull(groupDeductRoomsCell) && StringUtils.isNotBlank(groupDeductRoomsCell.toString())) {
                        BigDecimal groupDeductRooms;
                        try {
                            groupDeductRooms = new BigDecimal(CellUtils.convertCellStr(groupDeductRoomsCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupDeductRoomsTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The group deduct rooms must be a number");
                        }
                        if (groupDeductRooms.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupDeductRoomsTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The group deduct rooms exceed the limit");
                        }
                    }

                    Cell groupDeductRevenueCell = CellUtils.getCellByColumnLetter(row, "I");
                    if (Objects.nonNull(groupDeductRevenueCell) && StringUtils.isNotBlank(groupDeductRevenueCell.toString())) {
                        BigDecimal groupDeductRevenue;
                        try {
                            groupDeductRevenue = new BigDecimal(CellUtils.convertCellStr(groupDeductRevenueCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupDeductRevenueTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The group deduct revenue must be a number");
                        }
                        if (groupDeductRevenue.toBigInteger().toString().length() > 6) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(groupDeductRevenueTitle, 6),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The group deduct revenue exceed the limit");
                        }
                    }
                }
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        @Override
        public OtbAndTransientGroupBO handleFile(PropertyDTO propertyDTO, InputStream inputStream, Long startDate, Long endDate) throws IOException {
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            int dataPrecision = BaseConstant.DATA_PRECISION;
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            Integer propertyId = propertyDTO.getId();
            RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyId);
            Integer rooms = roomsConfig.getRooms();

            RevenueAdrConfig revenueAdrConfig = revenueAdrConfigService.get(propertyId);
            boolean checkTransientDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckTransientDeduct();
            boolean checkGroupDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckGroupDeduct();

            // 最多1个月的数据
            List<TransientGroupBO> transientGroups = Lists.newArrayListWithExpectedSize(31);
            ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            BigDecimal oneHundred = BigDecimal.valueOf(100L);

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            for (int i = 2; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (Objects.isNull(row)) {
                    continue;
                }

                Cell dateCell = CellUtils.getCellByColumnLetter(row, "A");
                String dateStr = CellUtils.convertCellStr(dateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                ZonedDateTime targetDateZoneDateTime = LocalDate.parse(dateStr, dateTimeFormatter).atStartOfDay(zoneId);
                long targetDate = targetDateZoneDateTime.toEpochSecond();
                if (targetDate < startDate || targetDate > endDate) {
                    continue;
                }

                TransientGroupBO transientGroup = new TransientGroupBO();
                transientGroup.setTargetDate(dateStr);

                // 如果配置了房间数，则根据 occ 计算规则判断：1.使用配置的房间数计算 occ，2.直接使用文件中的 occ
                if (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                    String totalOccRoomsStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "B"));
                    if (StringUtils.isNotEmpty(totalOccRoomsStr)) {
                        //  Occ. % = total occ rooms / 总房间数
                        BigDecimal occPercent = new BigDecimal(totalOccRoomsStr).divide(BigDecimal.valueOf(rooms), dataPrecision, roundingMode).multiply(oneHundred);
                        transientGroup.setOccPercent(occPercent);
                    }
                } else {
                    String occPercentStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "C"));
                    if (StringUtils.isNotEmpty(occPercentStr)) {
                        transientGroup.setOccPercent(new BigDecimal(occPercentStr).setScale(dataPrecision, roundingMode));
                    }
                }

                String adrStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "D"));
                if (StringUtils.isNotEmpty(adrStr)) {
                    transientGroup.setAdr(new BigDecimal(adrStr).setScale(dataPrecision, roundingMode));
                }

                // 如果勾选了 Transient deduct，则累加交订金的 Transient 房间数
                String transientRoomsStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "F"));
                if (checkTransientDeduct && StringUtils.isNotEmpty(transientRoomsStr)) {
                    transientGroup.setTransientRoomNum(Integer.valueOf(transientRoomsStr));
                }
                // 如果勾选了 Transient deduct，则计算交订金的 Transient 房间平均房价
                BigDecimal transientRoomRevenue = null;
                String deductRevenueStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "G"));
                if (checkTransientDeduct && StringUtils.isNotEmpty(deductRevenueStr)) {
                    transientRoomRevenue = new BigDecimal(deductRevenueStr);
                }
                Integer transientRoomNum = transientGroup.getTransientRoomNum();
                if (Objects.nonNull(transientRoomRevenue) && Objects.nonNull(transientRoomNum) && transientRoomNum != BaseConstant.ZERO) {
                    BigDecimal transientAdr = transientRoomRevenue.divide(BigDecimal.valueOf(transientRoomNum), BaseConstant.DATA_PRECISION, roundingMode);
                    transientGroup.setTransientAdr(transientAdr);
                }

                // 如果勾选了 Group deduct，则累加交订金的 Group 房间数
                String groupRoomsStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "H"));
                if (checkGroupDeduct && StringUtils.isNotEmpty(groupRoomsStr)) {
                    transientGroup.setGroupRoomNum(Integer.valueOf(groupRoomsStr));
                }
                // 如果勾选了 Group deduct，则计算交订金的 Group 房间平均房价
                BigDecimal groupRoomRevenue = null;
                String grpDeductRevenueStr = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "I"));
                if (checkGroupDeduct && StringUtils.isNotEmpty(grpDeductRevenueStr)) {
                    groupRoomRevenue = new BigDecimal(grpDeductRevenueStr);
                }
                Integer groupRoomNum = transientGroup.getGroupRoomNum();
                if (Objects.nonNull(groupRoomRevenue) && Objects.nonNull(groupRoomNum) && groupRoomNum != BaseConstant.ZERO) {
                    BigDecimal groupAdr = groupRoomRevenue.divide(BigDecimal.valueOf(groupRoomNum),BaseConstant.DATA_PRECISION, roundingMode);
                    transientGroup.setGroupAdr(groupAdr);
                }

                // 计算 Rooms Available = 酒店房间数 - Total Occ. - OOO Rooms
                Integer roomsAvailable = rooms;
                if (Objects.nonNull(roomsAvailable)) {
                    String totalOcc = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "B"));
                    String oooRooms = CellUtils.convertCellStr(CellUtils.getCellByColumnLetter(row, "E"));
                    if (StringUtils.isNotEmpty(totalOcc)) {
                        roomsAvailable -= Integer.parseInt(totalOcc);
                    }
                    if (StringUtils.isNotEmpty(oooRooms)) {
                        roomsAvailable -= Integer.parseInt(oooRooms);
                    }
                }
                transientGroup.setRoomsAvailable(roomsAvailable);

                transientGroups.add(transientGroup);
            }

            OtbRevenueBO otbRevenue = new OtbRevenueBO();
            Row revenueRow = sheet.getRow(0);
            if (Objects.nonNull(revenueRow)) {
                Cell revenueCell = revenueRow.getCell(1);
                if (Objects.nonNull(revenueCell) && StringUtils.isNotBlank(revenueCell.toString())) {
                    otbRevenue.setOtbRevenue(new BigDecimal(CellUtils.convertCellStr(revenueCell)));
                }
            }

            workbook.close();

            return new OtbAndTransientGroupBO(otbRevenue, transientGroups);
        }

    }