# PastReservationGuestInHouseParseByOtherManualImport.java

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

    import cloud.wconnect.commonlib.cons.*;
    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.GuestInHouseBO;
    import cloud.wconnect.frontoffice.pojo.bo.pastreservation.GuestNameBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationImportLogService;
    import cloud.wconnect.frontoffice.service.pastreservation.IPastReservationOpGuestinHouseService;
    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.collections.CollectionUtils;
    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.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author yyt
     * 2024/10/3
     */
    @Service
    @DS("logbook")
    public class PastReservationGuestInHouseParseByOtherManualImport implements IPastReservationReportParse {

        @Resource
        private IPastReservationImportLogService pastReservationImportLogService;
        @Resource
        private IPastReservationOpGuestinHouseService pastReservationOpGuestinHouseService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        @Value("${aws-s3.third-party.key.past-reservation.guest-in-house}")
        private String guestInHouseS3key;

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

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

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

                    GuestInHouseBO guestInHouse = new GuestInHouseBO();
                    Cell firstNameCell = row.getCell(1);
                    guestInHouse.setFirstName(CellUtils.convertCellStr(firstNameCell));
                    Cell lastNameCell = row.getCell(0);
                    guestInHouse.setLastName(CellUtils.convertCellStr(lastNameCell));

                    guestInHouse.setFullName(new GuestNameBO(guestInHouse.getFirstName(), guestInHouse.getLastName()).getFullName());

                    Cell roomNumberCell = row.getCell(2);
                    guestInHouse.setRoomNumber(CellUtils.convertCellStr(roomNumberCell));
                    Cell checkInDateCell = row.getCell(3);
                    guestInHouse.setCheckInDate(CellUtils.convertCellStr(checkInDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    Cell checkOutDateCell = row.getCell(4);
                    guestInHouse.setCheckOutDate(CellUtils.convertCellStr(checkOutDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    guestInHouses.add(guestInHouse);
                }

                workbook.close();

                if (CollectionUtils.isEmpty(guestInHouses)) {
                    return Collections.emptyList();
                }

                // 数据去重（姓名、房间号、入住日期）
                return guestInHouses.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(GuestInHouseBO::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/10/3
         **/
        @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 firstNameTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String lastNameTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String roomNumberTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String checkInDateTitle = CellUtils.convertCellStr(titleRow.getCell(3));
                String departureDateTitle = CellUtils.convertCellStr(titleRow.getCell(4));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

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

                    Cell firstNameCell = row.getCell(1);
                    if (Objects.isNull(firstNameCell) || StringUtils.isBlank(firstNameCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(firstNameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The first name cannot be empty");
                    } else {
                        // 最多 60 个字
                        String firstName = CellUtils.convertCellStr(firstNameCell);
                        if (firstName.length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(firstNameTitle, 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The first name cannot be more than 60 characters");
                        }
                    }

                    Cell lastNameCell = row.getCell(0);
                    if (Objects.isNull(lastNameCell) || StringUtils.isBlank(lastNameCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(lastNameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The last name cannot be empty");
                    } else {
                        // 最多 60 个字
                        String lastName = CellUtils.convertCellStr(lastNameCell);
                        if (lastName.length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(lastNameTitle, 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The last name cannot be more than 60 characters");
                        }
                    }

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

                    Cell checkInDateCell = row.getCell(3);
                    if (Objects.isNull(checkInDateCell) || StringUtils.isBlank(checkInDateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(checkInDateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The check-in date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(checkInDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(checkInDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The check-in date format error");
                        }
                    }

                    Cell departureDateCell = row.getCell(4);
                    if (Objects.isNull(departureDateCell) || StringUtils.isBlank(departureDateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(departureDateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The departure date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(departureDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(departureDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The departure date format error");
                        }
                    }

                    // 入住日期不能晚于退房日期
                    LocalDate checkInDate = LocalDate.parse(CellUtils.convertCellStr(checkInDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    LocalDate departureDate = LocalDate.parse(CellUtils.convertCellStr(departureDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    if (checkInDate.isAfter(departureDate)) {
                        throw new BadRequestException(CommonErrorI18nConstant.CHECK_IN_DATE_CANNOT_GREATER_THAN_CHECK_OUT_DATE,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The check-in date cannot be later than check-out date");
                    }
                }
            } 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/10/3
         **/
        @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.GUEST_IN_HOUSE,
                    ReportImportResultCons.IMPORT_IN_PROGRESS, key, userId);
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/10/3
         **/
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + guestInHouseS3key +
                    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/10/3
         **/
        @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<GuestInHouseBO> guestInHouses = parsReport(inputStream);
                pastReservationOpGuestinHouseService.handleGuestInHouseData(propertyDTO, guestInHouses, userId);
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "handle import guest in house report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/10/3
         **/
        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/10/3
         **/
        private void importFail(PastReservationImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                PastReservationImportLog updateLog = new PastReservationImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_FAIL);
                pastReservationImportLogService.updateById(updateLog);
            });
        }

    }