# RateShopHistoryAndForecastServiceByOther.java

    package cloud.wconnect.rateshop.service.rateshop.historyandforecast;

    import cloud.wconnect.commonlib.component.BeanMapper;
    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.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.S3BucketFunctionCons;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    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.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.Autowired;
    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.*;

    /**
     * 解析Other来源的History And Forecast报告
     *
     * @author lichen
     * @date 2024/7/3
     */
    @Component
    @DS("rate_shop")
    @Slf4j
    public class RateShopHistoryAndForecastServiceByOther implements IRateShopHistoryAndForecastService {

        @Autowired
        private RoomsConfigInternalService roomsConfigInternalService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private IReportImportLogService importLogService;
        @Autowired
        private IRateShopOccForecastService rateShopOccForecastService;
        @Autowired
        private IPropertyOperationService propertyOperationService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${aws-s3.third-party.key.rate-shop.history-and-forecast}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.rate-shop}")
        private long fileMaxSize;

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

        /**
         * 解析报告
         *
         * @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
         */
        @Override
        public 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 daily check-in info excel error");
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @author lichen
         * @date 2024/8/14
         */
        @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 startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @return void
         * @author lichen
         * @date 2024/8/14
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long startDate, long endDate, long logId, int userId) {
            String tenantSymbol = propertyDTO.getTenantSymbol();
            String abbr = propertyDTO.getAbbr();

            String key = tenantSymbol + "/" + abbr + "/" + s3FilePath +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());

            boolean result = true;
            try (InputStream inputStream = file.getInputStream()) {
                amazonS3Service.uploadFile(S3BucketFunctionCons.RATE_SHOP_IMPORT_RECORD, file, key);
                //解析报告
                List<HistoryAndForecastForRateShopBO> boList = parse(inputStream, propertyDTO, startDate, endDate);

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

                //保存occ数据
                rateShopOccForecastService.saveOccForecast(propertyDTO, userId, boList);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result = false;
            } finally {
                importLogService.updateLog(logId, userId, key, result);
            }
        }
    }