# OutOfOrderFileParseByPep.java

    package cloud.wconnect.frontoffice.service.oooroom.outoforder;

    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.oooroom.OooImportLog;
    import cloud.wconnect.frontoffice.pojo.bo.oooroom.OutOfOrderBO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.oooroom.IOooImportLogService;
    import cloud.wconnect.frontoffice.service.oooroom.IOooRoomHandleFileService;
    import cloud.wconnect.frontoffice.service.oooroom.IOooRoomTypeConfigService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Nullable;
    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.apache.logging.log4j.util.Strings;
    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.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Objects;

    /**
     * 解析 out of order 报告
     *
     * @author yyt
     * 2023/8/7
     */
    @Service
    @DS("ratelog_manage")
    @Slf4j
    @RequiredArgsConstructor
    public class OutOfOrderFileParseByPep implements IOutOfOrderFileParse {

        private final IOooRoomTypeConfigService oooRoomTypeConfigService;
        private final IOooImportLogService oooImportLogService;
        private final IOooRoomHandleFileService oooRoomHandleFileService;
        private final AmazonS3Service amazonS3Service;

        @Value("${file-max-size.import-report.ooo-room}")
        private Long importReportFileMaxSize;
        @Value("${aws-s3.third-party.key.ooo-room.out-of-order}")
        private String operaOutOfOrderS3key;

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

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param in         文件流
         * @param timeZone   时区
         * @return ooo room
         * @author yyt
         * @date 2026/1/19
         */
        @Override
        public List<OutOfOrderBO> parsReport(Integer propertyId, InputStream in, String timeZone) throws Exception {
            List<OutOfOrderBO> result = new ArrayList<>();
            // 查询类型配置
            List<String> roomTypeSymbols = oooRoomTypeConfigService.listForRoomTypeSymbols(propertyId);
            if (CollectionUtils.isEmpty(roomTypeSymbols)) {
                return Collections.emptyList();
            }

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

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

                    String roomNumber = CsvFileUtils.get(csvRecord, "A");
                    if(StringUtils.isBlank(roomNumber)){
                        continue;
                    }
                    // 只解析 Maintenance Activity 部分的数据（若第一列内容是标题，则结束循环）
                    if (roomNumber.equals("Room Number")) {
                        break;
                    }

                    // 房型
                    String roomType = CsvFileUtils.get(csvRecord, "B");
                    if (StringUtils.isEmpty(roomType)) {
                        continue;
                    }
                    if (!roomTypeSymbols.contains(roomType.toLowerCase())) {
                        continue;
                    }

                    String startDateStr = CsvFileUtils.get(csvRecord, "D");
                    String endDateStr = CsvFileUtils.get(csvRecord, "E");
                    if (StringUtils.isEmpty(startDateStr) || StringUtils.isEmpty(endDateStr)) {
                        continue;
                    }

                    String comment = CsvFileUtils.get(csvRecord, "M");

                    OutOfOrderBO outOfOrder = new OutOfOrderBO();
                    outOfOrder.setRoomNumber(roomNumber);
                    outOfOrder.setRoomTypeSymbol(roomType);
                    outOfOrder.setFromDate(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(startDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    String endDate = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(endDateStr, BaseConstant.DATE_FORMAT_MMMDDYYYY_USA),
                            BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    outOfOrder.setToDate(endDate);

                    // 当 Status=CLOSED，End Date 表示实际完成日期
                    String status = CsvFileUtils.get(csvRecord, "H");
                    outOfOrder.setCompletedDate(StringUtils.isNotEmpty(status) && status.equals("CLOSED") ? endDate : Strings.EMPTY);

                    outOfOrder.setRemarks(StringUtils.isEmpty(comment) ? Strings.EMPTY : comment);
                    result.add(outOfOrder);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse pep [Maintenance Activity] report error", e);
            }
            return result;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @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()) {
                PepFileCheckUtils.checkMaintenanceActivityFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing pep [Maintenance Activity] failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.frontoffice.entity.oooroom.OooImportLog
         * @author yyt
         * @date 2026/1/19
         */
        @Override
        public OooImportLog handleImportLog(SymbolBO tenantBO, PropertyDTO propertyDTO, @Nullable OooImportLog importLog,
                                            Long theDate, MultipartFile file, int userId) {
            String key = toS3(tenantBO.getSymbol(), propertyDTO.getAbbr(), file);
            if (Objects.isNull(importLog)) {
                importLog = oooImportLogService.saveRecord(propertyDTO.getId(), theDate, ReportImportResultCons.IMPORT_IN_PROGRESS, key, userId);
            } else {
                // 更新异常为修复中
                OooImportLog updateContent = new OooImportLog();
                updateContent.setId(importLog.getId());
                updateContent.setStatus(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                updateContent.setUrl(key);
                oooImportLogService.updateById(updateContent);
            }
            return importLog;
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return java.lang.String
         * @author yyt
         * @date 2026/1/19
         */
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + operaOutOfOrderS3key +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());
            try {
                // 上传文件
                amazonS3Service.uploadFile(S3BucketFunctionCons.OOO_ROOM_IMPORT_RECORD, file, key);
            } catch (Exception e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Uploading pep [Maintenance Activity] file to s3 failure", e);
            }
            return key;
        }

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

    }