# ArrivalFileParseByPep.java

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

    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.ClcMissingReport;
    import cloud.wconnect.frontoffice.pojo.bo.clc.ArrivalBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.clc.IClcArrivalDetailedFilterConfigService;
    import cloud.wconnect.frontoffice.service.clc.IClcGuestInhFilterConfigService;
    import cloud.wconnect.frontoffice.service.clc.IClcHandleFileService;
    import cloud.wconnect.frontoffice.service.clc.IClcMissingReportService;
    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.time.LocalDate;
    import java.time.ZoneId;
    import java.util.*;

    import static java.util.stream.Collectors.toMap;

    /**
     * 解析 arrival 报告
     *
     * @author yyt
     * 2026/1/29
     */
    @Service
    @DS("logbook")
    @Slf4j
    @RequiredArgsConstructor
    public class ArrivalFileParseByPep implements IArrivalFileParse {

        private final IClcArrivalDetailedFilterConfigService clcArrivalDetailedFilterConfigService;
        private final IClcMissingReportService clcMissingReportService;
        private final IClcHandleFileService clcHandleFileService;
        private final IClcGuestInhFilterConfigService clcGuestInhFilterConfigService;
        private final AmazonS3Service amazonS3Service;

        @Value("${aws-s3.third-party.key.clc.opera-arrival}")
        private String operaArrivalS3key;
        @Value("${file-max-size.import-report.clc}")
        private Long importReportFileMaxSize;

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

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param date       日期
         * @param in         文件流
         * @param timeZone   时区
         * @return 入住信息
         * @author yyt
         * @date 2026/1/29
         */
        @Override
        public List<ArrivalBO> parsReport(Integer propertyId, Long date, InputStream in, String timeZone) {
            List<ArrivalBO> result = new ArrayList<>();
            // company 动态配置规则
            List<String> companyNameConfigs = clcArrivalDetailedFilterConfigService.listForCompanyName(propertyId);

            // rate code 配置
            List<String> rateCodes = clcGuestInhFilterConfigService.listForRateCode(propertyId);
            if (CollectionUtils.isEmpty(rateCodes)) return Collections.emptyList();

            ZoneId zoneId = ZoneId.of(timeZone);

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                // 获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord csvRecord : iterable) {
                    // 跳过第一行标题
                    if (csvRecord.getRecordNumber() == 1) {
                        continue;
                    }

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

                    String ratePlan = CsvFileUtils.get(csvRecord, "H");
                    if (StringUtils.isEmpty(ratePlan) || !rateCodes.contains(ratePlan)) {
                        continue;
                    }

                    // 客人姓名
                    String guestName = CsvFileUtils.get(csvRecord, "A");
                    if (!clcHandleFileService.isGuestName(guestName)) {
                        continue;
                    }

                    String company = CsvFileUtils.get(csvRecord, "K");
                    if (clcHandleFileService.checkClcCompany(company, companyNameConfigs)) {
                        String roomNumber = CsvFileUtils.get(csvRecord, "X");

                        // 入住日期
                        String arrivalDateStr = CsvFileUtils.get(csvRecord, "E");
                        if (StringUtils.isBlank(arrivalDateStr)) {
                            continue;
                        }
                        // 截取日期
                        LocalDate arrivDateLocal = DateTimeUtils.strToLocalDate(arrivalDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA);
                        if ((DateTimeUtils.toTimestamp(arrivDateLocal.atStartOfDay(zoneId)) == date) && !roomNumber.isEmpty()) {
                            ArrivalBO arrivalBO = new ArrivalBO();
                            arrivalBO.setGuestName(guestName);
                            arrivalBO.setCompany(company);
                            arrivalBO.setRoomNumber(StringUtils.isEmpty(roomNumber) ? "" : roomNumber);
                            arrivalBO.setArrivDate(DateTimeUtils.localDateToStr(arrivDateLocal, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                            String confNumber = CsvFileUtils.get(csvRecord, "G");
                            arrivalBO.setConfNumber(StringUtils.isEmpty(confNumber) ? "" : confNumber);

                            String departureDateStr = CsvFileUtils.get(csvRecord, "F");
                            if (StringUtils.isBlank(departureDateStr)) {
                                continue;
                            }
                            arrivalBO.setDepartDate(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(departureDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA),
                                    BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                            //房间类型
                            String roomType = CsvFileUtils.get(csvRecord, "W");
                            arrivalBO.setRoomType(StringUtils.isEmpty(roomType) ? "" : roomType);

                            result.add(arrivalBO);
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(result)) {
                    // 将Arrivals数据按照 arrival date + room number 进行分组去重，当出现重复数据时只保留最新的记录
                    Map<String, ArrivalBO> arrivalByUniqKey = result.stream()
                            .collect(toMap(item -> item.getArrivDate()
                                    + "&" + item.getRoomNumber(), val -> val, (oldVal, newVal) -> newVal));
                    result = new ArrayList<>(arrivalByUniqKey.values());
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse pep [Arrivals Report Detailed] report error", e);
            }
            return result;

        }

        /**
         * 检查文件
         *
         * @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.checkArrivalsReportDetailedFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing pep [Arrivals Report Detailed] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.frontoffice.entity.clc.ClcMissingReport
         * @author yyt
         * @date 2026/1/29
         */
        @Override
        public ClcMissingReport handleImportLog(SymbolBO tenantBO, PropertyDTO propertyDTO, ClcMissingReport importLog,
                                                Long theDate, MultipartFile file, int userId) {
            String key = toS3(tenantBO.getSymbol(), propertyDTO.getAbbr(), file);
            if (Objects.isNull(importLog)) {
                importLog = clcMissingReportService.saveInProgressRecord(propertyDTO.getId(), theDate, key, userId);
            } else {
                // 更新异常为修复中
                ClcMissingReport updateContent = new ClcMissingReport();
                updateContent.setId(importLog.getId());
                updateContent.setStatus(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                updateContent.setUrl(key);
                clcMissingReportService.updateById(updateContent);
            }
            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 + "/" + operaArrivalS3key +
                    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 [Arrivals Report Detailed] 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, ClcMissingReport importLog, Integer userId) {
            clcHandleFileService.sendArrivalEvent(tenantBO, propertyDTO, file, SystemPlatformEnum.PEP.getDesc(), importLog, userId);
        }

    }