package com.ruoyi.project.zjsgfa.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class ImageProcessUtil {
    private static final Logger logger = LoggerFactory.getLogger(ImageProcessUtil.class);

    /**
     * 从完整Base64字符串中提取并解码SVG内容
     */
    public static String extractSvgFromBase64(String fullBase64) {
        if (fullBase64 == null || !fullBase64.startsWith("data:image/svg+xml")) {
            logger.error("无效的SVG Base64格式");
            return null;
        }

        try {
            // 移除前缀（兼容带charset的格式）
            String base64Content = fullBase64.replaceAll("^data:image/svg\\+xml;.*?base64,", "");
            
            // 验证Base64格式
            if (!Base64.isBase64(base64Content)) {
                logger.error("Base64字符串格式无效");
                return null;
            }
            
            // 解码为SVG字符串
            byte[] svgBytes = Base64.decodeBase64(base64Content);
            return new String(svgBytes, "UTF-8");
        } catch (Exception e) {
            logger.error("提取SVG内容失败", e);
            return null;
        }
    }

    /**
     * 将SVG字符串转换为PNG输入流（确保字节流有效）
     */
    public static InputStream convertSvgToPng(String svgContent) {
        if (svgContent == null || svgContent.trim().isEmpty()) {
            logger.error("SVG内容为空");
            return null;
        }

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 初始化Batik转换器
            PNGTranscoder transcoder = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(
                new ByteArrayInputStream(svgContent.getBytes("UTF-8"))
            );
            TranscoderOutput output = new TranscoderOutput(outputStream);

            // 执行转换
            transcoder.transcode(input, output);
            outputStream.flush();

            // 验证转换结果
            byte[] pngBytes = outputStream.toByteArray();
            if (pngBytes.length == 0) {
                logger.error("转换后的PNG字节流为空");
                return null;
            }

            return new ByteArrayInputStream(pngBytes);
        } catch (TranscoderException e) {
            logger.error("SVG转换PNG失败（可能包含不支持的元素）", e);
            return null;
        } catch (Exception e) {
            logger.error("PNG流处理失败", e);
            return null;
        }
    }
}
    