# ParseGuestsInHouseComplimentaryByOpera.java

    package cloud.wconnect.frontoffice.parsereport.comproom.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.parsereport.comproom.IParseGuestsInHouseComplimentary;
    import cloud.wconnect.frontoffice.pojo.bo.comproom.GuestsInHouseComplimentaryBO;
    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.collections.CollectionUtils;
    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.util.Collections;
    import java.util.List;
    import java.util.Map;

    /**
     * 解析Guests In-House Complimentary报告
     *
     * @author lichen
     * @date 2023/8/7
     */
    @Slf4j
    @Service
    public class ParseGuestsInHouseComplimentaryByOpera implements IParseGuestsInHouseComplimentary {

        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Value("${aws-s3.third-party.key.comp-room.guests-in-house-complimentary}")
        private String s3FilePath;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private ObjectMapper objectMapper;

        /**
         * 支持的报告源
         *
         * @param source 报告来源
         * @return boolean
         * @author lichen
         * @date 2023/8/7
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in 文件流
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.bo.comproom.GuestsInHouseComplimentaryBO>
         * @author lichen
         * @date 2023/8/7
         */
        @Override
        public List<GuestsInHouseComplimentaryBO> parse(InputStream in) throws ParseReportException {
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_ROOM");
                if (CollectionUtils.isEmpty(nodes)) {
                    return Collections.emptyList();
                }

                List<GuestsInHouseComplimentaryBO> result = Lists.newArrayListWithExpectedSize(nodes.size());

                for (Node node : nodes) {
                    GuestsInHouseComplimentaryBO guestsInHouseComplimentaryBO = new GuestsInHouseComplimentaryBO();

                    Element dataElement = (Element) node;
                    guestsInHouseComplimentaryBO.setRoomNumber(dataElement.elementTextTrim("ROOM"));
                    guestsInHouseComplimentaryBO.setRoomType(dataElement.elementTextTrim("ROOM_CATEGORY_LABEL"));
                    guestsInHouseComplimentaryBO.setGuestName(dataElement.elementTextTrim("FULL_NAME"));
                    guestsInHouseComplimentaryBO.setGuestNameId(dataElement.elementTextTrim("GUEST_NAME_ID"));
                    //入住日期
                    String arrivalDateStr = dataElement.elementTextTrim("ARRIVAL");
                    if (StringUtils.isNotBlank(arrivalDateStr)) {
                        LocalDate arrivalDateLocalDate = DateTimeUtils.strToLocalDate(arrivalDateStr, BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);
                        String arrivalDate = DateTimeUtils.localDateToStr(arrivalDateLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                        guestsInHouseComplimentaryBO.setArrivalDate(arrivalDate);
                    }
                    //离店日期
                    String deptDateStr = dataElement.elementTextTrim("DEPARTURE");
                    if (StringUtils.isNotBlank(deptDateStr)) {
                        LocalDate deptDateLocalDate = DateTimeUtils.strToLocalDate(deptDateStr, BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);
                        String deptDate = DateTimeUtils.localDateToStr(deptDateLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                        guestsInHouseComplimentaryBO.setDepartureDate(deptDate);
                    }

                    String adultsNumber = dataElement.elementTextTrim("ADULTS");
                    guestsInHouseComplimentaryBO.setAdultsNumber(adultsNumber.isEmpty() ? 0 : Integer.parseInt(adultsNumber));
                    String childrenNumber = dataElement.elementTextTrim("CHILDREN");
                    guestsInHouseComplimentaryBO.setChildrenNumber(childrenNumber.isEmpty() ? 0 : Integer.parseInt(childrenNumber));

                    // 获取备注信息
                    List<Node> commentNodes = node.selectNodes("LIST_G_COMMENT_RESV_NAME_ID/G_COMMENT_RESV_NAME_ID");
                    if (CollectionUtils.isNotEmpty(commentNodes)) {
                        List<String> commentList = Lists.newArrayListWithExpectedSize(commentNodes.size());
                        for (Node commentNode : commentNodes) {
                            Element commentElement = (Element) commentNode;
                            commentList.add(commentElement.elementTextTrim("RES_COMMENT"));
                        }
                        guestsInHouseComplimentaryBO.setCommentList(commentList);
                    } else {
                        guestsInHouseComplimentaryBO.setCommentList(Collections.emptyList());
                    }

                    result.add(guestsInHouseComplimentaryBO);
                }
                return result;
            } catch (DocumentException e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "source=opera, parse [Guests In-House Complimentary] 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 inputStream = file.getInputStream()) {
                //校验文件节点是否满足需求
                FileCheckUtils.checkGuestsInHouseComplimentaryFile(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse [Guests In-House Complimentary] excel error", e2);
            }
        }

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

                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(6);
                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 + "/" + s3FilePath +
                        UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                snsSender.publish(EventSubjectEnum.GUESTS_IN_HOUSE_COMPLIMENTARY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Import opera Guests In-House Complimentary report exception", e);
            }
        }

    }