# DbPmsHfParseServiceByOpera.java

    package cloud.wconnect.workperformance.service.database.historyforecast;

    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.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.cons.database.DbCons;
    import cloud.wconnect.workperformance.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.historyforecast.DbPmsHfBO;
    import cloud.wconnect.workperformance.service.database.IDbReportService;
    import com.google.common.collect.Lists;
    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.util.List;

    /**
     * 解析 Opera History and Forecast/Service 报告
     *
     * @author zc
     * @date 2026/1/5
     */
    @Component
    public class DbPmsHfParseServiceByOpera implements IDbPmsHfParseService {

        private final IDbReportService reportService;

        public DbPmsHfParseServiceByOpera(IDbReportService reportService) {
            this.reportService = reportService;
        }

        @Value("${aws-s3.third-party.key.database.history-and-forecast}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.database}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author zc
         * @date 2026/1/5
         */
        @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 Database History and Forecast Opera report error", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @param importLog   日志
         * @param operatorId  操作人 id
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, DbReportImportLog importLog, int operatorId) {
            reportService.sendReportEvent(propertyDTO, file, importLog, operatorId, s3FilePath,
                    EventSubjectEnum.HISTORY_AND_FORECAST_SERVICE_LAST_2_DAY_TO_365_DAY.getSubject());
        }

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return List<DbPmsHfBO>
         * @author zc
         * @date 2026/1/5
         */
        @Override
        public List<DbPmsHfBO> parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            List<String> recTypeList = Lists.newArrayList(DbCons.HF_REPORT_DATA_HISTORY,
                    DbCons.HF_REPORT_DATA_FORECAST);
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            long startDate = dateRange.get(0);
            long endDate = dateRange.get(1);
            try {
                List<DbPmsHfBO> boList = 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)) {
                        continue;
                    }

                    List<Node> dateNodes = recTypeNodeElement.selectNodes(".//G_CONSIDERED_DATE");
                    for (Node dateNode : dateNodes) {
                        Element dataElement = (Element) dateNode;
                        // 获取数据日期
                        String consideredDateStr = dataElement.element("CHAR_CONSIDERED_DATE").getTextTrim().substring(0, 8);
                        LocalDate consideredLocalDate = DateTimeUtils.strToLocalDate(consideredDateStr, BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);
                        long consideredDate = Long.parseLong(DateTimeUtils.localDateToStr(consideredLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));

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

                        DbPmsHfBO bo = convert2Bo(consideredLocalDate, dataElement, roundingMode);
                        bo.setOperaDataType(recTypeDesc);
                        boList.add(bo);
                    }
                }

                return boList;
            } catch (DocumentException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Database parse History and Forecast Opera report error", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param dataElement  数据元素
         * @param roundingMode 舍入模式
         * @return PmsHfBO
         * @author zc
         * @date 2026/1/5
         */
        private DbPmsHfBO convert2Bo(LocalDate consideredLocalDate, Element dataElement, RoundingMode roundingMode) {
            int scale = BaseConstant.DATA_PRECISION;

            DbPmsHfBO bo = new DbPmsHfBO();
            bo.setDStr(DateTimeUtils.localDateToStr(consideredLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return bo;
        }
    }