# ApiParseServiceByOther.java

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

    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.api.AcApiBO;
    import cloud.wconnect.finance.pojo.bo.api.api.AcApiListBO;
    import cloud.wconnect.finance.pojo.dto.api.ConflictApiDTO;
    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.Iterator;
    import java.util.List;
    import java.util.Locale;

    /**
     * API Other 报告
     *
     * @author zc
     * @date 2023/08/08
     */
    @Slf4j
    @Component
    @DS("finance")
    public class ApiParseServiceByOther implements IApiParseService {
        @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/8
         */
        @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)) {
                Iterator<Sheet> sheetIterator = workbook.sheetIterator();
                while (sheetIterator.hasNext()) {
                    Sheet sheet = sheetIterator.next();

                    // 获取最大行数
                    int lastRowNum = sheet.getLastRowNum();
                    // 若只包含标题，直接返回
                    if (lastRowNum < 1) {
                        return;
                    }

                    // 提取标题
                    List<String> titleList = Lists.newArrayList();
                    Row titleRow = sheet.getRow(0);
                    for (int i = 0; i <= 7; i++) {
                        titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                    }

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

                        // Airline
                        String airlineStr = CellUtils.convertCellStr(row.getCell(0));
                        if (StringUtils.isBlank(airlineStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Airline cannot be blank");
                        } else {
                            if (airlineStr.length() > 100) {
                                throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0), 100),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Airline Code cannot be more than 100 characters");
                            }
                        }

                        // Conf. No.
                        String confNoStr = CellUtils.convertCellStr(row.getCell(1));
                        if (StringUtils.isNotBlank(confNoStr)) {
                            if (confNoStr.length() > 20) {
                                throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), 20),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Conf. No. cannot be more than 20 characters");
                            }
                        }

                        // Check-In Date
                        String checkInDateStr = CellUtils.convertCellStr(row.getCell(2));
                        if (StringUtils.isBlank(checkInDateStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                    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(2), BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Check-In Date format is incorrect, Check-In Date = " + checkInDateStr);
                            }
                        }

                        // 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() > 255) {
                                throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3), 255),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Last Name cannot be more than 255 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() > 255) {
                                throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(4), 255),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The First Name cannot be more than 255 characters");
                            }
                        }

                        // Room Amounts
                        String roomAmountsStr = CellUtils.convertCellStr(row.getCell(5));
                        if (StringUtils.isBlank(roomAmountsStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Room Amounts cannot be blank");
                        } else {
                            BigDecimal roomAmounts;
                            try {
                                roomAmounts = new BigDecimal(roomAmountsStr);
                            } catch (NumberFormatException e) {
                                throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Room Amounts format is incorrect, Room Amounts = " + roomAmountsStr);
                            }
                            // 校验整数位是否超过限制
                            int intLength = roomAmounts.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 Amounts exceeds the limit, Room Amounts = " + roomAmountsStr);
                            }
                        }

                        // Nights
                        String nightsStr = CellUtils.convertCellStr(row.getCell(6));
                        if (StringUtils.isBlank(nightsStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Nights cannot be blank");
                        } else {
                            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_NUMBER,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Nights format is incorrect, Nights = " + nightsStr);
                            }
                        }

                        // Total Rooms
                        String totalRoomsStr = CellUtils.convertCellStr(row.getCell(7));
                        if (StringUtils.isBlank(totalRoomsStr)) {
                            throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Total Rooms cannot be blank");
                        } else {
                            try {
                                int totalRooms = Integer.parseInt(totalRoomsStr);
                                if (totalRooms < 0) {
                                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                            i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7)),
                                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                            "The Total Rooms cannot be less than 0, Total Rooms = " + totalRoomsStr);
                                }
                                if (totalRooms > 1000000) {
                                    throw new BadRequestException(CommonErrorI18nConstant.NUMBER_OVERLENGTH,
                                            i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7), 6, 0),
                                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                            "The Total Rooms cannot be greater than 1000000, Total Rooms = " + totalRoomsStr);
                                }
                            } catch (NumberFormatException e) {
                                throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(7)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Total Rooms format is incorrect, Total Rooms = " + totalRoomsStr);
                            }
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check API Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param batchNo     批次编号
         * @return ConflictApiDTO
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public ConflictApiDTO handleData(PropertyDTO propertyDTO, MultipartFile file, String batchNo) {
            try (InputStream in = file.getInputStream()) {
                // 处理 API 报告数据
                List<AcApiListBO> apiList = parse(propertyDTO, in);

                AcApiBO apiBO = AcApiBO.builder()
                        .batchNo(batchNo)
                        .list(apiList)
                        .build();
                return acApiService.handleImportApiReport(propertyDTO, apiBO);
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import API report error.", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告
         * @return ApiListBO 集合
         * @author zc
         * @date 2023/8/8
         */
        @Override
        public List<AcApiListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            List<AcApiListBO> resultList = Lists.newArrayList();

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try(Workbook workbook = WorkbookFactory.create(in)) {
                for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                    Sheet sheet = workbook.getSheetAt(i);
                    // 跳过第一行的标题
                    for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                        Row row = sheet.getRow(r);

                        AcApiListBO api = new AcApiListBO();
                        api.setInvoiceNo(sheet.getSheetName());
                        api.setAirline(CellUtils.convertCellStr(row.getCell(0)));
                        api.setConfNo(CellUtils.convertCellStr(row.getCell(1)));
                        api.setCheckInStr(CellUtils.convertCellStr(row.getCell(2)));
                        api.setLastName(CellUtils.convertCellStr(row.getCell(3)));
                        api.setFirstName(CellUtils.convertCellStr(row.getCell(4)));

                        String roomCosts = CellUtils.convertCellStr(row.getCell(5)).trim();
                        api.setRoomCosts(StringUtils.isBlank(roomCosts) ?
                                BigDecimal.ZERO : new BigDecimal(roomCosts).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                        String nights = CellUtils.convertCellStr(row.getCell(6));
                        api.setNights(StringUtils.isBlank(nights) ? BaseConstant.ZERO : Integer.parseInt(nights));

                        String totalRoom = CellUtils.convertCellStr(row.getCell(7));
                        api.setTotalRoom(StringUtils.isBlank(totalRoom) ? BaseConstant.ZERO : Integer.parseInt(totalRoom));

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

    }