# PastReservationCreditLimitParseByOtherManualImport.java

    package cloud.wconnect.frontoffice.service.pastreservation.report.manualimport.creditlimit;

    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.bo.SymbolBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.frontoffice.cons.S3BucketFunctionCons;
    import cloud.wconnect.frontoffice.cons.pastreservation.PastReservationReportTypeCons;
    import cloud.wconnect.frontoffice.entity.pastreservation.PastReservationImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.pastreservation.CreditLimitInfoBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationCreditLimitService;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationImportLogService;
    import cloud.wconnect.frontoffice.service.pastreservation.report.manualimport.IPastReservationReportParse;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author yyt
     * 2024/12/12
     */
    @Service
    @DS("logbook")
    public class PastReservationCreditLimitParseByOtherManualImport implements IPastReservationReportParse {

        @Resource
        private IPastReservationImportLogService pastReservationImportLogService;
        @Resource
        private IPastReservationCreditLimitService pastReservationCreditLimitService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        @Value("${aws-s3.third-party.key.past-reservation.credit-limit}")
        private String creditLimitS3key;

        @Value("${file-max-size.import-report.past-reservation}")
        private Long importReportFileMaxSize;

        /**
         * 判断支持的平台
         *
         * @param source     平台数据源
         * @param reportType 报告类型
         * @return boolean
         * @author yyt
         * @date 2024/12/12
         */
        @Override
        public boolean supports(String source, int reportType) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source) && PastReservationReportTypeCons.CREDIT_LIMIT == reportType;
        }

        /**
         * 解析报告数据
         *
         * @param inputStream 文件流
         * @return PaymentInfoBO
         * @author yyt
         * @date 2024/12/12
         */
        private List<CreditLimitInfoBO> parsReport(InputStream inputStream) {
            try {
                Workbook workbook = WorkbookFactory.create(inputStream);
                Sheet sheet = workbook.getSheetAt(0);
                List<CreditLimitInfoBO> creditLimitInfoBOS = Lists.newArrayListWithExpectedSize(sheet.getLastRowNum());
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    CreditLimitInfoBO creditLimitInfo = new CreditLimitInfoBO();
                    Cell fullNameCell = row.getCell(0);
                    creditLimitInfo.setFullName(CellUtils.convertCellStr(fullNameCell));
                    Cell roomNumberCell = row.getCell(1);
                    creditLimitInfo.setRoomNumber(CellUtils.convertCellStr(roomNumberCell));
                    Cell totalBalanceCell = row.getCell(2);
                    String totalBalance = CellUtils.convertCellStr(totalBalanceCell);
                    creditLimitInfo.setTotalBalance(new BigDecimal(totalBalance));
                    Cell totalApprovalAmountCell = row.getCell(3);
                    String totalApprovalAmount = CellUtils.convertCellStr(totalApprovalAmountCell);
                    creditLimitInfo.setTotalApprovalAmount(new BigDecimal(totalApprovalAmount));
                    creditLimitInfoBOS.add(creditLimitInfo);
                }

                workbook.close();

                // 数据去重（姓名、房间号）
                return creditLimitInfoBOS.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(CreditLimitInfoBO::getUniKey))), ArrayList::new));
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/12/12
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));

            try (InputStream in = file.getInputStream();
                 Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row titleRow = sheet.getRow(0);
                if (Objects.isNull(titleRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                String fullNameTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String roomNumberTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String totalBalanceTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String totalApprovalAmountTitle = CellUtils.convertCellStr(titleRow.getCell(3));

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell fullNameCell = row.getCell(0);
                    if (Objects.isNull(fullNameCell) || StringUtils.isBlank(fullNameCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(fullNameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The full name cannot be empty");
                    } else {
                        String fullName = CellUtils.convertCellStr(fullNameCell);
                        if (fullName.length() > 255) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(fullNameTitle, 255),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The full name cannot be more than 255 characters");
                        }
                    }

                    Cell roomNumberCell = row.getCell(1);
                    if (Objects.nonNull(roomNumberCell) && CellUtils.convertCellStr(roomNumberCell).length() > 8) {
                        throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle, 8),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The room number cannot be more than 8 characters");
                    }

                    Cell totalBalanceCell = row.getCell(2);
                    if(Objects.isNull(totalBalanceCell) || StringUtils.isBlank(totalBalanceCell.toString())){
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalBalanceTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The total balance cannot be empty");
                    } else {
                        BigDecimal totalBalance;
                        try {
                            totalBalance = new BigDecimal(CellUtils.convertCellStr(totalBalanceCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalBalanceTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The total balance must be a number");
                        }
                        if (totalBalance.toBigInteger().toString().length() > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalBalanceTitle, 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The total balance exceed the limit");
                        }
                    }

                    Cell totalApprovalAmountCell = row.getCell(3);
                    if(Objects.isNull(totalApprovalAmountCell) || StringUtils.isBlank(totalApprovalAmountCell.toString())){
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalApprovalAmountTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The total approval amount cannot be empty");
                    } else {
                        BigDecimal totalApprovalAmount;
                        try {
                            totalApprovalAmount = new BigDecimal(CellUtils.convertCellStr(totalApprovalAmountCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalApprovalAmountTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The total approval amount must be a number");
                        }
                        if (totalApprovalAmount.toBigInteger().toString().length() > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(totalApprovalAmountTitle, 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The total approval amount exceed the limit");
                        }
                    }
                }
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param file        文件
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/12/12
         **/
        @Override
        public PastReservationImportLog handleImportLog(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, int userId) {
            String key = toS3(tenantBO.getSymbol(), propertyDTO.getAbbr(), file);

            return pastReservationImportLogService.add(propertyDTO.getId(), PastReservationReportTypeCons.CREDIT_LIMIT,
                    ReportImportResultCons.IMPORT_IN_PROGRESS, key, userId);
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/12/12
         **/
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + creditLimitS3key +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());
            try {
                // 上传文件
                amazonS3Service.uploadFile(S3BucketFunctionCons.PAST_RESERVATION_IMPORT_RECORD, file, key);
            } catch (Exception e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Uploading to s3 failure", e);
            }
            return key;
        }

        /**
         * 处理文件
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/12/12
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, PastReservationImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<CreditLimitInfoBO> creditLimitInfoBOS = parsReport(inputStream);
                pastReservationCreditLimitService.handleCreditLimitData(propertyDTO, creditLimitInfoBOS, userId);
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "handle import credit limit report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/12/12
         **/
        private void importSuccess(PastReservationImportLog importLog) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                PastReservationImportLog updateLog = new PastReservationImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                pastReservationImportLogService.updateById(updateLog);
            });
        }

        /**
         * 导入失败
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/12/12
         **/
        private void importFail(PastReservationImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                PastReservationImportLog updateLog = new PastReservationImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_FAIL);
                pastReservationImportLogService.updateById(updateLog);
            });
        }

    }