package com.ruoyi.common.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

import com.ruoyi.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 缩略图处理工具类（仅处理图片）
 *
 * @author ruoyi
 */
public class ThumbnailUtils
{
    private static final Logger log = LoggerFactory.getLogger(ThumbnailUtils.class);

    /**
     * 默认缩略图宽度
     */
    private static final int DEFAULT_THUMBNAIL_WIDTH = 200;

    /**
     * 默认缩略图高度
     */
    private static final int DEFAULT_THUMBNAIL_HEIGHT = 200;

    /**
     * 生成缩略图
     *
     * @param file 原始文件
     * @return 缩略图文件路径，如果生成失败返回null
     */
    public static String generateThumbnail(MultipartFile file)
    {
        try
        {
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            if (originalImage == null)
            {
                log.warn("无法读取图片文件: {}", file.getOriginalFilename());
                return null;
            }

            return generateThumbnail(originalImage, file.getOriginalFilename(), DEFAULT_THUMBNAIL_WIDTH, DEFAULT_THUMBNAIL_HEIGHT);
        }
        catch (IOException e)
        {
            log.error("生成缩略图失败", e);
            return null;
        }
    }

    /**
     * 生成缩略图
     *
     * @param file 原始文件
     * @param width 缩略图宽度
     * @param height 缩略图高度
     * @return 缩略图文件路径，如果生成失败返回null
     */
    public static String generateThumbnail(MultipartFile file, int width, int height)
    {
        try
        {
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            if (originalImage == null)
            {
                log.warn("无法读取图片文件: {}", file.getOriginalFilename());
                return null;
            }

            return generateThumbnail(originalImage, file.getOriginalFilename(), width, height);
        }
        catch (IOException e)
        {
            log.error("生成缩略图失败", e);
            return null;
        }
    }

    /**
     * 生成缩略图
     *
     * @param imagePath 原始图片路径
     * @return 缩略图文件路径，如果生成失败返回null
     */
    public static String generateThumbnail(String imagePath)
    {
        try
        {
            File imageFile = new File(imagePath);
            if (!imageFile.exists())
            {
                log.warn("图片文件不存在: {}", imagePath);
                return null;
            }

            BufferedImage originalImage = ImageIO.read(imageFile);
            if (originalImage == null)
            {
                log.warn("无法读取图片文件: {}", imagePath);
                return null;
            }

            String fileName = imageFile.getName();
            return generateThumbnail(originalImage, fileName, DEFAULT_THUMBNAIL_WIDTH, DEFAULT_THUMBNAIL_HEIGHT);
        }
        catch (IOException e)
        {
            log.error("生成缩略图失败: {}", imagePath, e);
            return null;
        }
    }

    /**
     * 生成缩略图（内部方法）
     */
    private static String generateThumbnail(BufferedImage originalImage, String originalFileName, int width, int height)
    {
        try
        {
            int originalWidth = originalImage.getWidth();
            int originalHeight = originalImage.getHeight();

            // 计算缩放比例，保持宽高比
            double scale = Math.min((double) width / originalWidth, (double) height / originalHeight);
            int scaledWidth = (int) (originalWidth * scale);
            int scaledHeight = (int) (originalHeight * scale);

            // 创建缩略图
            BufferedImage thumbnail = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbnail.createGraphics();

            // 设置图片平滑渲染
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION,
                    java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(originalImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH), 0, 0, null);
            g2d.dispose();

            // 生成缩略图文件名
            String extension = getFileExtension(originalFileName);
            String thumbnailFileName = "thumb_" + IdUtils.fastSimpleUUID() + "." + extension;
            String datePath = DateUtils.datePath();
            String thumbnailPath = datePath + "/" + thumbnailFileName;

            // 保存缩略图
            String uploadDir = RuoYiConfig.getUploadPath();
            File thumbnailFile = FileUploadUtils.getAbsoluteFile(uploadDir, thumbnailPath);
            ImageIO.write(thumbnail, extension, thumbnailFile);

            // 返回访问路径
            return FileUploadUtils.getPathFileName(uploadDir, thumbnailPath);
        }
        catch (Exception e)
        {
            log.error("生成缩略图失败", e);
            return null;
        }
    }

    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String fileName)
    {
        if (StringUtils.isEmpty(fileName))
        {
            return "jpg";
        }
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1)
        {
            return fileName.substring(lastDotIndex + 1).toLowerCase();
        }
        return "jpg";
    }
}
