# GuestInHouseParseByPep.java

    package cloud.wconnect.frontoffice.service.clc.guestinhouse;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    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.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.IClcHandleFileService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.text.DecimalFormat;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author yyt
     * 2026/1/29
     */
    @Service
    @DS("logbook")
    @Slf4j
    @RequiredArgsConstructor
    public class GuestInHouseParseByPep implements IGuestInHouseParse {

        private final IClcGuestInhImportLogService clcGuestInhImportLogService;
        private final AmazonS3Service amazonS3Service;
        private final IClcGuestInhFilterConfigService clcGuestInhFilterConfigService;
        private final IClcHandleFileService clcHandleFileService;

        @Value("${file-max-size.import-report.clc}")
        private Long importReportFileMaxSize;
        @Value("${aws-s3.third-party.key.clc.guest-in-house}")
        private String guestInHouseS3key;

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author yyt
         * @date 2026/1/29
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.PEP.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param inputStream 文件流
         * @param propertyDTO 资产DTO
         * @return 在住客人信息
         * @author yyt
         * @date 2026/1/29
         */
        @Override
        public List<GuestInHouseBO> parsReport(InputStream inputStream, PropertyDTO propertyDTO) {
            // 未配置过滤配置，则不处理后续逻辑
            List<String> rateCodes = clcGuestInhFilterConfigService.listForRateCode(propertyDTO.getId());
            if (CollectionUtils.isEmpty(rateCodes)) {
                return Collections.emptyList();
            }

            DecimalFormat decimalFormat = new DecimalFormat("0000");
            try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream)) {
                // 获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);

                // 构建返回集合
                List<GuestInHouseBO> guestInHouses = Lists.newArrayList();

                for (CSVRecord csvRecord : iterable) {
                    // 跳过第一行标题
                    if (csvRecord.getRecordNumber() == 1) {
                        continue;
                    }

                    // 行数据不完整时，跳过
                    if (csvRecord.values().length < 13) {
                        continue;
                    }

                    // 房间号
                    String room = CsvFileUtils.get(csvRecord, "N");
                    if(StringUtils.isBlank(room)){
                        continue;
                    }
                    // 房间号不足4位的补0
                    String roomNumber = decimalFormat.format(Integer.parseInt(room));

                    // 到店日期
                    String arrivalDateStr = CsvFileUtils.get(csvRecord, "k");
                    if (StringUtils.isBlank(arrivalDateStr)) {
                        continue;
                    }
                    // 格式化入住日期
                    String checkInDate = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(arrivalDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                    // 获取rate code
                    String rateCode = CsvFileUtils.get(csvRecord, "P");
                    if (StringUtils.isBlank(rateCode) || !rateCodes.contains(rateCode)) {
                        continue;
                    }

                    // 离店日期
                    String departureDateStr = CsvFileUtils.get(csvRecord, "L");
                    if (StringUtils.isBlank(departureDateStr)) {
                        continue;
                    }
                    // 格式化离店日期
                    String checkOutDate = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(departureDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                    // 名称
                    String guestName = CsvFileUtils.get(csvRecord, "F");

                    GuestInHouseBO guestInHouse = new GuestInHouseBO();
                    guestInHouse.setRateCode(rateCode);
                    guestInHouse.setCheckInDate(checkInDate);
                    guestInHouse.setCheckOutDate(checkOutDate);
                    guestInHouse.setCompanyName(CsvFileUtils.get(csvRecord, "G"));
                    // 设置 First Name Last Name
                    String[] fullNames = guestName.split(", ");
                    if (fullNames.length >= 2) {
                        guestInHouse.setFirstName(fullNames[0]);
                        guestInHouse.setLastName(fullNames[1]);
                    } else {
                        guestInHouse.setFirstName(fullNames[0]);
                        guestInHouse.setLastName("");
                    }
                    guestInHouse.setRoomNumber(roomNumber);
                    guestInHouses.add(guestInHouse);
                }

                // 数据去重（姓名、房间号、入住日期）
                return guestInHouses.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(GuestInHouseBO::getUniKey))), ArrayList::new));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse pep [IN HOUSE] report error", e);
            }
        }

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

            try (InputStream in = file.getInputStream()) {
                PepFileCheckUtils.checkInHouseGuestReportFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing pep [IN HOUSE] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.frontoffice.entity.clc.ClcGuestInhImportLog
         * @author yyt
         * @date 2026/1/29
         */
        @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 java.lang.String
         * @author yyt
         * @date 2026/1/29
         */
        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 pep [IN HOUSE] file to s3 failure", e);
            }
            return key;
        }

        /**
         * 处理文件
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2026/1/29
         */
        @Override
        public void handleFile(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, ClcGuestInhImportLog importLog,
                               Integer userId) {
            clcHandleFileService.sendGuestInHouseEvent(tenantBO, propertyDTO, file, SystemPlatformEnum.PEP.getDesc(), importLog, userId);
        }

    }