# ParseArrivalsDetailedServiceByOpera.java

    package cloud.wconnect.frontoffice.parsereport.badguest.impl;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.badguest.BgReportTypeEnum;
    import cloud.wconnect.frontoffice.parsereport.badguest.IParseFileService;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    import org.springframework.beans.factory.annotation.Autowired;
    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.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author lichen
     * @description 解析 Arrivals Detailed/service 报告,来源为OPERA
     * @date 2023/3/23 14:27
     */
    @Slf4j
    @Service
    public class ParseArrivalsDetailedServiceByOpera implements IParseFileService {

        @Value("${aws-s3.third-party.key.guests-blacklist.arrivals-detailed}")
        private String arrivalsDetailedS3FilePath;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Autowired
        private ObjectMapper objectMapper;

        /**
         * 支持的文件来源 、文件类型
         *
         * @param source 来源
         * @param type   类型
         * @return boolean
         * @author lichen
         * @date 2024/7/30
         */
        @Override
        public boolean supports(String source, int type) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source) && BgReportTypeEnum.ARRIVALS_DETAILED_SERVICE.getType() == type;
        }

        /**
         * 解析报告
         *
         * @param in          文件流
         * @param propertyDTO 资产对象
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO>
         * @author lichen
         * @date 2023/5/12
         */
        @Override
        public List<GuestInHouseDTO> parse(InputStream in, PropertyDTO propertyDTO) throws ParseReportException {
            try {
                //fileInputStream-> document
                Document document = new SAXReader().read(in);
                //解析报告数据
                List<GuestInHouseDTO> guestInHouseList = parseDocument(document, propertyDTO);
                //去重返回
                return guestInHouseList.stream()
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(() -> new TreeSet<>(
                                                Comparator.comparing(GuestInHouseDTO::getInHouseRecordStr))), ArrayList::new
                                )
                        );
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "source=opera, parse [Arrivals Detailed/service] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @return void
         * @author lichen
         * @date 2024/7/29
         */
        @Override
        public void checkFile(MultipartFile file) {
            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            try (InputStream in = file.getInputStream()) {
                //校验文件内容
                FileCheckUtils.checkArrivalDetailFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse [Arrivals Detailed/service] report error", e2);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param userId      操作人ID
         * @param type        文件类型
         * @return void
         * @author lichen
         * @date 2024/7/29
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, int userId, int type) {
            String tenantSymbol = propertyDTO.getTenantSymbol();
            String abbr = propertyDTO.getAbbr();

            try {
                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(3);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(abbr));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());

                //上传文件
                String key = tenantSymbol + "/" + abbr + "/" + arrivalsDetailedS3FilePath +
                        UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                //发布事件
                snsSender.publish(EventSubjectEnum.ARRIVALS_DETAILED_SERVICE.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (BadRequestException badRequestException) {
                throw badRequestException;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Import opera [Arrivals Detailed/service] report exception", e);
            }
        }

        /**
         * 解析xml文档
         *
         * @param document    文档对象
         * @param propertyDTO 资产
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.GuestInHouseDTO>
         * @author lichen
         * @date 2023/12/28
         */
        private List<GuestInHouseDTO> parseDocument(Document document, PropertyDTO propertyDTO) {
            List<Node> nodes = document.selectNodes("//G_RESERVATION");
            if (nodes.isEmpty()) {
                return Collections.emptyList();
            }
            //获取当前资产对应的ZoneId
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);
            ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());
            //构建返回集合
            List<GuestInHouseDTO> guestInHouseList = Lists.newArrayListWithExpectedSize(nodes.size());
            //循环处理nodes
            for (Node node : nodes) {
                Element element = (Element) node;
                String fullNameStr = element.elementText("FULL_NAME");
                if (StringUtils.isEmpty(fullNameStr)) {
                    continue;
                }

                GuestInHouseDTO guestInHouse = new GuestInHouseDTO();
                guestInHouse.setPropertyId(propertyDTO.getId());
                //设置First Name Last Name
                String[] fullNames = fullNameStr.split(",");
                if (fullNames.length == 2) {
                    guestInHouse.setFirstName(fullNames[1]);
                    guestInHouse.setLastName(fullNames[0]);
                } else {
                    guestInHouse.setLastName(fullNames[0]);
                    guestInHouse.setFirstName("");
                }
                //设置checkInDate
                String inDate = element.elementText("ARRIVAL");
                if (StringUtils.isEmpty(inDate)) {
                    guestInHouse.setCheckInDate(BaseConstant.LONG_ZERO);
                } else {
                    guestInHouse.setCheckInDate(LocalDate.parse(inDate, dateTimeFormatter)
                            .atStartOfDay(zoneId).toEpochSecond());
                }
                //设置checkOutDate
                String outDate = element.elementText("DEPARTURE");
                if (StringUtils.isEmpty(outDate)) {
                    guestInHouse.setCheckOutDate(BaseConstant.LONG_ZERO);
                } else {
                    guestInHouse.setCheckOutDate(LocalDate.parse(outDate, dateTimeFormatter)
                            .atStartOfDay(zoneId).toEpochSecond());
                }

                guestInHouse.setCreatedTime(DateTimeUtils.nowTimestamp());
                guestInHouse.setCreatedBy(BaseConstant.ZERO);
                guestInHouseList.add(guestInHouse);
            }
            return guestInHouseList;
        }

    }