# WMRevenueReservationForecastParseServiceByOpera.java

    package cloud.wconnect.rateshop.service.weeklymonthlyrevenue.reservationforecast;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.entity.revenue.RevenueCustomersRule;
    import cloud.wconnect.rateshop.pojo.bo.weeklymonthlyrevenue.WMRevenueReservationForecastBO;
    import cloud.wconnect.rateshop.service.revenue.IRevenueCustomersRuleService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.MapUtils;
    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.stereotype.Component;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * 解析 Opera 系统的 Reservation Forecast/Service 报告
     *
     * @author zc
     * @date 2024/05/20
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class WMRevenueReservationForecastParseServiceByOpera implements IWMRevenueReservationForecastParseService {
        @Resource
        private IRevenueCustomersRuleService revenueCustomersRuleService;

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return WMRevenueReservationForecastBO 集合
         * @author zc
         * @date 2024/5/20
         */
        @Override
        public List<WMRevenueReservationForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            Map<Integer, List<String>> type2RuleList = revenueCustomersRuleService.list(propertyDTO.getId()).stream()
                    .collect(Collectors.toMap(RevenueCustomersRule::getType, item -> Arrays.stream(item.getRule().split(",")).toList()));
            if (MapUtils.isEmpty(type2RuleList)) {
                return Collections.emptyList();
            }

            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            List<String> groupRules = type2RuleList.getOrDefault(RevenueCons.GROUP, Collections.emptyList());
            List<String> contractRules = type2RuleList.getOrDefault(RevenueCons.CONTRACT, Collections.emptyList());
            try {
                long startDate = dateRange.get(0);
                long endDate = dateRange.get(1);

                Document document = new SAXReader().read(in);
                List<Node> dateNodes = document.selectNodes("//DAY");

                List<WMRevenueReservationForecastBO> reservationForecastBOList = Lists.newArrayList();
                for (Node node : dateNodes) {
                    Element element = (Element) node;
                    String theDateStr = element.elementText("CHAR_RESERVATION_DATE");
                    LocalDate theLocalDate = DateTimeUtils.strToLocalDate(theDateStr, BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);
                    long theDate = Long.parseLong(DateTimeUtils.localDateToStr(theLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (theDate < startDate || theDate > endDate) {
                        continue;
                    }

                    String theDay = DateTimeUtils.localDateToStr(theLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                    BigDecimal totalRevenue = null;
                    BigDecimal groupRevenue = null;
                    BigDecimal contractRevenue = null;
                    Integer totalRoomsSold = null;
                    Integer groupRoomsSold = null;
                    Integer contractRoomsSold = null;

                    List<Node> childNodes = node.selectNodes("./LIST_MARKET/MARKET");
                    for (Node childNode : childNodes) {
                        Element elementChild = (Element) childNode;
                        String marketCode = elementChild.elementText("MARKET_CODE");
                        List<Node> detailNodes = childNode.selectNodes("./LIST_DETAIL/DETAIL");
                        for (Node detailNode : detailNodes) {
                            Element detailElement = (Element) detailNode;
                            String revenueStr = detailElement.elementTextTrim("TOTAL_REVENUE");
                            if (!revenueStr.isEmpty()) {
                                BigDecimal revenue = new BigDecimal(revenueStr);

                                // 累计 Total revenue
                                if (Objects.isNull(totalRevenue)) {
                                    totalRevenue = BigDecimal.ZERO;
                                }
                                totalRevenue = totalRevenue.add(revenue);

                                if (groupRules.contains(marketCode)) {
                                    // 累计 Group revenue
                                    if (Objects.isNull(groupRevenue)) {
                                        groupRevenue = BigDecimal.ZERO;
                                    }
                                    groupRevenue = groupRevenue.add(revenue);
                                }

                                if (contractRules.contains(marketCode)) {
                                    // 累计 Contract revenue
                                    if (Objects.isNull(contractRevenue)) {
                                        contractRevenue = BigDecimal.ZERO;
                                    }
                                    contractRevenue = contractRevenue.add(revenue);
                                }
                            }
                            String roomsSoldStr = detailElement.elementTextTrim("NO_DEFINITE_ROOMS");
                            if (StringUtils.isNotBlank(roomsSoldStr)) {
                                int roomsSold = Integer.parseInt(roomsSoldStr);

                                // 累计 Total rooms sold
                                if (Objects.isNull(totalRoomsSold)) {
                                    totalRoomsSold = 0;
                                }
                                totalRoomsSold = totalRoomsSold + roomsSold;

                                if (groupRules.contains(marketCode)) {
                                    // 累计 Group rooms sold
                                    if (Objects.isNull(groupRoomsSold)) {
                                        groupRoomsSold = 0;
                                    }
                                    groupRoomsSold = groupRoomsSold + roomsSold;
                                }

                                if (contractRules.contains(marketCode)) {
                                    // 累计 Contract rooms sold
                                    if (Objects.isNull(contractRoomsSold)) {
                                        contractRoomsSold = 0;
                                    }
                                    contractRoomsSold = contractRoomsSold + roomsSold;
                                }
                            }
                        }
                    }

                    WMRevenueReservationForecastBO reservationForecastBO = new WMRevenueReservationForecastBO();
                    reservationForecastBO.setTheDay(theDay);

                    BigDecimal transientRevenue = Objects.isNull(totalRevenue) ? null :
                            totalRevenue.subtract(Objects.isNull(groupRevenue) ? BigDecimal.ZERO : groupRevenue)
                                    .subtract(Objects.isNull(contractRevenue) ? BigDecimal.ZERO : contractRevenue);
                    reservationForecastBO.setTransientRevenue(formatPrecision(transientRevenue, roundingMode));
                    reservationForecastBO.setGroupRevenue(formatPrecision(groupRevenue, roundingMode));
                    reservationForecastBO.setContractRevenue(formatPrecision(contractRevenue, roundingMode));

                    Integer transientSold = Objects.isNull(totalRoomsSold) ? null :
                            totalRoomsSold - (Objects.isNull(groupRoomsSold) ? 0 : groupRoomsSold)
                                    - (Objects.isNull(contractRoomsSold) ? 0 : contractRoomsSold);
                    reservationForecastBO.setTransientSold(transientSold);
                    reservationForecastBO.setGroupSold(groupRoomsSold);
                    reservationForecastBO.setContractSold(contractRoomsSold);

                    reservationForecastBOList.add(reservationForecastBO);
                }

                return reservationForecastBOList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Weekly Monthly Revenue Reservation Forecast Opera report error.", e);
            }
        }

        /**
         * 格式化精度
         *
         * @param value        数值
         * @param roundingMode 舍入模式
         * @return java.math.BigDecimal
         * @author zc
         * @date 2025/5/30
         */
        private BigDecimal formatPrecision(BigDecimal value, RoundingMode roundingMode) {
            if (Objects.isNull(value)) {
                return null;
            }
            return value.setScale(BaseConstant.DATA_PRECISION, roundingMode);
        }
    }