# GmwrHistoryAndForecastParseServiceByOpera.java

    package cloud.wconnect.workperformance.service.gmwr.historyandforecast;

    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.workperformance.pojo.bo.gmwr.GmwrHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.gmwr.IGmwrHistoryAndForecastService;
    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.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Locale;

    /**
     * 解析 Opera 系统的 History And Forecast 报告
     */
    @RequiredArgsConstructor
    @Slf4j
    @Component
    @DS("work_performance")
    public class GmwrHistoryAndForecastParseServiceByOpera implements IGmwrHistoryAndForecastParseService {

        private final IGmwrHistoryAndForecastService gmwrHistoryAndForecastService;

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   日期范围(yyyyMMdd)
         * @return GmwrHistoryAndForecastBO 集合
         * @author zc
         * @date 2024/10/16
         */
        @Override
        public List<GmwrHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_DD_MMM_YY, Locale.ENGLISH);

                long startDate = dateRange.get(0);
                long endDate = dateRange.get(1);

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

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

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

                    // 获取数据日期
                    String consideredDateStr = dataElement.element("CONSIDERED_DATE").getTextTrim();
                    LocalDate localDate = parseDate(consideredDateStr, dateTimeFormatter);
                    long consideredDate = Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (consideredDate < startDate || consideredDate > endDate) {
                        continue;
                    }

                    // 获取 OOO Rooms
                    String oooRoomsStr = dataElement.element("CF_OOO_ROOMS").getTextTrim();
                    Integer oooRooms = StringUtils.isBlank(oooRoomsStr) ? null : Integer.parseInt(oooRoomsStr);

                    // 获取 Rooms Sold
                    String roomsSoldStr = dataElement.element("CF_CALC_OCC_ROOMS").getTextTrim();
                    Integer roomsSold = StringUtils.isBlank(roomsSoldStr) ? null : Integer.parseInt(roomsSoldStr);

                    // 获取 Revenue
                    String revenueStr = dataElement.element("REVENUE").getTextTrim();
                    BigDecimal roomRevenue = StringUtils.isBlank(revenueStr) ? null : new BigDecimal(revenueStr)
                            .setScale(BaseConstant.DATA_PRECISION, roundingMode);

                    resultList.add(GmwrHistoryAndForecastBO.builder()
                            .dateStr(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD))
                            .ooo(oooRooms)
                            .roomsSold(roomsSold)
                            .roomRevenue(roomRevenue)
                            .build());
                }
                return resultList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse GM Weekly Report History and forecast Opera report error.", e);
            }
        }

        /**
         * 解析报告中的日期
         *
         * @param dateStr           Date
         * @param dateTimeFormatter 日期格式
         * @return LocalDate
         * @author zc
         * @date 2024/10/16
         */
        private LocalDate parseDate(String dateStr, DateTimeFormatter dateTimeFormatter) {
            String[] dateArr = StringUtils.split(dateStr, "-");
            dateArr[1] = DateTimeUtils.capitalize(dateArr[1]);
            return LocalDate.parse(String.join("-", dateArr), dateTimeFormatter);
        }

        /**
         * 处理 History And Forecast 数据
         *
         * @param propertyDTO              资产
         * @param historyAndForecastBOList 报告数据
         * @author yyt
         * @date 2026/2/5
         **/
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void handleHistoryAndForecast(PropertyDTO propertyDTO, List<GmwrHistoryAndForecastBO> historyAndForecastBOList) {
            gmwrHistoryAndForecastService.handleHistoryAndForecast(propertyDTO, historyAndForecastBOList);
        }

    }