package com.zjsgfa.framework.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RichTextProcessor {

    // 匹配img标签的正则表达式
    private static final Pattern IMG_TAG_PATTERN = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");

    // 处理富文本，压缩其中的图片
    public static String processRichText(String richText, float quality, int maxWidth, int maxHeight) {
        if (richText == null || richText.isEmpty()) {
            return richText;
        }

        Matcher matcher = IMG_TAG_PATTERN.matcher(richText);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String imgTag = matcher.group(0);
            String src = matcher.group(1);

            // 只处理Base64图片
            if (src.startsWith("data:image/")) {
                String compressedSrc = ImageCompressor.compressBase64Image(src, quality, maxWidth, maxHeight);
                String compressedImgTag = imgTag.replace(src, compressedSrc);
                matcher.appendReplacement(sb, compressedImgTag);
            }
        }

        matcher.appendTail(sb);
        return sb.toString();
    }

}
