# ArrivalFileParseByOpera.java

    package cloud.wconnect.frontoffice.service.clc.arrival;

    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.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    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 cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    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.text.DecimalFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.regex.Pattern;

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

    /**
     * 解析 arrival 报告
     *
     * @author yyt
     * 2023/7/26
     */
    @Service
    @DS("logbook")
    public class ArrivalFileParseByOpera 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 final Sender snsSender;

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

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

        private static final Pattern WORD_PATTERN = Pattern.compile("[A-Za-z]+");

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

        /**
         * 解析报告数据
         *
         * @param propertyId 资产 id
         * @param date       日期
         * @param in         文件流
         * @param timeZone   时区
         * @return 入住信息
         * @author yyt
         * @date 2023/7/26
         */
        @Override
        public List<ArrivalBO> parsReport(Integer propertyId, Long date, InputStream in, String timeZone) {
            List<ArrivalBO> result = new ArrayList<>();
            try {
                // company 动态配置规则
                List<String> companyNameConfigs = clcArrivalDetailedFilterConfigService.listForCompanyName(propertyId);

                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yy");
                DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                DecimalFormat decimalFormat = new DecimalFormat("0000");
                ZoneId zoneId = ZoneId.of(timeZone);

                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_GROUP_BY1");
                for (Node node : nodes) {
                    Element dataElement = (Element) node;
                    String company = dataElement.elementTextTrim("GROUPBY1_COL");
                    if (clcHandleFileService.checkClcCompany(company, companyNameConfigs)) {
                        List<Node> clcNodes = node.selectNodes("./LIST_G_RESERVATION/G_RESERVATION");
                        if (!clcNodes.isEmpty()) {
                            for (Node dataNode : clcNodes) {
                                Element dataNodeElement = (Element) dataNode;

                                // Arrival Date
                                String arrivDateStr = dataNodeElement.element("ARRIVAL").getTextTrim();
                                LocalDate arrivDateLocal = LocalDate.parse(arrivDateStr, dateTimeFormatter);
                                long arrivDate = DateTimeUtils.toTimestamp(arrivDateLocal.atStartOfDay(zoneId));
                                // Room Number
                                String roomNumber = dataNodeElement.element("ROOM_NO").getTextTrim();
                                if ((arrivDate == date) && !roomNumber.isEmpty()) {
                                    ArrivalBO arrivalBO = new ArrivalBO();
                                    arrivalBO.setCompany(company);
                                    arrivalBO.setArrivDate(dateTimeFormatter2.format(arrivDateLocal));
                                    // 房间号不足4位数字时前面补0
                                    roomNumber = decimalFormat.format(Integer.valueOf(roomNumber));
                                    arrivalBO.setRoomNumber(roomNumber);

                                    // Departure Date
                                    String departDateStr = dataNodeElement.element("DEPARTURE").getTextTrim();
                                    arrivalBO.setDepartDate(dateTimeFormatter2.format(LocalDate.parse(departDateStr, dateTimeFormatter)));

                                    // Conf No.
                                    String confNumber = dataNodeElement.element("CONFIRMATION_NO").getTextTrim();
                                    arrivalBO.setConfNumber(confNumber);

                                    // Guest Name
                                    String guestName = dataNodeElement.element("FULL_NAME").getTextTrim();
                                    arrivalBO.setGuestName(guestName);

                                    // Room Type
                                    String roomType = dataNodeElement.element("ROOM_CATEGORY_LABEL").getTextTrim();
                                    arrivalBO.setRoomType(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 (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse arrival report error", e);
            }
            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.checkArrivalDetailFile(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 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 文件路径
         * @author yyt
         * @date 2024/8/2
         **/
        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 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, ClcMissingReport importLog, Integer userId) {
            clcHandleFileService.sendArrivalEvent(tenantBO, propertyDTO, file, SystemPlatformEnum.OPERA.getDesc(), importLog, userId);
        }

    }