# OutOfOrderFileParseByOpera.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.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 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.Nullable;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    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.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 OutOfOrderFileParseByOpera implements IOutOfOrderFileParse {

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

        @Resource
        private IOooRoomTypeConfigService oooRoomTypeConfigService;
        @Resource
        private IOooImportLogService oooImportLogService;
        @Resource
        private IOooRoomHandleFileService oooRoomHandleFileService;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        private ObjectMapper objectMapper;

        @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;

        private final Sender snsSender;

        public OutOfOrderFileParseByOpera(@Qualifier("3pSender") Sender snsSender) {
            this.snsSender = snsSender;
        }

        /**
         * 判断支持的平台
         *
         * @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 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();
            }

            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yy");
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Document document = new SAXReader().read(in);
            List<Node> nodes = document.selectNodes("//G_ROOM");
            for (Node node : nodes) {
                Element dataElement = (Element) node;

                OutOfOrderBO outOfOrder = new OutOfOrderBO();
                outOfOrder.setRoomNumber(dataElement.elementTextTrim("ROOM"));

                // 忽略房型标识跟配置规则不匹配的
                String roomTypeSymbol = dataElement.elementTextTrim("ROOM_STATUS");
                if (StringUtils.isEmpty(roomTypeSymbol)) {
                    continue;
                }
                if (!roomTypeSymbols.contains(roomTypeSymbol.toLowerCase())) {
                    continue;
                }

                outOfOrder.setRoomTypeSymbol(roomTypeSymbol);
                String remarks = dataElement.elementTextTrim("REPAIR_REMARKS");
                if (remarks.contains("&;&")) {
                    remarks = StringUtils.replace(remarks, "&;&", "\n");
                }
                outOfOrder.setRemarks(remarks);
                String fromDateStr = dataElement.elementTextTrim("BEGIN_DATE");
                String toDateStr = dataElement.elementTextTrim("END_DATE");
                String completedDateStr = dataElement.elementTextTrim("COMPLETED_ON");
                if (StringUtils.isEmpty(fromDateStr) || StringUtils.isEmpty(toDateStr)) {
                    continue;
                }

                outOfOrder.setFromDate(dateTimeFormatter2.format(LocalDate.parse(fromDateStr, dateTimeFormatter)));
                outOfOrder.setToDate(dateTimeFormatter2.format(LocalDate.parse(toDateStr, dateTimeFormatter)));
                outOfOrder.setCompletedDate(completedDateStr.isEmpty() ? StringUtils.EMPTY :
                        dateTimeFormatter2.format(LocalDate.parse(completedDateStr, dateTimeFormatter)));
                result.add(outOfOrder);
            }
            return result;
        }

        /**
         * 检查文件
         *
         * @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("xml"));

            try (InputStream in = file.getInputStream()) {
                FileCheckUtils.checkOutOfOrderFile(in);
            } 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 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);
            }
            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 tenantBO    租户
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/1
         **/
        @Override
        public void handleFile(SymbolBO tenantBO, PropertyDTO propertyDTO, MultipartFile file, OooImportLog importLog, Integer userId) {
            oooRoomHandleFileService.sendOutOfOrderEvent(tenantBO, propertyDTO, file, SystemPlatformEnum.OPERA.getDesc(), importLog, userId);
        }

    }