# WMRevenueHistoryAndForecastParseServiceByOpera.java

    package cloud.wconnect.rateshop.service.weeklymonthlyrevenue.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.*;
    import cloud.wconnect.rateshop.cons.weeklymonthlyrevenue.MonthlyRevenueCons;
    import cloud.wconnect.rateshop.pojo.bo.weeklymonthlyrevenue.WMRevenueHistoryAndForecastBO;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    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 java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Locale;

    /**
     * 解析 Opera 系统的 History And Forecast/Service 报告
     *
     * @author zc
     * @date 2024/05/17
     */
    @Slf4j
    @Component
    @DS("rate_shop")
    public class WMRevenueHistoryAndForecastParseServiceByOpera implements IWMRevenueHistoryAndForecastParseService {

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

        /**
         * 解析报告
         *
         * @param in          报告文件流
         * @param propertyDTO 资产
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return WMRevenueHistoryAndForecastBO 集合
         * @author zc
         * @date 2024/8/22
         */
        @Override
        public List<WMRevenueHistoryAndForecastBO> 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());

                ArrayList<String> recTypeList = Lists.newArrayList(MonthlyRevenueCons.HISTORY_AND_FORECAST_REPORT_DATA_HISTORY,
                        MonthlyRevenueCons.HISTORY_AND_FORECAST_REPORT_DATA_FORECAST);

                List<WMRevenueHistoryAndForecastBO> historyAndForecastBOList = Lists.newArrayList();

                Document document = new SAXReader().read(in);
                List<Node> recTypeNodes = document.selectNodes("//G_REC_TYPE");
                for (Node recTypeNode : recTypeNodes) {
                    Element recTypeNodeElement = (Element) recTypeNode;
                    //数据类型
                    String recTypeDesc = recTypeNodeElement.element("REC_TYPE_DESC").getTextTrim();
                    if (recTypeList.contains(recTypeDesc)) {

                        List<Node> nodeList = recTypeNodeElement.selectNodes(".//G_CONSIDERED_DATE");
                        for (Node node : nodeList) {
                            Element dataElement = (Element) node;
                            // 获取数据日期
                            String consideredDateStr = dataElement.element("CONSIDERED_DATE").getTextTrim();
                            long consideredDate = parseDate(consideredDateStr, dateTimeFormatter);

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

                            WMRevenueHistoryAndForecastBO wmRevenueHistoryAndForecastBO = convert2Bo(consideredDate, dataElement, roundingMode);
                            wmRevenueHistoryAndForecastBO.setOperaDataType(recTypeDesc);
                            historyAndForecastBOList.add(wmRevenueHistoryAndForecastBO);
                        }
                    }
                }

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

        /**
         * 将报告中的信息转换为实体类
         *
         * @param consideredDate consideredDate
         * @param dataElement    dataElement
         * @param roundingMode   舍入模式
         * @return WMRevenueHistoryAndForecastBO
         * @author zc
         * @date 2025/5/21
         */
        private WMRevenueHistoryAndForecastBO convert2Bo(long consideredDate, Element dataElement, RoundingMode roundingMode) {
            WMRevenueHistoryAndForecastBO bo = new WMRevenueHistoryAndForecastBO();

            int scale = BaseConstant.DATA_PRECISION;
            LocalDate localDate = DateTimeUtils.strToLocalDate(String.valueOf(consideredDate), BaseConstant.DATE_FORMAT_YYYYMMDD);
            bo.setTheDay(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            // Room Revenue
            String revenueStr = dataElement.element("REVENUE").getTextTrim();
            bo.setRoomRevenue(StringUtils.isBlank(revenueStr) ? null : new BigDecimal(revenueStr)
                    .setScale(scale, roundingMode));

            // Deduct Individual
            String deductIndividualStr = dataElement.elementTextTrim("IND_DEDUCT_ROOMS");
            bo.setDeductIndividual(StringUtils.isBlank(deductIndividualStr) ? 0 : Integer.parseInt(deductIndividualStr));

            // Deduct Individual Revenue
            String deductIndividualRevenueStr = dataElement.elementTextTrim("CF_IND_DED_REV");
            bo.setDeductIndividualRevenue(StringUtils.isBlank(deductIndividualRevenueStr) ? null :
                    new BigDecimal(deductIndividualRevenueStr).setScale(scale, roundingMode));

            // Non-Deduct Individual
            String nonDeductIndividualStr = dataElement.elementTextTrim("IND_NON_DEDUCT_ROOMS");
            bo.setNonDeductIndividual(StringUtils.isBlank(nonDeductIndividualStr) ? 0 : Integer.parseInt(nonDeductIndividualStr));

            // Non-Deduct Individual Revenue
            String nonDeductIndividualRevenueStr = dataElement.elementTextTrim("CF_IND_NON_DED_REV");
            bo.setNonDeductIndividualRevenue(StringUtils.isBlank(nonDeductIndividualRevenueStr) ? null :
                    new BigDecimal(nonDeductIndividualRevenueStr).setScale(scale, roundingMode));

            // Deduct Group
            String deductGroupStr = dataElement.elementTextTrim("GRP_DEDUCT_ROOMS");
            bo.setDeductGroup(StringUtils.isBlank(deductGroupStr) ? 0 : Integer.parseInt(deductGroupStr));

            // Deduct Group Revenue
            String deductGroupRevenueStr = dataElement.elementTextTrim("CF_BLK_DED_REV");
            bo.setDeductGroupRevenue(StringUtils.isBlank(deductGroupRevenueStr) ? null :
                    new BigDecimal(deductGroupRevenueStr).setScale(scale, roundingMode));

            // Non-Deduct Group
            String nonDeductGroupStr = dataElement.elementTextTrim("GRP_NON_DEDUCT_ROOMS");
            bo.setNonDeductGroup(StringUtils.isBlank(nonDeductGroupStr) ? 0 : Integer.parseInt(nonDeductGroupStr));

            // Non-Deduct Group Revenue
            String nonDeductGroupRevenueStr = dataElement.elementTextTrim("CF_BLK_NON_DED_REV");
            bo.setNonDeductGroupRevenue(StringUtils.isBlank(nonDeductGroupRevenueStr) ? null :
                    new BigDecimal(nonDeductGroupRevenueStr).setScale(scale, roundingMode));

            // Number of Persons
            String numberOfPersonsStr = dataElement.elementTextTrim("NO_PERSONS");
            bo.setNumberOfPersons(StringUtils.isBlank(numberOfPersonsStr) ? 0 : Integer.parseInt(numberOfPersonsStr));

            // Arrival Rooms
            String arrivalRoomsStr = dataElement.elementTextTrim("ARRIVAL_ROOMS");
            bo.setArrivalRooms(StringUtils.isBlank(arrivalRoomsStr) ? 0 : Integer.parseInt(arrivalRoomsStr));

            // Departure Rooms
            String departureRoomsStr = dataElement.elementTextTrim("DEPARTURE_ROOMS");
            bo.setDepartureRooms(StringUtils.isBlank(departureRoomsStr) ? 0 : Integer.parseInt(departureRoomsStr));

            // Complimentary Rooms
            String complimentaryRoomsStr = dataElement.element("COMPLIMENTARY_ROOMS").getTextTrim();
            bo.setComplimentaryRooms(StringUtils.isBlank(complimentaryRoomsStr) ? 0 : Integer.parseInt(complimentaryRoomsStr));

            // House Use Rooms
            String houseUseRoomsStr = dataElement.element("HOUSE_USE_ROOMS").getTextTrim();
            bo.setHouseUseRooms(StringUtils.isBlank(houseUseRoomsStr) ? 0 : Integer.parseInt(houseUseRoomsStr));

            // Day Use Rooms
            String dayUseRoomsStr = dataElement.element("DAY_USE_ROOMS").getTextTrim();
            bo.setDayUseRooms(StringUtils.isBlank(dayUseRoomsStr) ? 0 : Integer.parseInt(dayUseRoomsStr));

            // No Show Rooms
            String noShowRoomsStr = dataElement.element("NO_SHOW_ROOMS").getTextTrim();
            bo.setNoShowRooms(StringUtils.isBlank(noShowRoomsStr) ? 0 : Integer.parseInt(noShowRoomsStr));

            // Inventory Rooms
            String inventoryRoomsStr = dataElement.element("INVENTORY_ROOMS").getTextTrim();
            bo.setInventoryRooms(StringUtils.isBlank(inventoryRoomsStr) ? 0 : Integer.parseInt(inventoryRoomsStr));

            // Sell Inventory Rooms
            String sellInventoryRoomsStr = dataElement.element("CF_CALC_INV_ROOMS").getTextTrim();
            bo.setSellInventoryRooms(StringUtils.isBlank(sellInventoryRoomsStr) ? 0 : Integer.parseInt(sellInventoryRoomsStr));

            // Total Occ.(Total Rooms Sold)
            String totalOccStr = dataElement.elementTextTrim("CF_CALC_OCC_ROOMS");
            bo.setTotalOcc(StringUtils.isBlank(totalOccStr) ? 0 : Integer.parseInt(totalOccStr));

            // OOO Rooms
            String oooRoomsStr = dataElement.elementTextTrim("CF_OOO_ROOMS");
            bo.setOooRooms(StringUtils.isBlank(oooRoomsStr) ? 0 : Integer.parseInt(oooRoomsStr));

            // ADR
            String adrStr = dataElement.element("CF_AVERAGE_ROOM_RATE").getTextTrim();
            bo.setAverageRate(StringUtils.isBlank(adrStr) ? null : new BigDecimal(adrStr)
                    .setScale(scale, roundingMode));

            // OCC %
            String occPercentStr = dataElement.elementTextTrim("CF_OCCUPANCY");
            bo.setOccupancy(StringUtils.isBlank(occPercentStr) ? null : new BigDecimal(occPercentStr)
                    .setScale(scale, roundingMode));

            return bo;
        }

        /**
         * 解析报告中的日期
         *
         * @param dateStr           Date
         * @param dateTimeFormatter 日期格式
         * @return 日期（yyyyMMdd）
         * @author zc
         * @date 2024/5/18
         */
        private long parseDate(String dateStr, DateTimeFormatter dateTimeFormatter) {
            String[] dateArr = StringUtils.split(dateStr, "-");
            dateArr[1] = DateTimeUtils.capitalize(dateArr[1]);
            LocalDate localDate = LocalDate.parse(String.join("-", dateArr), dateTimeFormatter);
            return Long.parseLong(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
        }

    }