# TaCreditCardParseServiceByOther.java

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

    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.creditcard.TaCreditCardBO;
    import cloud.wconnect.finance.pojo.bo.ta.creditcard.TaCreditCardListBO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.ta.ITaCompareCreditCardService;
    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;

    /**
     * 解析 Credit Card Other 报告
     *
     * @author zc
     * @date 2023/07/19
     */
    @Slf4j
    @Component
    @DS("finance")
    public class TaCreditCardParseServiceByOther implements ITaCreditCardParseService {
        @Resource
        private ITaCompareCreditCardService compareCreditCardService;
        @Resource
        private ITaImportLogService importLogService;
        @Resource
        private I18nMessageUtils i18nMessageUtils;
        @Resource
        private AmazonS3Service amazonS3Service;

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

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

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

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

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

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

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

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

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

                    // Room Revenue
                    String roomRevenueStr = CellUtils.convertCellStr(row.getCell(5));
                    if (StringUtils.isBlank(roomRevenueStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(5)),
                                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(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 = " + roomRevenueStr);
                        }
                    }

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

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

                    // Total Charged
                    String totalChargedStr = CellUtils.convertCellStr(row.getCell(8));
                    if (StringUtils.isBlank(totalChargedStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(8)),
                                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(8)),
                                    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(8), 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The integer of Total Charged exceeds the limit, Total Charged = " + totalChargedStr);
                        }
                    }

                    // Credit Card Number(last four)
                    String creditCardNumberStr = CellUtils.convertCellStr(row.getCell(9));
                    if (StringUtils.isBlank(creditCardNumberStr)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(titleList.get(9)),
                                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(9), 4),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The Credit Card Number(last four) cannot be longer than 4 characters");
                        }
                    }
                }
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle check TA Credit Card Other report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param date        报告数据日期(时间戳)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/21
         */
        @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<TaCreditCardListBO> taCreditCardList = parse(propertyDTO, in);

                TaCreditCardBO creditCardBO = TaCreditCardBO.builder()
                        .dataDate(DateTimeUtils.timestampToStr(date, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone()))
                        .list(taCreditCardList).build();
                // 处理报告
                compareCreditCardService.handleCreditCardReport(propertyDTO, creditCardBO);
            } catch (Exception e) {
                handleResult = false;
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import TA Credit Card Other report error.", e);
            } finally {
                importLogService.update(logId, handleResult, operatorId, s3Key);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in       报告
         * @return TaCreditCardListBO 集合
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public List<TaCreditCardListBO> parse(PropertyDTO propertyDTO, InputStream in) throws ParseReportException {
            try(Workbook workbook = WorkbookFactory.create(in)){
                Sheet sheet = workbook.getSheetAt(0);
                // 获取最大行数
                int lastRowNum = sheet.getLastRowNum();

                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                        .getInternationalization().getNumber().getCalculationRule());
                int scale = BaseConstant.DATA_PRECISION;

                List<TaCreditCardListBO> taCreditCardList = Lists.newArrayList();
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);

                    TaCreditCardListBO taCreditCard = new TaCreditCardListBO();
                    taCreditCard.setCardType(CellUtils.convertCellStr(row.getCell(0)));
                    taCreditCard.setName(CellUtils.convertCellStr(row.getCell(1)));
                    taCreditCard.setRoomNo(CellUtils.convertCellStr(row.getCell(2)));
                    taCreditCard.setArrivalDay(CellUtils.convertCellStr(row.getCell(3)));
                    taCreditCard.setDepartureDay(CellUtils.convertCellStr(row.getCell(4)));
                    taCreditCard.setRoomRevenue(new BigDecimal(CellUtils.convertCellStr(row.getCell(5)))
                            .setScale(scale, roundingMode));
                    taCreditCard.setFbRevenue(new BigDecimal(CellUtils.convertCellStr(row.getCell(6)))
                            .setScale(scale, roundingMode));
                    taCreditCard.setNonRevenue(new BigDecimal(CellUtils.convertCellStr(row.getCell(7)))
                            .setScale(scale, roundingMode));
                    taCreditCard.setTotalCharged(new BigDecimal(CellUtils.convertCellStr(row.getCell(8)))
                            .setScale(scale, roundingMode));
                    taCreditCard.setLastFourDigits(CellUtils.convertCellStr(row.getCell(9)));

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