# ArrivalFileParseByShiji.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.cons.shiji.ArrivalsDetailedTitleCons;
    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.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.IClcHandleFileService;
    import cloud.wconnect.frontoffice.service.clc.IClcMissingReportService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    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.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.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;

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

    /**
     * 解析 arrival 报告
     *
     * @author yyt
     * 2023/7/26
     */
    @Service
    @DS("logbook")
    @Slf4j
    public class ArrivalFileParseByShiji implements IArrivalFileParse {

        @Resource
        private IClcArrivalDetailedFilterConfigService clcArrivalDetailedFilterConfigService;
        @Resource
        private IClcMissingReportService clcMissingReportService;
        @Resource
        private IClcHandleFileService clcHandleFileService;
        @Resource
        private AmazonS3Service amazonS3Service;

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

        private static final String SOURCE = SystemPlatformEnum.SHI_JI.getDesc();

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

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param date       日期
         * @param in         文件流
         * @param timeZone   时区
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.bo.clc.ArrivalBO>
         * @author lichen
         * @date 2025/7/28
         */
        @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);

            ZoneId zoneId = ZoneId.of(timeZone);

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                //标题列
                CSVRecord titleRecord = iterable.iterator().next();
                //获取标题对应的索引
                Map<String, Integer> title2Index = ShijiFileCheckUtils.getTitleIndex(titleRecord, ArrivalsDetailedTitleCons.TITLE_LIST);
                //获取所有的数据列
                ArrayList<CSVRecord> allRows = Lists.newArrayList();
                iterable.forEach(allRows::add);

                Integer indexByGuestName = title2Index.get(ArrivalsDetailedTitleCons.NAME);
                Integer indexByConfNumber = title2Index.get(ArrivalsDetailedTitleCons.NAME);

                Integer indexByArrivalDate = title2Index.get(ArrivalsDetailedTitleCons.ARRIVAL);
                Integer indexByDepartureDate = title2Index.get(ArrivalsDetailedTitleCons.ARRIVAL);

                Integer indexByRoomNumber = title2Index.get(ArrivalsDetailedTitleCons.ROOM_NUMBER);
                Integer indexByRoomType = title2Index.get(ArrivalsDetailedTitleCons.ROOM_TYPE);
                Integer indexByCompany = title2Index.get(ArrivalsDetailedTitleCons.COMPANY);

                for (int i = 0; i < allRows.size(); i++) {
                    CSVRecord csvRecord = allRows.get(i);

                    //客人姓名
                    String guestName = ShijiFileCheckUtils.getByIndex(csvRecord, indexByGuestName).trim();
                    if (!clcHandleFileService.isGuestName(guestName)) {
                        continue;
                    }

                    String company = "";
                    if(Objects.nonNull(indexByCompany)){
                        company = ShijiFileCheckUtils.getByIndex(csvRecord, indexByCompany);
                    }else{
                        continue;
                    }

                    if (clcHandleFileService.checkClcCompany(company, companyNameConfigs)) {

                        String roomNumber = ShijiFileCheckUtils.getByIndex(csvRecord, indexByRoomNumber);

                        //入住日期
                        String arrivalDateStr = ShijiFileCheckUtils.getByIndex(csvRecord, indexByArrivalDate);
                        if(StringUtils.isBlank(arrivalDateStr)){
                            continue;
                        }
                        //截取日期
                        arrivalDateStr = arrivalDateStr.trim().substring(0,8);
                        LocalDate arrivDateLocal = DateTimeUtils.strToLocalDate(arrivalDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY);
                        long arrivDateByLong = DateTimeUtils.toTimestamp(arrivDateLocal.atStartOfDay(zoneId));

                        if ((arrivDateByLong == 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));

                            //从后2行获取Conf #
                            CSVRecord nextCsvRecord = allRows.get(i + 2);
                            String confNumber = ShijiFileCheckUtils.getByIndex(nextCsvRecord, indexByConfNumber);
                            arrivalBO.setConfNumber(StringUtils.isEmpty(confNumber) ? "" : confNumber.trim());

                            //从后2行获取离店日期
                            String departureDateStr = ShijiFileCheckUtils.getByIndex(nextCsvRecord, indexByDepartureDate);
                            if(StringUtils.isBlank(departureDateStr)){
                                continue;
                            }
                            //截取日期
                            departureDateStr = departureDateStr.trim().substring(0,8);
                            arrivalBO.setDepartDate(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(departureDateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY),
                                    BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                            //房间类型
                            String roomType = ShijiFileCheckUtils.getByIndex(csvRecord, indexByRoomType);
                            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 shiji [Arrivals Report Detailed] report error", e);
            }
            return result;

        }

        /**
         * 检查文件
         *
         * @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.checkArrivalsReportDetailedFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing shiji [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 lichen
         * @date 2025/7/28
         */
        @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 lichen
         * @date 2025/7/28
         */
        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 shiji [Arrivals Report Detailed] file to s3 failure", e);
            }
            return key;
        }

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

    }