# HotelKpiHistoryAndForecastParseServiceByOpera.java

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

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    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.FileCheckUtils;
    import cloud.wconnect.commonlib.util.InternationalizationUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.workperformance.pojo.bo.hotelkpi.HotelKpiHistoryAndForecastBO;
    import cloud.wconnect.workperformance.service.hotelkpi.IHotelKpiHandleReportService;
    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.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    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 HotelKpiHistoryAndForecastParseServiceByOpera implements IHotelKpiHistoryAndForecastParseService {

        private final IHotelKpiHandleReportService hotelKpiHandleReportService;

        @Value("${file-max-size.import-report.hotel-kpi}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2024/8/20
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            // 校验文件内容
            try (InputStream inputStream = file.getInputStream()) {
                FileCheckUtils.checkHistoryAndForecastFile(inputStream);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Check Hotel KPI History and forecast Opera report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @param logId       日志 id
         * @param operatorId  操作人 id
         * @author zc
         * @date 2024/8/21
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, List<Long> dateRange, long logId, int operatorId) {
            hotelKpiHandleReportService.sendHistoryAndForecastEvent(propertyDTO, SystemPlatformEnum.OPERA.getDesc(), file, dateRange, logId, operatorId);
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   报告数据日期范围(yyyyMMdd)
         * @return HotelKpiHistoryAndForecastBO 集合
         * @author zc
         * @date 2024/7/10
         */
        @Override
        public List<HotelKpiHistoryAndForecastBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_DD_MMM_YY, Locale.ENGLISH);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_CONSIDERED_DATE");

                List<HotelKpiHistoryAndForecastBO> resultList = Lists.newArrayList();
                for (Node node : nodes) {
                    Element dataElement = (Element) node;

                    // 获取数据日期
                    String consideredDateStr = dataElement.element("CONSIDERED_DATE").getTextTrim();
                    long consideredDate = parseDate(consideredDateStr, dateTimeFormatter);

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

                    HotelKpiHistoryAndForecastBO bo = new HotelKpiHistoryAndForecastBO();
                    LocalDate localDate = DateTimeUtils.strToLocalDate(String.valueOf(consideredDate), BaseConstant.DATE_FORMAT_YYYYMMDD);
                    bo.setDateStr(DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

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

                    // 获取 Arr. Rooms
                    String arrivalRoomsStr = dataElement.element("ARRIVAL_ROOMS").getTextTrim();
                    Integer arrivalRooms = StringUtils.isBlank(arrivalRoomsStr) ? null : Integer.parseInt(arrivalRoomsStr);
                    bo.setArrivalRooms(arrivalRooms);

                    // 获取 Dep. Rooms
                    String departureRoomsStr = dataElement.element("DEPARTURE_ROOMS").getTextTrim();
                    Integer departureRooms = StringUtils.isBlank(departureRoomsStr) ? null : Integer.parseInt(departureRoomsStr);
                    bo.setDepartureRooms(departureRooms);

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

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

                    resultList.add(bo);
                }
                return resultList;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Hotel KPI History and forecast Opera report error.", e);
            }
        }

        /**
         * 解析报告中的日期
         *
         * @param dateStr           Date
         * @param dateTimeFormatter 日期格式
         * @return 日期（yyyyMMdd）
         * @author zc
         * @date 2024/7/10
         */
        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));
        }
    }