# OutOfOrderFileParseByOther.java

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

    import cloud.wconnect.commonlib.cons.*;
    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.entity.oooroom.OooRoomTypeConfig;
    import cloud.wconnect.frontoffice.pojo.bo.clc.DataBO;
    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.IOooRoomService;
    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 org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.IOException;
    import java.io.InputStream;
    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")
    public class OutOfOrderFileParseByOther implements IOutOfOrderFileParse {

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

        @Resource
        private IOooRoomTypeConfigService oooRoomTypeConfigService;
        @Resource
        private IOooRoomService oooRoomService;
        @Resource
        private IOooImportLogService oooImportLogService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        @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 2023/8/7
         */
        @Override
        public boolean supports(String source) {
            return SOURCE.equals(source);
        }

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param in         文件流
         * @param timeZone   时区
         * @return 故障房信息
         * @author yyt
         * @date 2023/7/26
         */
        @Override
        public List<OutOfOrderBO> parsReport(Integer propertyId, InputStream in, String timeZone) throws IOException {
            // 查询类型配置
            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();
            }
            List<OutOfOrderBO> result = new ArrayList<>();
            try(Workbook workbook = WorkbookFactory.create(in)){
                Sheet sheet = workbook.getSheetAt(0);
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    // 忽略房型标识跟配置规则不匹配的
                    Cell typeCell = row.getCell(1);
                    String roomTypeSymbol = CellUtils.convertCellStr(typeCell);
                    if (!roomTypeSymbols.contains(roomTypeSymbol.toLowerCase())) {
                        continue;
                    }

                    OutOfOrderBO outOfOrder = new OutOfOrderBO();
                    Cell roomNumberCell = row.getCell(0);
                    outOfOrder.setRoomNumber(CellUtils.convertCellStr(roomNumberCell));
                    outOfOrder.setRoomTypeSymbol(roomTypeSymbol);

                    outOfOrder.setFromDate(CellUtils.convertCellStr(row.getCell(2), BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    outOfOrder.setToDate(CellUtils.convertCellStr(row.getCell(3), BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                    Cell completionDate = row.getCell(4);
                    if (Objects.nonNull(completionDate) && StringUtils.isNotBlank(completionDate.toString())) {
                        outOfOrder.setCompletedDate(CellUtils.convertCellStr(completionDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                    }

                    Cell remarkCell = row.getCell(5);
                    outOfOrder.setRemarks(CellUtils.convertCellStr(remarkCell));

                    result.add(outOfOrder);
                }

                return result;
            }catch (Exception e){
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsReport file error", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/2
         **/
        @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);
                importLog.setStatus(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
            }
            return importLog;
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/8/2
         **/
        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 to s3 failure", e);
            }
            return key;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/8/1
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xls", "xlsx"));

            try (InputStream in = file.getInputStream();
                 Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row titleRow = sheet.getRow(0);
                if (Objects.isNull(titleRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                String roomNumberTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String typeTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String startDateTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String endDateTitle = CellUtils.convertCellStr(titleRow.getCell(3));
                String completionDateTitle = CellUtils.convertCellStr(titleRow.getCell(4));
                String remarkTitle = CellUtils.convertCellStr(titleRow.getCell(5));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell roomNumberCell = row.getCell(0);
                    if (Objects.isNull(roomNumberCell) || StringUtils.isBlank(roomNumberCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The room number cannot be empty");
                    } else {
                        // 最多 2000 个字
                        if (CellUtils.convertCellStr(roomNumberCell).length() > 2000) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle, 2000),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The room number cannot be more than 2000 characters");
                        }
                    }

                    Cell typeCell = row.getCell(1);
                    // 类型不能为空
                    if (Objects.isNull(typeCell) || StringUtils.isBlank(typeCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(typeTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The type cannot be empty");
                    } else {
                        // 最多 255 个字
                        if (CellUtils.convertCellStr(typeCell).length() > 255) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(typeTitle, 255),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The type cannot be more than 255 characters");
                        }
                    }

                    Cell startDateCell = row.getCell(2);
                    if (Objects.isNull(startDateCell) || StringUtils.isBlank(startDateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(startDateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The start date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(startDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(startDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The start date format error");
                        }
                    }

                    Cell endDateCell = row.getCell(3);
                    if (Objects.isNull(endDateCell) || StringUtils.isBlank(endDateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(endDateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The end date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(endDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(endDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The end date format error");
                        }
                    }

                    // 开始日期不能晚于结束日期
                    LocalDate startDate = LocalDate.parse(CellUtils.convertCellStr(startDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    LocalDate endDate = LocalDate.parse(CellUtils.convertCellStr(endDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                    if (startDate.isAfter(endDate)) {
                        throw new BadRequestException(CommonErrorI18nConstant.START_DATE_CANNOT_GREATER_THAN_END_DATE,
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The start date cannot be later than the end date");
                    }

                    Cell completionDateCell = row.getCell(4);
                    if (Objects.nonNull(completionDateCell) && StringUtils.isNotBlank(completionDateCell.toString())) {
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(completionDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(completionDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The completion date format error");
                        }
                    }

                    Cell remarkCell = row.getCell(5);
                    if (Objects.nonNull(remarkCell) && StringUtils.isNotBlank(remarkCell.toString())) {
                        // 最多 1000 个字
                        if (CellUtils.convertCellStr(remarkCell).length() > 1000) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(remarkTitle, 1000),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The remark cannot be more than 1000 characters");
                        }
                    }
                }
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 处理文件
         *
         * @param tenantBO    租户
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/1
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, OooImportLog importLog, Integer userId) {
            String timezone = propertyDTO.getTimezone();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<OutOfOrderBO> outOfOrders = parsReport(propertyDTO.getId(), inputStream, timezone);
                DataBO<OutOfOrderBO> dataBO = new DataBO<>();
                dataBO.setDate(dateTimeFormatter.format(DateTimeUtils.toZonedDateTime(importLog.getTheDate(),
                        timezone)));
                dataBO.setData(outOfOrders);
                oooRoomService.handleOooRoomData(propertyDTO, userId, dataBO);
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse out of order report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog, userId);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @param userId    操作人
         * @author yyt
         * @date 2024/8/2
         **/
        private void importSuccess(OooImportLog importLog, int userId) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                OooImportLog updateLog = new OooImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                if (importLog.getStatus() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                    updateLog.setResolvedBy(userId).setResolvedTime(DateTimeUtils.nowTimestamp());
                }
                oooImportLogService.updateById(updateLog);
            });
        }

        /**
         * 导入失败
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/8/2
         **/
        private void importFail(OooImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                OooImportLog updateLog = new OooImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_FAIL);
                oooImportLogService.updateById(updateLog);
            });
        }

    }