# GuestInHouseParseByOther.java

    package cloud.wconnect.frontoffice.service.clc.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.entity.clc.ClcGuestInhFilterConfig;
    import cloud.wconnect.frontoffice.entity.clc.ClcGuestInhImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.clc.GuestInHouseBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhFilterConfigService;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhImportLogService;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    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.text.DecimalFormat;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author yyt
     * 2023/7/31
     */
    @Service
    @DS("logbook")
    public class GuestInHouseParseByOther implements IGuestInHouseParse{

        @Resource
        private IClcGuestInhFilterConfigService clcGuestInhFilterConfigService;
        @Resource
        private IClcGuestInhService clcGuestInhService;
        @Resource
        private IClcGuestInhImportLogService clcGuestInhImportLogService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

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

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

        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OTHER.getDesc().equals(source);
        }

        @Override
        public List<GuestInHouseBO> parsReport(InputStream inputStream, PropertyDTO propertyDTO) {
            try {
                // 未配置过滤配置，则不处理后续逻辑
                List<String> rateCodes = clcGuestInhFilterConfigService.list(new QueryWrapper<ClcGuestInhFilterConfig>()
                                .lambda().eq(ClcGuestInhFilterConfig::getPropertyId, propertyDTO.getId()))
                        .stream().map(ClcGuestInhFilterConfig::getRateCode).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(rateCodes)) {
                    return Collections.emptyList();
                }

                DecimalFormat decimalFormat = new DecimalFormat("0000");
                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;
                    }

                    Cell rateCodeCell = row.getCell(0);
                    String rateCode = CellUtils.convertCellStr(rateCodeCell);
                    if (!rateCodes.contains(rateCode)) {
                        continue;
                    }
                    GuestInHouseBO guestInHouse = new GuestInHouseBO();
                    guestInHouse.setRateCode(rateCode);

                    Cell checkInDateCell = row.getCell(5);
                    guestInHouse.setCheckInDate(CellUtils.convertCellStr(checkInDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    Cell checkOutDateCell = row.getCell(6);
                    guestInHouse.setCheckOutDate(CellUtils.convertCellStr(checkOutDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    Cell companyCell = row.getCell(1);
                    guestInHouse.setCompanyName(CellUtils.convertCellStr(companyCell));

                    Cell firstNameCell = row.getCell(3);
                    guestInHouse.setFirstName(CellUtils.convertCellStr(firstNameCell));
                    Cell lastNameCell = row.getCell(2);
                    guestInHouse.setLastName(CellUtils.convertCellStr(lastNameCell));

                    // 房间号不足4位的补0
                    Cell roomNumberCell = row.getCell(4);
                    guestInHouse.setRoomNumber(StringUtils.isEmpty(CellUtils.convertCellStr(roomNumberCell)) ? "" :
                            decimalFormat.format(Integer.parseInt(CellUtils.convertCellStr(roomNumberCell))));
                    guestInHouses.add(guestInHouse);
                }
                if (CollectionUtils.isEmpty(guestInHouses)) {
                    return Collections.emptyList();
                }

                workbook.close();

                // 数据去重（姓名、房间号、入住日期）
                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/8/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 rateCodeTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String companyTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String lastNameTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String firstNameTitle = CellUtils.convertCellStr(titleRow.getCell(3));
                String roomNumberTitle = CellUtils.convertCellStr(titleRow.getCell(4));
                String checkInDateTitle = CellUtils.convertCellStr(titleRow.getCell(5));
                String departureDateTitle = CellUtils.convertCellStr(titleRow.getCell(6));
                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 rateCodeCell = row.getCell(0);
                    if (Objects.isNull(rateCodeCell) || StringUtils.isBlank(rateCodeCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(rateCodeTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The rate code cannot be empty");
                    } else {
                        // 最多 10 个字
                        if (CellUtils.convertCellStr(rateCodeCell).length() > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(rateCodeTitle, 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The rate code cannot be more than 10 characters");
                        }
                    }

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

                    Cell lastNameCell = row.getCell(2);
                    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 个字
                        if (CellUtils.convertCellStr(lastNameCell).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 firstNameCell = row.getCell(3);
                    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 个字
                        if (CellUtils.convertCellStr(firstNameCell).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 roomNumberCell = row.getCell(4);
                    if (Objects.nonNull(roomNumberCell) && StringUtils.isNotBlank(roomNumberCell.toString())) {
                        // 最多 10 个字
                        if (CellUtils.convertCellStr(roomNumberCell).length() > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle, 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The room number cannot be more than 10 characters");
                        }
                    }

                    Cell checkInDateCell = row.getCell(5);
                    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(6);
                    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/8/3
         **/
        @Override
        public ClcGuestInhImportLog handleImportLog(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, int userId) {
            String key = toS3(tenantBO.getSymbol(), propertyDTO.getAbbr(), file);
            ClcGuestInhImportLog importLog = new ClcGuestInhImportLog().setPropertyId(propertyDTO.getId())
                    .setStatus(ReportImportResultCons.IMPORT_IN_PROGRESS).setUrl(key)
                    .setCreatedBy(userId).setCreatedTime(DateTimeUtils.nowTimestamp());
            clcGuestInhImportLogService.save(importLog);
            return importLog;
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/8/3
         **/
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + guestInHouseS3key +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());
            try {
                // 上传文件
                amazonS3Service.uploadFile(S3BucketFunctionCons.CLC_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/8/3
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, ClcGuestInhImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<GuestInHouseBO> guestInHouses = parsReport(inputStream, propertyDTO);
                clcGuestInhService.handleGuestInHouseData(propertyDTO, userId, guestInHouses);
            } 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/8/5
         **/
        private void importSuccess(ClcGuestInhImportLog importLog) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                ClcGuestInhImportLog updateLog = new ClcGuestInhImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                clcGuestInhImportLogService.updateById(updateLog);
            });
        }

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

    }