# OutOfOrderFileParseByShiji.java

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

    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.FileCheckUtils;
    import cloud.wconnect.commonlib.util.ShijiFileCheckUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.frontoffice.cons.S3BucketFunctionCons;
    import cloud.wconnect.frontoffice.entity.oooroom.OooImportLog;
    import cloud.wconnect.frontoffice.entity.oooroom.OooRoomTypeConfig;
    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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Nullable;
    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.format.DateTimeFormatter;
    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
    public class OutOfOrderFileParseByShiji implements IOutOfOrderFileParse {

        private static final String SOURCE = SystemPlatformEnum.SHI_JI.getDesc();
        //数据状态字段
        public static final String PENDING = "Pending";
        public static final String RELEASED = "Released";
        public static final String CANCELLED = "Cancelled";

        @Resource
        private IOooRoomTypeConfigService oooRoomTypeConfigService;
        @Resource
        private IOooImportLogService oooImportLogService;
        @Resource
        private IOooRoomHandleFileService oooRoomHandleFileService;
        @Resource
        private 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 lichen
         * @date 2025/7/28
         */
        @Override
        public boolean supports(String source) {
            return SOURCE.equals(source);
        }

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param in         文件流
         * @param timeZone   时区
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.bo.oooroom.OutOfOrderBO>
         * @author lichen
         * @date 2025/7/29
         */
        @Override
        public List<OutOfOrderBO> parsReport(Integer propertyId, InputStream in, String timeZone) throws Exception {
            List<OutOfOrderBO> result = new ArrayList<>();
            // 查询类型配置
            List<String> roomTypeSymbols = oooRoomTypeConfigService.list(new QueryWrapper<OooRoomTypeConfig>().lambda()
                            .eq(OooRoomTypeConfig::getPropertyId, propertyId))
                    .stream().map(item -> item.getRoomTypeSymbol().toLowerCase()).toList();
            if (CollectionUtils.isEmpty(roomTypeSymbols)) {
                return Collections.emptyList();
            }

            //有效的数据状态集合
            ArrayList<String> validStateList = Lists.newArrayList(PENDING, RELEASED, CANCELLED);

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yy");
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            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;
                    }

                    //房间状态
                    String status = ShijiFileCheckUtils.get(csvRecord, "C");
                    if (StringUtils.isEmpty(status)) {
                        continue;
                    }
                    if (!roomTypeSymbols.contains(status.toLowerCase())) {
                        continue;
                    }

                    //日期格式mm/dd/yy
                    String startDateStr = ShijiFileCheckUtils.get(csvRecord, "D");
                    String endDateStr = ShijiFileCheckUtils.get(csvRecord, "E");
                    if (StringUtils.isEmpty(startDateStr) || StringUtils.isEmpty(endDateStr)) {
                        continue;
                    }

                    //状态
                    String state = ShijiFileCheckUtils.get(csvRecord, "H");
                    if (StringUtils.isBlank(state) || !validStateList.contains(state)) {
                        continue;
                    }
                    //state=Released时，L列才表示完成日期
                    //state=Canceled时，E列表示完成日期
                    String dateEntered = "";
                    if (state.equals(RELEASED)) {
                        //完成日期 日期格式mm/dd/yy
                        dateEntered = ShijiFileCheckUtils.get(csvRecord, "L");
                    } else if (state.equals(CANCELLED)) {
                        dateEntered = endDateStr;
                    }

                    //房间号
                    String roomNumber = ShijiFileCheckUtils.get(csvRecord, "A");
                    if(StringUtils.isBlank(roomNumber)){
                        continue;
                    }
                    String comment = ShijiFileCheckUtils.get(csvRecord, "I");

                    OutOfOrderBO outOfOrder = new OutOfOrderBO();
                    outOfOrder.setRoomNumber(roomNumber);
                    outOfOrder.setRoomTypeSymbol(status);
                    outOfOrder.setFromDate(dateTimeFormatter2.format(LocalDate.parse(startDateStr.trim(), dateTimeFormatter)));
                    outOfOrder.setToDate(dateTimeFormatter2.format(LocalDate.parse(endDateStr.trim(), dateTimeFormatter)));
                    outOfOrder.setCompletedDate(dateEntered.isBlank() ? StringUtils.EMPTY :
                            dateTimeFormatter2.format(LocalDate.parse(dateEntered.trim(), dateTimeFormatter)));
                    outOfOrder.setRemarks(StringUtils.isEmpty(comment) ? "" : comment);
                    result.add(outOfOrder);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse shiji [Out of Order / Out of Service] 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.checkOutOfOrderFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing shiji [Out of Order / Out of Service] failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.frontoffice.entity.oooroom.OooImportLog
         * @author lichen
         * @date 2025/7/29
         */
        @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 lichen
         * @date 2025/7/29
         */
        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 shiji [Out of Order / Out of Service] file to s3 failure", e);
            }
            return key;
        }

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

    }