# ApiOtaParseServiceByOther.java

    package cloud.wconnect.finance.service.api.acota;

    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.finance.pojo.bo.api.ota.AcOtaBO;
    import cloud.wconnect.finance.pojo.bo.api.ota.AcOtaListBO;
    import cloud.wconnect.finance.service.api.IAcApiService;
    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;

    /**
     * OTA other 报告
     *
     * @author zc
     * @date 2023/08/09
     */
    @Slf4j
    @Component
    @DS("finance")
    public class ApiOtaParseServiceByOther implements IApiOtaParseService {
        @Resource
        private IAcApiService acApiService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;

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

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

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

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

                    // CRS #
                    String crsNoStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(crsNoStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The CRS # cannot be blank");
                    } else {
                        if (crsNoStr.length() > 20) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0), 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The CRS # cannot be more than 20 characters");
                        }
                    }
                    // Check in Date
                    String checkInDateStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(checkInDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Check in Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(checkInDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Check in Date format is incorrect, Check in Date = " + checkInDateStr);
                        }
                    }
                    // Check out Date
                    String checkOutDateStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(checkOutDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Check out Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(checkOutDateStr, formatter);
                        } catch (DateTimeParseException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Check out Date format is incorrect, Check out Date = " + checkOutDateStr);
                        }
                    }
                    // Last Name
                    String lastNameStr = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(lastNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Last Name cannot be blank");
                    } else {
                        if (lastNameStr.length() > 100) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3), 100),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Last Name cannot be more than 100 characters");
                        }
                    }
                    // First Name
                    String firstNameStr = CellUtils.convertCellStr(row.getCell(4));
                    if (StringUtils.isBlank(firstNameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The First Name cannot be blank");
                    } else {
                        if (firstNameStr.length() > 100) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4), 100),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The First Name cannot be more than 100 characters");
                        }
                    }
                    // Room Revenue
                    String roomRevenueStr = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isNotBlank(roomRevenueStr)) {
                        BigDecimal roomRevenue;
                        try {
                            roomRevenue = new BigDecimal(roomRevenueStr);
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Room Revenue format is incorrect, Room Revenue = " + roomRevenueStr);
                        }
                        // 校验整数位是否超过限制
                        int intLength = roomRevenue.abs().toBigInteger().toString().length();
                        if (intLength > 7) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5), 7),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Room Revenue exceeds the limit, Room Revenue = " + roomRevenue);
                        }
                    }
                    // Nights
                    String nightsStr = CellUtils.convertCellStr(row.getCell(6));
                    if (StringUtils.isNotBlank(nightsStr)) {
                        try {
                            int nights = Integer.parseInt(nightsStr);
                            if (nights < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Nights cannot be less than 0, Nights = " + nightsStr);
                            }
                            if (nights > 1000000) {
                                throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6), 6, 0),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Nights cannot be greater than 1000000, Nights = " + nightsStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Nights must integer, Nights = " + nightsStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check API Commission OTA Other report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param files       文件
         * @param batchNo     批次编号
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile[] files, String batchNo) {
            List<AcOtaListBO> otaList = Lists.newArrayList();
            for (MultipartFile file : files) {
                try (InputStream inputStream = file.getInputStream()) {
                    otaList.addAll(parse(propertyDTO, inputStream));
                } catch (ParseReportException e) {
                    throw e;
                } catch (Exception e) {
                    throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                            BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                            "Handle import API Commission OTA Other report error", e);
                }
            }

            AcOtaBO otaBO = AcOtaBO.builder()
                    .batchNo(batchNo)
                    .list(otaList)
                    .build();
            acApiService.handleImportOtaReport(propertyDTO, otaBO);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告
         * @return AcOtaListBO 集合
         * @author zc
         * @date 2023/8/9
         */
        @Override
        public List<AcOtaListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            List<AcOtaListBO> resultList = Lists.newArrayList();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try(Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                // 跳过第一行的标题
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);

                    AcOtaListBO acOtaListBo = new AcOtaListBO();
                    // crs no
                    acOtaListBo.setCrsNo(CellUtils.convertCellStr(row.getCell(0)));
                    // arrival date
                    acOtaListBo.setArrivalDateStr(CellUtils.convertCellStr(row.getCell(1)));
                    // departure date
                    acOtaListBo.setDepartureDateStr(CellUtils.convertCellStr(row.getCell(2)));
                    // last name
                    acOtaListBo.setLastName(CellUtils.convertCellStr(row.getCell(3)));
                    // first name
                    acOtaListBo.setFirstName(CellUtils.convertCellStr(row.getCell(4)));
                    // room revenue
                    String roomRevenueStr = CellUtils.convertCellStr(row.getCell(5));
                    acOtaListBo.setRoomRevenue(StringUtils.isBlank(roomRevenueStr) ?
                            BigDecimal.ZERO : new BigDecimal(roomRevenueStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                    // nights
                    acOtaListBo.setNights(Integer.parseInt(CellUtils.convertCellStr(row.getCell(6))));

                    resultList.add(acOtaListBo);
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse API Commission OTA Other report error", e);
            }
        }

    }