package com.ruoyi.web.controller.common;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Builder;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 右下角水印工具类
 */
public class BottomRightWatermarkUtil {
    
    /**
     * 添加右下角文字水印（基本版）
//     */
//    public static MultipartFile addBottomRightWatermark(
//            MultipartFile originalFile,
//            String watermarkText) throws IOException {
//
//        return addBottomRightWatermark(
//            originalFile,
//            watermarkText,
//            BottomRightWatermarkConfig.defaultConfig()
//        );
//    }
    
    /**
     * 添加右下角文字水印（完整配置）
     */
//    public static MultipartFile addBottomRightWatermark(
//            MultipartFile originalFile,
//            String watermarkText,
//            BottomRightWatermarkConfig config) throws IOException {
//
//        // 读取图片
//        BufferedImage image = ImageIO.read(originalFile.getInputStream());
//        if (image == null) {
//            throw new IllegalArgumentException("无法读取图片文件");
//        }
//
//        // 添加右下角水印
//        image = addMultiLineBottomRightWatermark(image, watermarkText, config);
//
//        // 转换为 MultipartFile
//        return convertToMultipartFile(image, originalFile);
//    }


    
    /**
     * 多行右下角水印
     */
    public static BufferedImage addMultiLineBottomRightWatermark(
            BufferedImage image,
            String[] watermarkLines,
            BottomRightWatermarkConfig config) {
        
        Graphics2D g2d = image.createGraphics();

        // 设置字体和颜色
        Font font = new Font(config.getFontName(), config.getFontStyle(), image.getHeight() / 15 );
        g2d.setFont(font);
        g2d.setColor(config.getColor());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, config.getOpacity()));
        
        // 计算每行文字尺寸
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int lineHeight = fontMetrics.getHeight();
        int totalHeight = lineHeight * watermarkLines.length;
        
        // 计算最大行宽
        int maxWidth = 0;
        for (String line : watermarkLines) {
            int lineWidth = fontMetrics.stringWidth(line);
            if (lineWidth > maxWidth) {
                maxWidth = lineWidth;
            }
        }
        
        // 从右下角开始绘制（从下往上）
        int startY = image.getHeight() - config.getMarginY();
        
        for (int i = watermarkLines.length - 1; i >= 0; i--) {
            String line = watermarkLines[i];
            int lineWidth = fontMetrics.stringWidth(line);
            int x = image.getWidth() - lineWidth - config.getMarginX();
            int y = startY - (watermarkLines.length - 1 - i) * lineHeight;
            
            // 添加背景（可选）
            if (config.isWithBackground()) {
                Color originalColor = g2d.getColor();
                g2d.setColor(config.getBackgroundColor());
                int padding = config.getBackgroundPadding();
                g2d.fillRect(x - padding, y - lineHeight + padding, 
                           lineWidth + padding * 2, lineHeight);
                g2d.setColor(originalColor);
            }
            
            g2d.drawString(line, x, y);
        }
        
        g2d.dispose();
        return image;
    }
    

    
    /**
     * 带 Logo 图标的右下角水印
     */
    public static MultipartFile addLogoTextWatermark(
            MultipartFile originalFile,
            MultipartFile logoFile,
            String watermarkText) throws IOException {
        
        BufferedImage image = ImageIO.read(originalFile.getInputStream());
        BufferedImage logo = ImageIO.read(logoFile.getInputStream());
        
        Graphics2D g2d = image.createGraphics();
        
        // 配置
        BottomRightWatermarkConfig config = BottomRightWatermarkConfig.defaultConfig();
        Font font = new Font(config.getFontName(), config.getFontStyle(), config.getFontSize());
        g2d.setFont(font);
        g2d.setColor(config.getColor());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, config.getOpacity()));
        
        // 计算文字尺寸
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(watermarkText);
        int textHeight = fontMetrics.getHeight();
        
        // 调整 Logo 大小
        int logoSize = textHeight;
        BufferedImage resizedLogo = resizeImage(logo, logoSize, logoSize);
        
        // 计算位置（Logo + 文字）
        int totalWidth = logoSize + 5 + textWidth; // 5px 间距
        int x = image.getWidth() - totalWidth - config.getMarginX();
        int y = image.getHeight() - config.getMarginY();
        
        // 绘制 Logo
        g2d.drawImage(resizedLogo, x, y - logoSize + 5, null);
        
        // 绘制文字
        g2d.drawString(watermarkText, x + logoSize + 5, y);
        
        g2d.dispose();
        
        return convertToMultipartFile(image, originalFile);
    }
    
    /**
     * 旋转角度的右下角水印（倾斜效果）
     */
    public static MultipartFile addRotatedWatermark(
            MultipartFile originalFile,
            String watermarkText,
            double angle) throws IOException {
        
        BufferedImage image = ImageIO.read(originalFile.getInputStream());
        
        Graphics2D g2d = image.createGraphics();
        
        // 配置
        BottomRightWatermarkConfig config = BottomRightWatermarkConfig.defaultConfig();
        Font font = new Font(config.getFontName(), config.getFontStyle(), config.getFontSize());
        g2d.setFont(font);
        g2d.setColor(config.getColor());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, config.getOpacity()));
        
        // 计算文字尺寸
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(watermarkText);
        int textHeight = fontMetrics.getHeight();
        
        // 计算旋转后的位置
        int x = image.getWidth() - textWidth - config.getMarginX();
        int y = image.getHeight() - config.getMarginY();
        
        // 旋转 Graphics2D
        g2d.rotate(Math.toRadians(angle), x + textWidth / 2, y - textHeight / 2);
        
        // 绘制水印
        g2d.drawString(watermarkText, x, y);
        
        g2d.dispose();
        
        return convertToMultipartFile(image, originalFile);
    }
    

    /**
     * 缩放图片
     */
    private static BufferedImage resizeImage(BufferedImage originalImage, 
                                            int targetWidth, int targetHeight) {
        
        BufferedImage resizedImage = new BufferedImage(
            targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
        g2d.dispose();
        
        return resizedImage;
    }
    
    /**
     * 转换为 MultipartFile
     */
    private static MultipartFile convertToMultipartFile(
            BufferedImage image, 
            MultipartFile originalFile) throws IOException {
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        // 获取原文件扩展名
        String originalFilename = originalFile.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        String formatName = getFormatName(extension);
        
        // 写入图片
        ImageIO.write(image, formatName, baos);
        
        // 创建内存 MultipartFile
        return new InMemoryMultipartFile(
            originalFile.getName(),
            originalFilename,
            originalFile.getContentType(),
            baos.toByteArray()
        );
    }
    
    private static String getFileExtension(String filename) {
        if (StrUtil.isBlank(filename) || !filename.contains(".")) {
            return "jpg";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }
    
    private static String getFormatName(String extension) {
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "JPEG";
            case "png":
                return "PNG";
            case "gif":
                return "GIF";
            case "bmp":
                return "BMP";
            default:
                return "JPEG";
        }
    }
    
    /**
     * 右下角水印配置类
     */
    @Data
    @Builder
    public static class BottomRightWatermarkConfig {
        @Builder.Default
        private Color color = Color.WHITE;
        
        @Builder.Default
        private String fontName = "WenQuanYi Zen Hei";
        
        @Builder.Default
        private int fontStyle = Font.BOLD;
        
        @Builder.Default
        private int fontSize = 24;
        
        @Builder.Default
        private float opacity = 0.7f;
        
        @Builder.Default
        private int marginX = 10;  // 右边距
        
        @Builder.Default
        private int marginY = 10;  // 下边距
        
        @Builder.Default
        private boolean withBackground = false;
        
        private Color backgroundColor;
        
        @Builder.Default
        private int backgroundPadding = 5;
        
        @Builder.Default
        private boolean roundedBackground = false;
        
        @Builder.Default
        private int backgroundRadius = 5;
        
        @Builder.Default
        private boolean withShadow = false;
        
        @Builder.Default
        private Color shadowColor = Color.BLACK;
        
        @Builder.Default
        private float shadowOpacity = 0.5f;
        
        @Builder.Default
        private int shadowOffset = 2;
        
        public static BottomRightWatermarkConfig defaultConfig() {
            return BottomRightWatermarkConfig.builder().build();
        }
        
        public static BottomRightWatermarkConfig withBackgroundConfig() {
            return BottomRightWatermarkConfig.builder()
                .withBackground(true)
                .backgroundColor(new Color(0, 0, 0, 100))
                .build();
        }
        
        public static BottomRightWatermarkConfig withShadowConfig() {
            return BottomRightWatermarkConfig.builder()
                .withShadow(true)
                .color(Color.WHITE)
                .shadowColor(Color.BLACK)
                .build();
        }
        
        public static BottomRightWatermarkConfig subtleConfig() {
            return BottomRightWatermarkConfig.builder()
                .color(new Color(255, 255, 255, 180)) // 半透明白色
                .fontSize(18)
                .opacity(0.5f)
                .marginX(15)
                .marginY(15)
                .build();
        }
    }
}