# HistoryAndForecastListenerFileServiceByOpera.java

    package cloud.wconnect.rateshop.service.rateshop.historyandforecast.messagelistener;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.RoomsConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.service.RoomsConfigInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.rateshop.cons.revenue.RevenueCons;
    import cloud.wconnect.rateshop.pojo.bo.rateshop.HistoryAndForecastForRateShopBO;
    import cloud.wconnect.rateshop.service.rateshop.IPropertyOperationService;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopOccForecastService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import lombok.RequiredArgsConstructor;
    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.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;

    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.Objects;
    import java.util.Optional;

    /**
     * 解析 Opera 系统的 History And Forecast/Service 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("rate_shop")
    public class HistoryAndForecastListenerFileServiceByOpera implements IHistoryAndForecastListenerFileService {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final IPropertyOperationService propertyOperationService;
        private final IRateShopOccForecastService rateShopOccForecastService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param startDate   数据日期，开始时间(整点时刻时间戳)
         * @param endDate     数据日期，结束时间(整点时刻时间戳)
         * @return HistoryAndForecastForRateShopDTO
         * @author zc
         * @date 2024/3/23
         */
        @Override
        public List<HistoryAndForecastForRateShopBO> parse(InputStream in, PropertyDTO propertyDTO, long startDate, long endDate) throws ParseReportException {
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
                ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());

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

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

                // 获取房间数配置
                RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
                Integer configTotalRooms = Objects.isNull(roomsConfig) ? null : roomsConfig.getRooms();

                List<HistoryAndForecastForRateShopBO> resultList = Lists.newArrayListWithCapacity(nodes.size());
                for (Node node : nodes) {
                    Element dataElement = (Element) node;

                    // 获取数据日期
                    String consideredDateStr = dataElement.element("CONSIDERED_DATE").getTextTrim();
                    String[] consideredDateArr = StringUtils.split(consideredDateStr, "-");
                    consideredDateArr[1] = DateTimeUtils.capitalize(consideredDateArr[1]);
                    LocalDate localDate = LocalDate.parse(String.join("-", consideredDateArr), dateTimeFormatter);
                    long consideredDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(zoneId));

                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (consideredDate < startDate || consideredDate > endDate) continue;

                    String formattedDateStr = DateTimeUtils.timestampToStr(consideredDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD, propertyDTO.getTimezone());

                    // 获取 Total occ
                    String totalOccStr = dataElement.elementTextTrim("CF_CALC_OCC_ROOMS");
                    Integer totalOcc = StringUtils.isEmpty(totalOccStr) ? null : Integer.parseInt(totalOccStr);
                    int subtractTotalOcc = Optional.ofNullable(totalOcc).orElse(BaseConstant.ZERO);

                    // 获取 OOO Rooms
                    String oooRoomsStr = dataElement.elementTextTrim("CF_OOO_ROOMS");
                    Integer oooRooms = StringUtils.isEmpty(oooRoomsStr) ? null : Integer.parseInt(oooRoomsStr);
                    int subtractOooRooms = Optional.ofNullable(oooRooms).orElse(BaseConstant.ZERO);

                    // 获取 PC occ
                    BigDecimal pcOccPercent;
                    // 如果配置了房间数，则根据 pc occ 计算规则判断：1.使用配置的房间数计算 pc occ，2.直接使用文件中的 occ 作为 pc occ
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(totalOcc)
                            && (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE)) {
                        // pc occ = sold rooms / total rooms
                        BigDecimal totalOccBD = BigDecimal.valueOf(totalOcc);
                        pcOccPercent = totalOccBD.multiply(BigDecimal.valueOf(100))
                                .divide(new BigDecimal(configTotalRooms), BaseConstant.DATA_PRECISION, roundingMode);
                    } else {
                        String occPercentStr = dataElement.elementTextTrim("CF_OCCUPANCY");
                        pcOccPercent = StringUtils.isEmpty(occPercentStr) ?
                                null : new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    }

                    // 获取 SC occ
                    BigDecimal scOccPercent = null;
                    if (Objects.nonNull(roomsConfig) && Objects.nonNull(totalOcc)) {
                        // sc occ = sold rooms / (total rooms - ooo rooms)
                        BigDecimal totalOccBD = BigDecimal.valueOf(totalOcc);
                        int denominator = configTotalRooms - subtractOooRooms;
                        if (denominator != BaseConstant.ZERO) {
                            scOccPercent = totalOccBD.multiply(BigDecimal.valueOf(100))
                                    .divide(BigDecimal.valueOf(denominator), BaseConstant.DATA_PRECISION, roundingMode);
                        } else {
                            scOccPercent = BigDecimal.ZERO;
                        }
                    }

                    // 计算 Rooms Available = 资产总房间数 - Total Occ. - OOO Rooms
                    Integer roomsAvailable = Objects.nonNull(configTotalRooms) ?
                            (configTotalRooms - subtractTotalOcc - subtractOooRooms) : null;

                    // 获取 ADR
                    String adrStr = dataElement.element("CF_AVERAGE_ROOM_RATE").getTextTrim();
                    BigDecimal adr = StringUtils.isEmpty(adrStr) ? null : new BigDecimal(adrStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    // 获取 Deduct Ind.
                    String deductIndStr = dataElement.element("IND_DEDUCT_ROOMS").getTextTrim();
                    Integer deductInd = StringUtils.isEmpty(deductIndStr) ? null : Integer.parseInt(deductIndStr);

                    // 获取 Deduct Group
                    String deductGroupStr = dataElement.element("GRP_DEDUCT_ROOMS").getTextTrim();
                    Integer deductGroup = StringUtils.isEmpty(deductGroupStr) ? null : Integer.parseInt(deductGroupStr);

                    resultList.add(HistoryAndForecastForRateShopBO.builder()
                            .date(formattedDateStr)
                            .roomsSold(totalOcc)
                            .transientSold(deductInd)
                            .groupSold(deductGroup)
                            .pcOcc(pcOccPercent)
                            .scOcc(scOccPercent)
                            .adr(adr)
                            .oooRooms(oooRooms)
                            .roomsAvailable(roomsAvailable)
                            .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 [History and forecast/service] report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产DTO
         * @param boList      报告数据
         * @param operatorId  操作人 id
         * @author yyt
         * @date 2026/3/10
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastForRateShopBO> boList, int operatorId) {
            // 保存数据
            propertyOperationService.saveHistoryAndForecastReportData(propertyDTO, operatorId, boList);
            // 保存occ数据
            rateShopOccForecastService.saveOccForecast(propertyDTO, operatorId, boList);
        }

    }