# GuestInHouseParseByShiji.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.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.ShijiFileCheckUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    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.IClcHandleFileService;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    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.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    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
     * 2023/7/31
     */
    @Service
    @DS("logbook")
    @Slf4j
    public class GuestInHouseParseByShiji implements IGuestInHouseParse {

        @Resource
        private IClcGuestInhImportLogService clcGuestInhImportLogService;
        @Resource
        private IClcHandleFileService clcHandleFileService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private ObjectMapper objectMapper;
        @Value("${aws-s3.third-party.key.clc.guest-in-house}")
        private String guestInHouseS3key;
        @Value("${file-max-size.import-report.clc}")
        private Long importReportFileMaxSize;
        @Qualifier("3pSender")
        @Autowired
        private Sender snsSender;
        @Autowired
        private IClcGuestInhFilterConfigService clcGuestInhFilterConfigService;

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author lichen
         * @date 2025/7/28
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param inputStream 文件流
         * @param propertyDTO 资产DTO
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.bo.clc.GuestInHouseBO>
         * @author lichen
         * @date 2025/7/28
         */
        @Override
        public List<GuestInHouseBO> parsReport(InputStream inputStream, PropertyDTO propertyDTO) {
            // 未配置过滤配置，则不处理后续逻辑
            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");
            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;
                    }
                    //房间号
                    String room = ShijiFileCheckUtils.get(csvRecord, "A");
                    if(StringUtils.isBlank(room)){
                        continue;
                    }
                    //房间号不足4位的补0
                    String roomNumber = decimalFormat.format(Integer.parseInt(room));

                    //到店日期
                    String arrivalDateStr = ShijiFileCheckUtils.get(csvRecord, "C");
                    if (StringUtils.isBlank(arrivalDateStr)) {
                        continue;
                    }
                    //截取日期
                    arrivalDateStr = arrivalDateStr.trim().substring(0, 8);
                    //格式化入住日期
                    String checkInDate = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(arrivalDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD);

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

                    //离店日期
                    String departureDateStr = ShijiFileCheckUtils.get(csvRecord, "D");
                    if (StringUtils.isBlank(departureDateStr)) {
                        continue;
                    }
                    departureDateStr = departureDateStr.trim().substring(0, 8);
                    //格式化离店日期
                    String checkOutDate = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(departureDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    //客户名称
                    String guestName = ShijiFileCheckUtils.get(csvRecord, "B");

                    GuestInHouseBO guestInHouse = new GuestInHouseBO();
                    guestInHouse.setRateCode(rateCode);
                    guestInHouse.setCheckInDate(checkInDate);
                    guestInHouse.setCheckOutDate(checkOutDate);
                    guestInHouse.setCompanyName("");
                    //设置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 shiji [In-House Guest Report] report error", e);
            }
        }

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

            try (InputStream in = file.getInputStream()) {
                ShijiFileCheckUtils.checkInHouseGuestReportFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing shiji [In-House Guest Report] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.frontoffice.entity.clc.ClcGuestInhImportLog
         * @author lichen
         * @date 2025/7/28
         */
        @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 lichen
         * @date 2025/7/28
         */
        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 shiji [In-House Guest Report] file to s3 failure", e);
            }
            return key;
        }

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

    }