# DbPmsMarketCodeStatisticsParseServiceByOpera.java

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

    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.entity.database.DbReportImportLog;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsDataBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsParentGroupBO;
    import cloud.wconnect.workperformance.pojo.bo.database.marketcode.DbPmsMarketCodeStatisticsSubGroupBO;
    import cloud.wconnect.workperformance.service.database.IDbReportService;
    import com.google.common.collect.Lists;
    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;

    /**
     * 解析 Opera Market Code Statistics/Service 报告
     *
     * @author zc
     * @date 2025/12/12
     */
    @Component
    public class DbPmsMarketCodeStatisticsParseServiceByOpera implements IDbPmsMarketCodeStatisticsParseService {

        private final IDbReportService reportService;

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

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

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

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

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return DbPmsMarketCodeStatisticsBO
         * @author zc
         * @date 2025/12/12
         */
        @Override
        public DbPmsMarketCodeStatisticsBO parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            try {
                DbPmsMarketCodeStatisticsDataBO dataBO = convert2Bo(in, roundingMode);

                DbPmsMarketCodeStatisticsBO bo = new DbPmsMarketCodeStatisticsBO();
                LocalDate localDate = DateTimeUtils.strToLocalDate(dateRange.get(0).toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
                bo.setDateStr(localDate.format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD)));
                bo.setData(dataBO);
                return bo;
            } catch (DocumentException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Database parse Market Code Statistics Opera report error", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param in           文件流
         * @param roundingMode 舍入模式
         * @return PmsMarketCodeStatisticsDataBO
         * @author zc
         * @date 2025/12/12
         */
        private DbPmsMarketCodeStatisticsDataBO convert2Bo(InputStream in, RoundingMode roundingMode) throws DocumentException {
            Document document = new SAXReader().read(in);
            Node root = document.selectSingleNode("//STAT_DMY_SEG");
            Element rootElement = (Element) root;

            List<DbPmsMarketCodeStatisticsParentGroupBO> parentGroup = Lists.newArrayList();
            Element listGGrp1 = rootElement.element("LIST_G_GRP1");
            List<Element> gGrp1List = listGGrp1.elements("G_GRP1");
            for (Element gGrp1Element : gGrp1List) {
                List<DbPmsMarketCodeStatisticsSubGroupBO> subGroup = Lists.newArrayList();
                Element listGGrp2 = gGrp1Element.element("LIST_G_GRP2");
                List<Element> gGrp2ElementList = listGGrp2.elements("G_GRP2");
                for (Element gGrp2Element : gGrp2ElementList) {
                    DbPmsMarketCodeStatisticsSubGroupBO subGroupBO = new DbPmsMarketCodeStatisticsSubGroupBO();
                    subGroupBO.setCode(getStrValue(gGrp2Element, "SUB_GRP_CODE_DESC"));
                    subGroupBO.setDesc(getStrValue(gGrp2Element, "DESCRIPTION"));
                    subGroupBO.setRmsDay(formatIntegerValue(getStrValue(gGrp2Element, "ROOMS_DAY")));
                    subGroupBO.setRmsMtd(formatIntegerValue(getStrValue(gGrp2Element, "ROOMS_MTD")));
                    subGroupBO.setRmsYtd(formatIntegerValue(getStrValue(gGrp2Element, "ROOMS_YTD")));

                    subGroupBO.setRmRevDay(formatBigDecimalValue(getStrValue(gGrp2Element, "ROOM_REV_DAY"), roundingMode));
                    subGroupBO.setRmRevMtd(formatBigDecimalValue(getStrValue(gGrp2Element, "ROOM_REV_MTD"), roundingMode));
                    subGroupBO.setRmRevYtd(formatBigDecimalValue(getStrValue(gGrp2Element, "ROOM_REV_YTD"), roundingMode));

                    subGroupBO.setGuestDay(formatIntegerValue(getStrValue(gGrp2Element, "GUEST_DAY")));
                    subGroupBO.setGuestMtd(formatIntegerValue(getStrValue(gGrp2Element, "GUEST_MTD")));
                    subGroupBO.setGuestYtd(formatIntegerValue(getStrValue(gGrp2Element, "GUEST_YTD")));

                    subGroupBO.setAdrDay(formatBigDecimalValue(getStrValue(gGrp2Element, "ADR_DAY"), roundingMode));
                    subGroupBO.setAdrMtd(formatBigDecimalValue(getStrValue(gGrp2Element, "ADR_MTD"), roundingMode));
                    subGroupBO.setAdrYtd(formatBigDecimalValue(getStrValue(gGrp2Element, "ADR_YTD"), roundingMode));

                    subGroupBO.setOccDay(formatBigDecimalValue(getStrValue(gGrp2Element, "PER_OCC_DAY"), roundingMode));
                    subGroupBO.setOccMtd(formatBigDecimalValue(getStrValue(gGrp2Element, "PER_OCC_MTD"), roundingMode));
                    subGroupBO.setOccYtd(formatBigDecimalValue(getStrValue(gGrp2Element, "PER_OCC_YTD"), roundingMode));

                    subGroup.add(subGroupBO);
                }
                DbPmsMarketCodeStatisticsParentGroupBO parentGroupBO = new DbPmsMarketCodeStatisticsParentGroupBO();
                parentGroupBO.setCode(getStrValue(gGrp1Element, "GRP1_CODE_DESC"));
                parentGroupBO.setDesc(getStrValue(gGrp1Element, "MARKET_GROUP_DESCRIPTION"));
                parentGroupBO.setRmsDay(formatIntegerValue(getStrValue(gGrp1Element, "PM_DAY_ROOM")));
                parentGroupBO.setRmsMtd(formatIntegerValue(getStrValue(gGrp1Element, "PM_MONTH_ROOM")));
                parentGroupBO.setRmsYtd(formatIntegerValue(getStrValue(gGrp1Element, "PM_YEAR_ROOM")));

                parentGroupBO.setRmRevDay(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_DAY_CREV"), roundingMode));
                parentGroupBO.setRmRevMtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_MONTH_CREV"), roundingMode));
                parentGroupBO.setRmRevYtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_YEAR_CREV"), roundingMode));

                parentGroupBO.setGuestDay(formatIntegerValue(getStrValue(gGrp1Element, "PM_DAY_PERSON")));
                parentGroupBO.setGuestMtd(formatIntegerValue(getStrValue(gGrp1Element, "PM_MONTH_PERSON")));
                parentGroupBO.setGuestYtd(formatIntegerValue(getStrValue(gGrp1Element, "PM_YEAR_PRS")));

                parentGroupBO.setAdrDay(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_DAY_ARR"), roundingMode));
                parentGroupBO.setAdrMtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_MONTH_ARR"), roundingMode));
                parentGroupBO.setAdrYtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_YEAR_ARR"), roundingMode));

                parentGroupBO.setOccDay(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_DAY_PER_OCC"), roundingMode));
                parentGroupBO.setOccMtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_MTD_PER_OCC"), roundingMode));
                parentGroupBO.setOccYtd(formatBigDecimalValue(getStrValue(gGrp1Element, "PM_YTD_PER_OCC"), roundingMode));
                parentGroupBO.setRateCode(subGroup);

                parentGroup.add(parentGroupBO);
            }
            DbPmsMarketCodeStatisticsDataBO bo = new DbPmsMarketCodeStatisticsDataBO();
            bo.setRmsDay(formatIntegerValue(getStrValue(rootElement, "S_DAY_ROOMS")));
            bo.setRmsMtd(formatIntegerValue(getStrValue(rootElement, "S_MONTH_RMS")));
            bo.setRmsYtd(formatIntegerValue(getStrValue(rootElement, "S_YEAR_RMS")));

            bo.setRmRevDay(formatBigDecimalValue(getStrValue(rootElement, "S_DAY_CREV"), roundingMode));
            bo.setRmRevMtd(formatBigDecimalValue(getStrValue(rootElement, "S_MONTH_CREV"), roundingMode));
            bo.setRmRevYtd(formatBigDecimalValue(getStrValue(rootElement, "S_YEAR_CREV"), roundingMode));

            bo.setGuestDay(formatIntegerValue(getStrValue(rootElement, "S_DAY_PERSONS")));
            bo.setGuestMtd(formatIntegerValue(getStrValue(rootElement, "S_MONTH_PRS")));
            bo.setGuestYtd(formatIntegerValue(getStrValue(rootElement, "S_YEAR_PRS")));

            bo.setAdrDay(formatBigDecimalValue(getStrValue(rootElement, "S_DAY_ARR"), roundingMode));
            bo.setAdrMtd(formatBigDecimalValue(getStrValue(rootElement, "S_MONTH_ARR"), roundingMode));
            bo.setAdrYtd(formatBigDecimalValue(getStrValue(rootElement, "S_YEAR_ARR"), roundingMode));

            bo.setOccDay(formatBigDecimalValue(getStrValue(rootElement, "S_DAY_PER_OCC"), roundingMode));
            bo.setOccMtd(formatBigDecimalValue(getStrValue(rootElement, "S_MTD_PER_OCC"), roundingMode));
            bo.setOccYtd(formatBigDecimalValue(getStrValue(rootElement, "S_YTD_PER_OCC"), roundingMode));
            bo.setMarketCode(parentGroup);
            return bo;
        }

        /**
         * Element 提取 String 值
         *
         * @param element 元素
         * @param name    名称
         * @return String
         * @author zc
         * @date 2025/12/13
         */
        private String getStrValue(Element element, String name) {
            return element.element(name).getTextTrim();
        }

        /**
         * 格式化 Integer
         *
         * @param value 值
         * @return Integer
         * @author zc
         * @date 2025/12/13
         */
        private Integer formatIntegerValue(String value) {
            return value == null ? 0 : Integer.parseInt(value);
        }

        /**
         * 格式化 BigDecimal
         *
         * @param value        值
         * @param roundingMode 舍入模式
         * @return BigDecimal
         * @author zc
         * @date 2025/12/13
         */
        private BigDecimal formatBigDecimalValue(String value, RoundingMode roundingMode) {
            return value == null ? BigDecimal.ZERO : new BigDecimal(value)
                    .setScale(BaseConstant.DATA_PRECISION, roundingMode);
        }

    }