# 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.EventBodyParamEnum;
    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.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    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.AmazonS3Service;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import jakarta.annotation.Resource;
    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.Qualifier;
    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.HashMap;
    import java.util.List;
    import java.util.Objects;

    /**
     * 解析 Opera Manager Flash/Service 报告
     *
     * @author zc
     * @date 2025/12/02
     */
    @Component
    public class DbPmsManagerFlashParseServiceByOpera implements IDbPmsManagerFlashParseService {
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @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) {
            try {
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());

                // 上传报告到 S3 服务器，用于事件监听解析报告
                amazonS3Service.uploadFile(file, key);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), List.of(propertyDTO.getAbbr()));
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.DATABASE.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), importLog.getId());
                parameter.put(EventBodyParamEnum.BUSINESS_DATE.getDesc(), importLog.getBusinessDate());
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), importLog.getStartDate());
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), importLog.getEndDate());

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.MANAGER_FLASH_SERVICE_MTD_YESTERDAY.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Database Manager Flash Opera report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @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;
        }
    }