# HotelKpiHistoryAndForecastParseServiceByOther.java

    package cloud.wconnect.workperformance.service.hotelkpi.historyandforecast;

    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.cons.hotelkpi.HotelKpiMetricsEnum;
    import cloud.wconnect.workperformance.cons.hotelkpi.HotelKpiTriggerTypeCons;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiCommonSummaryService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiHistoryAndForecastService;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    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.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.List;
    import java.util.Locale;

    /**
     * 解析 Opera 系统的 History And Forecast 报告
     */
    @Slf4j
    @Component
    @DS("work_performance")
    public class HotelKpiHistoryAndForecastParseServiceByOther implements IHotelKpiHistoryAndForecastParseService {
        @Resource
        private IHotelKpiHistoryAndForecastService historyAndForecastService;
        @Resource
        private IHotelKpiCommonSummaryService commonSummaryService;
        @Resource
        private IHotelKpiImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.hotel-kpi.history-and-forecast}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.hotel-kpi}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2024/8/20
         */
        @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 <= 5; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

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

                    // 校验 Date
                    String dateStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(dateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(dateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Date format is incorrect, Date = " + dateStr);
                        }
                    }

                    // 校验 Room Revenue
                    String roomRevenueStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(roomRevenueStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Room Revenue cannot be blank");
                    } else {
                        BigDecimal roomRevenue;
                        try {
                            roomRevenue = new BigDecimal(roomRevenueStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Room Revenue format is incorrect, Room Revenue = " + roomRevenueStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = roomRevenue.abs().toBigInteger().toString().length();
                        if (intLength > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Room Revenue exceeds the limit, Room Revenue = " + roomRevenueStr);
                        }
                    }

                    // 校验 Arr. Rooms
                    String arrivalRoomsStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(arrivalRoomsStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Arr. Rooms cannot be blank");
                    } else {
                        try {
                            int arrivalRooms = Integer.parseInt(arrivalRoomsStr);
                            if (arrivalRooms < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Arr. Rooms cannot be less than 0, Arr. Rooms = " + arrivalRoomsStr);
                            }
                            if (arrivalRooms > 1000000) {
                                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), 6, 0),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Arr. Rooms cannot be greater than 1000000, Arr. Rooms = " + arrivalRoomsStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Arr. Rooms format is incorrect, Arr. Rooms = " + arrivalRoomsStr);
                        }
                    }

                    // 校验 Dep. Rooms
                    String departureRoomsStr = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(departureRoomsStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Dep. Rooms cannot be blank");
                    } else {
                        try {
                            int departureRooms = Integer.parseInt(departureRoomsStr);
                            if (departureRooms < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Dep. Rooms cannot be less than 0, Dep. Rooms = " + departureRoomsStr);
                            }
                            if (departureRooms > 1000000) {
                                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3), 6, 0),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Dep. Rooms cannot be greater than 1000000, Dep. Rooms = " + departureRoomsStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Dep. Rooms format is incorrect, Dep. Rooms = " + departureRoomsStr);
                        }
                    }

                    // 校验 Rooms Sold
                    String roomsSoldStr = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isBlank(roomsSoldStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Rooms Sold cannot be blank");
                    } else {
                        try {
                            int roomsSold = Integer.parseInt(roomsSoldStr);
                            if (roomsSold < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Rooms Sold cannot be less than 0, Rooms Sold = " + roomsSoldStr);
                            }
                            if (roomsSold > 1000000) {
                                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4), 6, 0),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Rooms Sold cannot be greater than 1000000, Rooms Sold = " + roomsSoldStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Rooms Sold format is incorrect, Rooms Sold = " + roomsSoldStr);
                        }
                    }

                    // 校验 ADR
                    String adrStr = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isBlank(adrStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The ADR cannot be blank");
                    } else {
                        BigDecimal adr;
                        try {
                            adr = new BigDecimal(adrStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The ADR format is incorrect, ADR = " + adrStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = adr.abs().toBigInteger().toString().length();
                        if (intLength > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5), 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of ADR exceeds the limit, ADR = " + adrStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check Hotel KPI History and forecast Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, List<Long> dateRange, long logId, 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.HOTEL_KPI_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<HotelKpiHistoryAndForecastBO> boList = parse(propertyDTO, in, dateRange);
                // 保存数据
                historyAndForecastService.insertOrUpdateBatch(propertyDTO.getId(), boList);
                // 处理数据
                handleData(propertyDTO, dateRange.get(0), dateRange.get(1));
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Hotel KPI History and forecast Other report error.", e);
            } finally {
                importLogService.update(logId, operatorId, s3Key, handleResult);
            }
        }

        /**
         * 处理数据 for History And Forecast
         *
         * @param propertyDTO 资产
         * @param startDate   开始日期(yyyyMMdd)
         * @param endDate     结束日期(yyyyMMdd)
         * @author zc
         * @date 2025/9/12
         */
        private void handleData(PropertyDTO propertyDTO, long startDate, long endDate) {
            List<Integer> metricsTypeList = Lists.newArrayList(HotelKpiMetricsEnum.OCC.getMetricsType(),
                    HotelKpiMetricsEnum.ADR.getMetricsType(), HotelKpiMetricsEnum.RM_REVENUE.getMetricsType());
            for (int metricsType : metricsTypeList) {
                commonSummaryService.triggerSetMetricsData(propertyDTO, HotelKpiTriggerTypeCons.HISTORY_AND_FORECAST,
                        startDate, endDate, metricsType);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return HotelKpiHistoryAndForecastBO 集合
         * @author zc
         * @date 2024/7/11
         */
        @Override
        public List<HotelKpiHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try (Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);

                List<HotelKpiHistoryAndForecastBO> resultList = Lists.newArrayList();
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    // 日期
                    String dateStr = CellUtils.convertCellStr(row.getCell(0));
                    LocalDate localDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    long date = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (date < startDate || date > endDate) {
                        continue;
                    }

                    HotelKpiHistoryAndForecastBO bo = new HotelKpiHistoryAndForecastBO();
                    bo.setDateStr(dateStr);

                    // 获取 Revenue
                    String roomRevenueStr = CellUtils.convertCellStr(row.getCell(1));
                    BigDecimal roomRevenue = StringUtils.isBlank(roomRevenueStr) ? null : new BigDecimal(roomRevenueStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    bo.setRoomRevenue(roomRevenue);

                    // 获取 Arr. Rooms
                    String arrivalRoomsStr = CellUtils.convertCellStr(row.getCell(2));
                    Integer arrivalRooms = StringUtils.isBlank(arrivalRoomsStr) ? null : Integer.parseInt(arrivalRoomsStr);
                    bo.setArrivalRooms(arrivalRooms);

                    // 获取 Dep. Rooms
                    String departureRoomsStr = CellUtils.convertCellStr(row.getCell(3));
                    Integer departureRooms = StringUtils.isBlank(departureRoomsStr) ? null : Integer.parseInt(departureRoomsStr);
                    bo.setDepartureRooms(departureRooms);

                    // 获取 Rooms Sold
                    String roomsSoldStr = CellUtils.convertCellStr(row.getCell(4));
                    Integer roomsSold = StringUtils.isBlank(roomsSoldStr) ? null : Integer.parseInt(roomsSoldStr);
                    bo.setRoomsSold(roomsSold);

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

                    resultList.add(bo);
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI History and forecast Other report error.", e);
            }
        }
    }