# DbPmsManagerFlashParseServiceByOpera.java

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

    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.managerflash.DbPmsManagerFlashBO;
    import cloud.wconnect.workperformance.pojo.bo.database.managerflash.DbPmsManagerFlashItemBO;
    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.time.format.DateTimeFormatter;
    import java.util.List;
    import java.util.Objects;

    /**
     * 解析 Opera Manager Flash/Service 报告
     *
     * @author zc
     * @date 2025/12/02
     */
    @Component
    public class DbPmsManagerFlashParseServiceByOpera implements IDbPmsManagerFlashParseService {

        private final IDbReportService reportService;

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

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

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

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

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

        /**
         * 解析报告
         *
         * @param propertyDTO 资产
         * @param in          报告文件流
         * @param dateRange   数据日期范围（yyyyMMdd）
         * @return DbPmsManagerFlashBO
         * @author zc
         * @date 2025/12/02
         */
        @Override
        public DbPmsManagerFlashBO parse(PropertyDTO propertyDTO, InputStream in, List<Long> dateRange) throws ParseReportException {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());
            List<DbPmsManagerFlashItemBO> boList = Lists.newArrayList();
            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_MASTER_VALUE");
                for (Node node : nodes) {
                    Element dataElement = (Element) node;

                    DbPmsManagerFlashItemBO itemBO = convert2Bo(dataElement, roundingMode);
                    // 跳过描述是空且数值都是 null 的数据
                    if (StringUtils.isBlank(itemBO.getDesc()) && Objects.isNull(itemBO.getDay())
                            && Objects.isNull(itemBO.getMtd()) && Objects.isNull(itemBO.getYtd())) {
                        continue;
                    }
                    boList.add(itemBO);
                }

                DbPmsManagerFlashBO bo = new DbPmsManagerFlashBO();
                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(boList);
                return bo;
            } catch (DocumentException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Database parse Manager Flash Opera report error", e);
            }
        }

        /**
         * 转换为 BO
         *
         * @param dataElement  数据元素
         * @param roundingMode 舍入模式
         * @return DbPmsManagerFlashItemBO
         * @author zc
         * @date 2025/12/02
         */
        private DbPmsManagerFlashItemBO convert2Bo(Element dataElement, RoundingMode roundingMode) {
            Element listGHeading1Order = dataElement.element("LIST_G_HEADING_1_ORDER");
            List<Element> gHeading1OrderElementList = listGHeading1Order.elements("G_HEADING_1_ORDER");

            DbPmsManagerFlashItemBO itemBO = new DbPmsManagerFlashItemBO();
            String description = dataElement.element("DESCRIPTION").getTextTrim();
            itemBO.setDesc(description);
            for (Element gHeading1OrderElement : gHeading1OrderElementList) {
                Element listGSumAmount = gHeading1OrderElement.element("LIST_G_SUM_AMOUNT");
                Element gSumAmount = listGSumAmount.element("G_SUM_AMOUNT");
                if (Objects.isNull(gSumAmount)) {
                    break;
                }
                Element sumAmount = gSumAmount.element("SUM_AMOUNT");
                if (Objects.isNull(sumAmount)) {
                    break;
                }
                String sumAmountStr = sumAmount.getTextTrim();
                BigDecimal arrivalRooms = StringUtils.isBlank(sumAmountStr) ? null :
                        new BigDecimal(sumAmountStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);

                String heading2Str = gHeading1OrderElement.element("HEADING_2").getTextTrim();
                if ("DAY".equalsIgnoreCase(heading2Str)) {
                    itemBO.setDay(arrivalRooms);
                } else if ("MONTH".equalsIgnoreCase(heading2Str)) {
                    itemBO.setMtd(arrivalRooms);
                } else if ("YEAR".equalsIgnoreCase(heading2Str)) {
                    itemBO.setYtd(arrivalRooms);
                }
            }
            return itemBO;
        }
    }