# PropertyOperationsOtherReportServiceImpl.java

    package cloud.wconnect.rateshop.service.rateshop.impl;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    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.pojo.dto.RoomsConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.rateshop.ReportImportLog;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationsOtherReportService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopOccForecastService;
    import cloud.wconnect.rateshop.service.rateshop.IReportImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    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.Service;
    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.time.format.DateTimeParseException;
    import java.util.*;

    /**
     *
     * @author: yyt
     * 2026-03-10
     */
    @RequiredArgsConstructor
    @Service
    @DS("rate_shop")
    public class PropertyOperationsOtherReportServiceImpl implements IPropertyOperationsOtherReportService {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final I18nMessageUtils i18nMessageUtils;
        private final IReportImportLogService importLogService;
        private final IRateShopOccForecastService rateShopOccForecastService;
        private final IPropertyOperationService propertyOperationService;

        @Value("${file-max-size.import-report.rate-shop}")
        private long fileMaxSize;

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @author yyt
         * @date 2026/3/10
         */
        @Override
        public void checkFile(MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xlsx", "xls"));

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

                //标题行
                Row titleRow = sheet.getRow(0);
                //标题集合
                ArrayList<String> titles = Lists.newArrayList();
                for (int i = 0; i < 7; i++) {
                    titles.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

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

                    //日期
                    String date = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isEmpty(date)) {
                        //获取国际化的参数
                        Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(0));
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY, language2ParamList,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The date cannot be null");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(date, formatter);
                        } catch (DateTimeParseException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(0),
                                    BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The date format is incorrect, date = " + date);
                        }
                    }

                    //已售房间
                    String totalOccStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isNotBlank(totalOccStr)) {
                        try {
                            int totalOcc = Integer.parseInt(totalOccStr);
                            if (totalOcc < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(1));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Rooms sold cannot be less than 0, totalOcc = " + totalOccStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(1));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Rooms sold must integer, totalOcc = " + totalOccStr);
                        }
                    }

                    //故障房间
                    String oooRoomsStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isNotBlank(oooRoomsStr)) {
                        try {
                            int oooRoom = Integer.parseInt(oooRoomsStr);
                            if (oooRoom < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(2));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The OOO Rooms cannot be less than 0, oooRooms = " + oooRoomsStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(2));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The OOO Rooms must integer, oooRooms = " + oooRoomsStr);
                        }
                    }

                    //入住率
                    String occPercentStr = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isNotBlank(occPercentStr)) {
                        BigDecimal occPercent;
                        try {
                            occPercent = new BigDecimal(occPercentStr);
                            if (occPercent.compareTo(new BigDecimal("0")) < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(3));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Occ cannot be less than 0, Occ = " + occPercentStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(3));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Occ must number, Occ = " + occPercentStr);
                        }

                        //校验整数位是否超过限制
                        int intLength = occPercent.abs().toBigInteger().toString().length();
                        if (intLength > 5) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(3), "5");
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Occ exceeds the limit, Occ  = " + occPercentStr);
                        }

                    }

                    // 获取 Deduct Ind.
                    String deductIndStr = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isNotBlank(deductIndStr)) {
                        try {
                            int deductInd = Integer.parseInt(deductIndStr);
                            if (deductInd < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(4));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Transient sold cannot be less than 0, Transient sold = " + deductIndStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(4));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Transient sold must integer, Transient sold = " + deductIndStr);
                        }
                    }
                    // 获取 Deduct Group
                    String deductGroupStr = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isNotBlank(deductGroupStr)) {
                        try {
                            int deductGroup = Integer.parseInt(deductGroupStr);
                            if (deductGroup < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(5));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Group sold cannot be less than 0, Group sold = " + deductGroupStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(5));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Group sold must integer, Group sold = " + deductGroupStr);
                        }
                    }
                    // 获取 ADR
                    String adrStr = CellUtils.convertCellStr(row.getCell(6));
                    if (StringUtils.isNotBlank(adrStr)) {
                        BigDecimal adr;
                        try {
                            adr = new BigDecimal(adrStr);
                            if (adr.compareTo(new BigDecimal("0")) < 0) {
                                //获取国际化的参数
                                Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(6));
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO, language2ParamList,
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The ADR cannot be less than 0, ADR = " + adrStr);
                            }
                        } catch (NumberFormatException e) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(6));
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The ADR must number, ADR = " + adrStr);

                        }

                        //校验整数位是否超过限制
                        int intLength = adr.abs().toBigInteger().toString().length();
                        if (intLength > 10) {
                            //获取国际化的参数
                            Map<String, List<Object>> language2ParamList = i18nMessageUtils.getErrorParamMapNotNeedTranslate(titles.get(6), "10");
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH, language2ParamList,
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of ADR exceeds the limit, adrStr  = " + adrStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse history and forecast excel error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人ID
         * @author yyt
         * @date 2026/3/10
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, ReportImportLog importLog, int userId) {
            boolean result = true;
            try (InputStream inputStream = file.getInputStream()) {
                //解析报告
                List<HistoryAndForecastForRateShopBO> boList = parse(inputStream, propertyDTO, importLog.getStartDate(), importLog.getEndDate());

                // 保存报告数据
                propertyOperationService.saveHistoryAndForecastReportData(propertyDTO, userId, boList);

                //保存occ数据
                rateShopOccForecastService.saveOccForecast(propertyDTO, userId, boList);
            } catch (Exception e) {
                result = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse report error", e);
            } finally {
                importLogService.updateImportStatus(importLog, result, userId);
            }
        }

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param startDate   数据日期，开始时间(整点时刻时间戳)
         * @param endDate     数据日期，结束时间(整点时刻时间戳)
         * @return java.util.List<cloud.wconnect.rateshop.pojo.dto.rateshop.messagelistener.HistoryAndForecastForRateShopDTO>
         * @author lichen
         * @date 2024/7/3
         */
        private List<HistoryAndForecastForRateShopBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate) throws ParseReportException {
            // 获取 Revenue 房间数配置
            RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
            Integer configTotalRooms = Objects.isNull(roomsConfig) ? null : roomsConfig.getRooms();

            // 获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            List<HistoryAndForecastForRateShopBO> resultList = Lists.newArrayList();
            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                //获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                //只包含标题
                if (lastRowNum < 1) return Collections.emptyList();

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

                    //日期
                    String dateStr = CellUtils.convertCellStr(row.getCell(0));
                    long dateTimestamp = DateTimeUtils.dateStrToEpochSecond(dateStr, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());
                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (dateTimestamp < startDate || dateTimestamp > endDate) continue;

                    //已售房间
                    String totalOccStr = CellUtils.convertCellStr(row.getCell(1));
                    Integer totalOcc = StringUtils.isEmpty(totalOccStr) ? null : Integer.parseInt(totalOccStr);
                    int subtractTotalOcc = Optional.ofNullable(totalOcc).orElse(BaseConstant.ZERO);

                    //故障房间
                    String oooRoomsStr = CellUtils.convertCellStr(row.getCell(2));
                    Integer oooRooms = StringUtils.isEmpty(oooRoomsStr) ? null : Integer.parseInt(oooRoomsStr);
                    int subtractOooRooms = Optional.ofNullable(oooRooms).orElse(BaseConstant.ZERO);

                    // 获取 PC occ
                    BigDecimal pcOccPercent;
                    // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(totalOcc)
                            && (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE)) {
                        // pc occ = sold rooms / total rooms
                        BigDecimal totalOccBD = BigDecimal.valueOf(totalOcc);
                        pcOccPercent = totalOccBD.multiply(BigDecimal.valueOf(100))
                                .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                    } else {
                        String occPercentStr = CellUtils.convertCellStr(row.getCell(3));
                        pcOccPercent = StringUtils.isEmpty(occPercentStr) ?
                                null : new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    }

                    // 获取 SC occ
                    BigDecimal scOccPercent = null;
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(totalOcc)) {
                        // sc occ = sold rooms / (total rooms - ooo rooms)
                        BigDecimal totalOccBD = BigDecimal.valueOf(totalOcc);
                        int denominator = configTotalRooms - subtractOooRooms;
                        if (denominator != BaseConstant.ZERO) {
                            scOccPercent = totalOccBD.multiply(BigDecimal.valueOf(100))
                                    .divide(BigDecimal.valueOf(denominator), BaseConstant.DATA_PRECISION, roundingMode);
                        } else {
                            scOccPercent = BigDecimal.ZERO;
                        }
                    }

                    // 计算 Rooms Available = 资产总房间数 - Total Occ. - OOO Rooms
                    Integer roomsAvailable = Objects.nonNull(configTotalRooms) ?
                            (configTotalRooms - subtractTotalOcc - subtractOooRooms) : null;

                    // 获取 Deduct Ind.
                    String deductIndStr = CellUtils.convertCellStr(row.getCell(4));
                    Integer deductInd = StringUtils.isEmpty(deductIndStr) ? null : Integer.parseInt(deductIndStr);

                    // 获取 Deduct Group
                    String deductGroupStr = CellUtils.convertCellStr(row.getCell(5));
                    Integer deductGroup = StringUtils.isEmpty(deductGroupStr) ? null : Integer.parseInt(deductGroupStr);

                    // 获取 ADR
                    String adrStr = CellUtils.convertCellStr(row.getCell(6));
                    BigDecimal adr = StringUtils.isEmpty(adrStr) ? null : new BigDecimal(adrStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    resultList.add(HistoryAndForecastForRateShopBO.builder()
                            .date(dateStr)
                            .roomsSold(totalOcc)
                            .transientSold(deductInd)
                            .groupSold(deductGroup)
                            .pcOcc(pcOccPercent)
                            .scOcc(scOccPercent)
                            .adr(adr)
                            .oooRooms(oooRooms)
                            .roomsAvailable(roomsAvailable)
                            .build());
                }

                return resultList;
            } catch (IOException ioException) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse property operation info excel error");
            }
        }

    }