# DailySummaryHistoryAndForecastParseImplByOpera.java

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

    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.entity.revenue.RevenueAdrConfig;
    import cloud.wconnect.rateshop.pojo.bo.revenue.DailySummaryBO;
    import cloud.wconnect.rateshop.pojo.dto.revenue.HistoryAndForecastDailySummaryDTO;
    import cloud.wconnect.rateshop.service.revenue.IHandleHistoryAndForecastReportCommonService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueAdrConfigService;
    import cloud.wconnect.rateshop.service.revenue.IRevenueDailySummaryService;
    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.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.stereotype.Service;
    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.Collections;
    import java.util.List;
    import java.util.Locale;
    import java.util.Objects;

    /**
     * Daily summary 功能解析HistoryAndForecast报告
     *
     * @author lichen
     * @date 2024/3/26
     */
    @RequiredArgsConstructor
    @Service
    @Slf4j
    @DS("rate_shop")
    public class DailySummaryHistoryAndForecastParseImplByOpera implements IDailySummaryHistoryAndForecastParse {

        private final RoomsConfigInternalService roomsConfigInternalService;
        private final IRevenueAdrConfigService revenueAdrConfigService;
        private final IHandleHistoryAndForecastReportCommonService handleHFYesterdayAndNinetyCommonService;
        private final IRevenueDailySummaryService revenueDailySummaryService;

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param startDate   数据日期，开始时间
         * @param endDate     数据日期，结束时间
         * @return java.util.List<cloud.wconnect.rateshop.pojo.dto.revenue.HourSummaryDTO>
         * @author lichen
         * @date 2024/3/27
         */
        @Override
        public List<HistoryAndForecastDailySummaryDTO> parse(InputStream in, PropertyDTO propertyDTO, Long startDate, Long endDate) throws ParseReportException {
            long syncTime = DateTimeUtils.nowTimestamp();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
            ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_CONSIDERED_DATE");
                if (CollectionUtils.isEmpty(nodes)) return Collections.emptyList();

                // 获取房间数配置
                RoomsConfigDTO roomsConfig = roomsConfigInternalService.getRoomsConfig(propertyDTO.getId());
                Integer rooms = roomsConfig.getRooms();

                //资产配置的规则
                RevenueAdrConfig revenueAdrConfig = revenueAdrConfigService.get(propertyDTO.getId());
                boolean checkTransientDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckTransientDeduct();
                boolean checkTransientNonDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckTransientNonDeduct();
                boolean checkGroupDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckGroupDeduct();
                boolean checkGroupNonDeduct = Objects.nonNull(revenueAdrConfig) && revenueAdrConfig.getCheckGroupNonDeduct();

                InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
                RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());
                BigDecimal oneHundred = BigDecimal.valueOf(100L);

                List<HistoryAndForecastDailySummaryDTO> hourSummaryList = Lists.newArrayListWithCapacity(nodes.size());
                for (Node node : nodes) {
                    Element dataElement = (Element) node;
                    HistoryAndForecastDailySummaryDTO historyAndForecastDailySummaryDTO = new HistoryAndForecastDailySummaryDTO();

                    //获取数据日期
                    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 theDate = DateTimeUtils.toTimestamp(localDate.atStartOfDay(zoneId));

                    if (theDate >= startDate && theDate <= endDate) {
                        historyAndForecastDailySummaryDTO.setTheDate(theDate);
                        //小时数
                        int hour = DateTimeUtils.dateTimeNow(propertyDTO.getTimezone()).getHour();
                        historyAndForecastDailySummaryDTO.setTheHour(hour);
                        //同步时间
                        historyAndForecastDailySummaryDTO.setSyncTime(syncTime);

                        //入住房间数
                        String totalOccStr = dataElement.element("CF_CALC_OCC_ROOMS").getTextTrim();
                        int totalOcc = StringUtils.isEmpty(totalOccStr) ? 0 : Integer.parseInt(totalOccStr);
                        historyAndForecastDailySummaryDTO.setTotalOcc(totalOcc);
                        //故障房
                        String oooRoomStr = dataElement.element("CF_OOO_ROOMS").getTextTrim();
                        int oooRooms = StringUtils.isEmpty(oooRoomStr) ? 0 : Integer.parseInt(oooRoomStr);
                        historyAndForecastDailySummaryDTO.setOooRooms(oooRooms);

                        //设置可用房间数 = 配置的房间数 - 入住房间数 - 故障房间数
                        historyAndForecastDailySummaryDTO.setRoomsAvailable(rooms - totalOcc - oooRooms);

                        // 如果勾选了 Transient deduct，则累加交订金的 Transient 房间数
                        int transientRooms = 0;
                        String transientRoomsStr = dataElement.element("IND_DEDUCT_ROOMS").getTextTrim();
                        if (checkTransientDeduct && StringUtils.isNotEmpty(transientRoomsStr)) {
                            transientRooms = Integer.parseInt(transientRoomsStr);
                        }

                        // 如果勾选了 Transient non deduct，则累加未交订金的 Transient 房间数
                        int nonDeductRooms = 0;
                        String nonDeductRoomsStr = dataElement.element("IND_NON_DEDUCT_ROOMS").getTextTrim();
                        if (checkTransientNonDeduct && StringUtils.isNotEmpty(nonDeductRoomsStr)) {
                            nonDeductRooms = Integer.parseInt(nonDeductRoomsStr);
                        }
                        historyAndForecastDailySummaryDTO.setTransientRooms(transientRooms + nonDeductRooms);

                        // 如果勾选了 Group deduct，则累加交订金的 Group 房间数
                        int groupRooms = 0;
                        String groupRoomsStr = dataElement.element("GRP_DEDUCT_ROOMS").getTextTrim();
                        if (checkGroupDeduct && StringUtils.isNotEmpty(groupRoomsStr)) {
                            groupRooms = Integer.parseInt(groupRoomsStr);
                        }

                        // 如果勾选了 Group non deduct，则累加未交订金的 Group 房间数
                        int grpNonDeductRooms = 0;
                        String grpNonDeductRoomsStr = dataElement.element("GRP_NON_DEDUCT_ROOMS").getTextTrim();
                        if (checkGroupNonDeduct && StringUtils.isNotEmpty(grpNonDeductRoomsStr)) {
                            grpNonDeductRooms = Integer.parseInt(grpNonDeductRoomsStr);
                        }
                        historyAndForecastDailySummaryDTO.setGroupRooms(groupRooms + grpNonDeductRooms);
                        historyAndForecastDailySummaryDTO.setTotalRoomsSold(transientRooms + nonDeductRooms + groupRooms + grpNonDeductRooms);

                        // 设置 occ，根据 occ 的配置规则判断：1.使用配置的房间数计算 occ，2.直接使用文件中的 occ
                        if (roomsConfig.getOccRule() == RevenueCons.USE_ROOMS_TO_CALCULATE) {
                            String totalOccRoomsStr = dataElement.element("CF_CALC_OCC_ROOMS").getTextTrim();
                            if (StringUtils.isNotEmpty(totalOccRoomsStr)) {
                                //  Occ. % = total occ rooms / 总房间数
                                BigDecimal occPercent = new BigDecimal(totalOccRoomsStr)
                                        .multiply(oneHundred)
                                        .divide(BigDecimal.valueOf(rooms), BaseConstant.DATA_PRECISION, roundingMode);
                                historyAndForecastDailySummaryDTO.setOcc(occPercent);
                            }
                        } else {
                            String occPercentStr = dataElement.element("CF_OCCUPANCY").getTextTrim();
                            if (StringUtils.isNotEmpty(occPercentStr)) {
                                historyAndForecastDailySummaryDTO.setOcc(new BigDecimal(occPercentStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));
                            }
                        }

                        hourSummaryList.add(historyAndForecastDailySummaryDTO);
                    }
                }
                return hourSummaryList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "source=opera, parse [History and forecast/service] report error", e);
            }
        }

        /**
         * 保存报告数据
         *
         * @param propertyDTO        资产
         * @param dailySummaryBOList 报告数据
         * @param operatorId   操作人 id
         * @param logId        导入记录 id
         * @author yyt
         * @date 2026/3/3
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void saveReportData(PropertyDTO propertyDTO, List<HistoryAndForecastDailySummaryDTO> dailySummaryBOList, Integer operatorId, Long logId) {
            List<DailySummaryBO> dailySummaryBOS = handleHFYesterdayAndNinetyCommonService.filterAndTransform(propertyDTO, operatorId, logId, dailySummaryBOList);
            if (CollectionUtils.isNotEmpty(dailySummaryBOList)) {
                revenueDailySummaryService.saveOrUpdate(propertyDTO, dailySummaryBOS);
            }
        }
    }