# TaPortalParseServiceByOther.java

    package cloud.wconnect.finance.service.ta.portal;

    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.cons.S3BucketFunctionCons;
    import cloud.wconnect.finance.pojo.bo.ta.portal.TaPortalBO;
    import cloud.wconnect.finance.pojo.bo.ta.portal.TaPortalListBO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.ta.ITaComparePortalService;
    import cloud.wconnect.finance.service.ta.ITaImportLogService;
    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;

    /**
     * Portal Other 报告
     *
     * @author zc
     * @date 2023/07/19
     */
    @Slf4j
    @Component
    @DS("finance")
    public class TaPortalParseServiceByOther implements ITaPortalParseService {
        @Resource
        private ITaComparePortalService comparePortalService;
        @Resource
        private ITaImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.ta-commission.portal}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.ta}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2024/8/22
         */
        @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 <= 10; i++) {
                    titleList.add(CellUtils.convertCellStr(titleRow.getCell(i)));
                }

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

                    // Arrival Date
                    String arrivalDateStr = CellUtils.convertCellStr(row.getCell(0));
                    if (StringUtils.isBlank(arrivalDateStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(0)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Arrival Date cannot be blank");
                    } else {
                        try {
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD, Locale.ENGLISH);
                            LocalDate.parse(arrivalDateStr, 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 Arrival Date format is incorrect, Arrival Date = " + arrivalDateStr);
                        }
                    }

                    // Name
                    String nameStr = CellUtils.convertCellStr(row.getCell(1));
                    if (StringUtils.isBlank(nameStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Name cannot be blank");
                    } else {
                        if (nameStr.length() > 200) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(1), 200),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Name cannot be longer than 200 characters");
                        }
                    }

                    // Rooms
                    String roomsStr = CellUtils.convertCellStr(row.getCell(2));
                    if (StringUtils.isBlank(roomsStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Rooms cannot be blank");
                    } else {
                        try {
                            int rooms = Integer.parseInt(roomsStr);
                            if (rooms < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Rooms cannot be less than 0, Rooms = " + roomsStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(2)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Rooms must integer, Rooms = " + roomsStr);
                        }
                    }

                    // Credit Card Number(last four)
                    String creditCardNumberStr = CellUtils.convertCellStr(row.getCell(3));
                    if (StringUtils.isBlank(creditCardNumberStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Credit Card Number(last four) cannot be blank");
                    } else {
                        if (creditCardNumberStr.length() > 4) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(3), 4),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Credit Card Number(last four) cannot be longer than 4 characters");
                        }
                    }

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

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

                    // 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_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(6)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Nights must integer, Nights = " + nightsStr);
                        }
                    }

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

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

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

                    // Customer Number
                    String customerNumberStr = CellUtils.convertCellStr(row.getCell(10));
                    if (StringUtils.isBlank(customerNumberStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(10)),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The Customer Number cannot be blank");
                    } else {
                        try {
                            int customerNumber = Integer.parseInt(customerNumberStr);
                            if (customerNumber < 0) {
                                throw new BadRequestException(CommonErrorI18nConstant.CANNOT_LESS_THAN_ZERO,
                                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(10)),
                                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                        "The Customer Number cannot be less than 0, Customer Number = " + customerNumberStr);
                            }
                        } catch (NumberFormatException e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_INTEGER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(10)),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Customer Number must integer, Customer Number = " + customerNumberStr);
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check TA Portal Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param date        报告数据日期(时间戳)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long date, 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.TA_IMPORT_RECORD, file, s3Key);

                // 解析报告
                List<TaPortalListBO> taPortalList = parse(propertyDTO, in);

                TaPortalBO portalBO = TaPortalBO.builder()
                        .dataDate(DateTimeUtils.timestampToStr(date, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone()))
                        .list(taPortalList).build();
                // 处理报告
                comparePortalService.handlePortalReport(propertyDTO, portalBO);
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Portal Other report error.", e);
            } finally {
                importLogService.update(logId, handleResult, operatorId, s3Key);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告
         * @return TaPortalListBO 集合
         * @author zc
         * @date 2023/7/19
         */
        @Override
        public List<TaPortalListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            try(Workbook workbook = WorkbookFactory.create(in)) {
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                        .getInternationalization().getNumber().getCalculationRule());
                int scale = BaseConstant.DATA_PRECISION;

                Sheet sheet = workbook.getSheetAt(0);

                List<TaPortalListBO> resultList = Lists.newArrayList();
                // 跳过第一行的标题
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row currentRow = sheet.getRow(i);

                    TaPortalListBO taPortal = new TaPortalListBO();
                    taPortal.setArrivalDay(CellUtils.convertCellStr(currentRow.getCell(0)));
                    taPortal.setName(CellUtils.convertCellStr(currentRow.getCell(1)));
                    taPortal.setRooms(Integer.parseInt(CellUtils.convertCellStr(currentRow.getCell(2))));
                    taPortal.setLastFourDigits(CellUtils.convertCellStr(currentRow.getCell(3)));

                    String rateStr = CellUtils.convertCellStr(currentRow.getCell(4)).trim();
                    taPortal.setRate(StringUtils.isBlank(rateStr) ?
                            BigDecimal.ZERO : new BigDecimal(rateStr).setScale(scale, roundingMode));

                    String totalChargedStr = CellUtils.convertCellStr(currentRow.getCell(5)).trim();
                    taPortal.setTotalCharged(StringUtils.isBlank(totalChargedStr) ?
                            BigDecimal.ZERO : new BigDecimal(totalChargedStr).setScale(scale, roundingMode));

                    taPortal.setNights(Integer.parseInt(CellUtils.convertCellStr(currentRow.getCell(6))));
                    taPortal.setAirline(CellUtils.convertCellStr(currentRow.getCell(7)));
                    taPortal.setVoucher(CellUtils.convertCellStr(currentRow.getCell(8)));
                    taPortal.setDepartureDay(CellUtils.convertCellStr(currentRow.getCell(9)));
                    taPortal.setCustomerNumber(Integer.parseInt(CellUtils.convertCellStr(currentRow.getCell(10))));

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