# RateShopGroupPickupServiceByOpera.java

    package cloud.wconnect.rateshop.service.rateshop.grouppickup;

    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.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.rateshop.cons.BusinessEnum;
    import cloud.wconnect.rateshop.cons.EventSubjectEnum;
    import cloud.wconnect.rateshop.cons.rateshop.BookingStatusEnum;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.GroupPickupBO;
    import cloud.wconnect.rateshop.service.AmazonS3Service;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    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.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;

    /**
     * 解析 Opera 系统的 Group Pickup/Service 报告
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class RateShopGroupPickupServiceByOpera implements IRateShopGroupPickupService {

        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${aws-s3.third-party.key.rate-shop.group-pickup}")
        private String s3FilePath;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Value("${file-max-size.import-report.rate-shop}")
        private long fileMaxSize;

        /**
         * 支持的报告来源
         *
         * @param source 报告来源
         * @return boolean
         * @author zc
         * @date 2024/3/23
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in                  报告文件流
         * @param propertyDTO         资产
         * @param startDate           数据日期，开始时间（整点时间戳）
         * @param endDate             数据日期，结束时间（整点时间戳）
         * @param bookingStatusLocale 解析预订状态的语言标识(解析Other报告时，用户可以自主选择系统支持的语言模板)
         * @return 报告数据
         * @author zc
         * @date 2024/3/22
         */
        @Override
        public List<GroupPickupBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate, Locale bookingStatusLocale) throws ParseReportException {
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_DD_MMM_YY, Locale.ENGLISH);
                ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());

                // 获取国际化的配置
                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

                List<GroupPickupBO> resultList = Lists.newArrayList();

                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_ALLOTMENT_CODE");
                for (Node node : nodes) {
                    Element dataElement = (Element) node;

                    Element listAllotmentDate = dataElement.element("LIST_G_ALLOTMENT_DATE");
                    List<Element> allotmentDateList = listAllotmentDate.elements("G_ALLOTMENT_DATE");
                    if (CollectionUtils.isEmpty(allotmentDateList)) {
                        continue;
                    }

                    // Booking status
                    String bookingStatusStr = dataElement.element("BOOKING_STATUS").getTextTrim();
                    if (StringUtils.isBlank(bookingStatusStr)) {
                        continue;
                    }
                    int bookingStatus = BookingStatusEnum.getCodeBySymbol(bookingStatusStr);
                    if (bookingStatus == BaseConstant.ZERO) {
                        continue;
                    }

                    String description = dataElement.element("DESCRIPTION").getTextTrim();

                    // Rate blocked
                    String minRate1Str = dataElement.element("MIN_RATE1").getTextTrim();
                    BigDecimal minRate1 = StringUtils.isEmpty(minRate1Str) ? null : new BigDecimal(minRate1Str)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    // Rate pickup
                    String minRate2Str = dataElement.element("MIN_RATE2").getTextTrim();
                    BigDecimal minRate2 = StringUtils.isEmpty(minRate2Str) ? null : new BigDecimal(minRate2Str)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    for (Element allotmentDateElement : allotmentDateList) {
                        Element listBlockSize = allotmentDateElement.element("LIST_G_BLOCKSIZE");
                        List<Element> blocksizeList = listBlockSize.elements("G_BLOCKSIZE");
                        if (CollectionUtils.isEmpty(blocksizeList)) {
                            continue;
                        }

                        String allotmentDateStr = allotmentDateElement.element("ALLOTMENT_DATE").getTextTrim();
                        String[] consideredDateArr = StringUtils.split(allotmentDateStr, "-");
                        consideredDateArr[1] = DateTimeUtils.capitalize(consideredDateArr[1]);
                        LocalDate localDate = LocalDate.parse(String.join("-", consideredDateArr), dateTimeFormatter);
                        long allotmentDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(zoneId));

                        // 判断数据日期是否在开始日期 和 结束日期之间
                        if (allotmentDate < startDate || allotmentDate > endDate) {
                            continue;
                        }
                        String formattedDateStr = DateTimeUtils.timestampToStr(allotmentDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());

                        for (Element blocksizeElement : blocksizeList) {
                            // Rooms blocked
                            String allottedStr = blocksizeElement.element("ALLOTTED").getTextTrim();
                            Integer allotted = StringUtils.isEmpty(allottedStr) ? null : Integer.parseInt(allottedStr);

                            // Rooms pickup
                            String pickupStr = blocksizeElement.element("PICKUP").getTextTrim();
                            Integer pickup = StringUtils.isEmpty(pickupStr) ? null : Integer.parseInt(pickupStr);

                            resultList.add(GroupPickupBO.builder()
                                    .date(formattedDateStr)
                                    .bookingStatus(bookingStatus)
                                    .groupName(description)
                                    .rateBlocked(minRate1)
                                    .ratePickup(minRate2)
                                    .roomBlocked(allotted)
                                    .roomPickup(pickup)
                                    .build());
                        }
                    }
                }

                return resultList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.INTERNAL_SERVICE_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.INTERNAL_SERVICE_ERROR.getCode(),
                        "source=opera, parse [Group Pickup/service] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file 文件
         * @author lichen
         * @date 2024/8/14
         */
        @Override
        public void checkFile(MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            try (InputStream inputStream = file.getInputStream()) {
                FileCheckUtils.checkGroupPickup(inputStream);
            } catch (BadRequestException exception) {
                throw exception;
            } catch (Exception ioException) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse [group pickup/service] report error", ioException);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param file        文件
         * @param startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @return void
         * @author lichen
         * @date 2024/8/14
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, long startDate, long endDate, long logId, int userId) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(7);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(propertyDTO.getAbbr()));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());
                params.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.RATE_SHOP.getBusiness());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), logId);
                params.put(EventBodyParamEnum.START_DATE.getDesc(), startDate);
                params.put(EventBodyParamEnum.END_DATE.getDesc(), endDate);

                snsSender.publish(EventSubjectEnum.GROUP_PICKUP_SERVICE_TODAY_NINETY_DAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "handle group pickup/service report, send event exception", e);
            }
        }
    }