package org.dromara.zhishu.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageUtils {

    private static final String CACHE_DIR = System.getProperty("java.io.tmpdir"); // 获取系统缓存目录
    private static final String IMAGE_PATH = CACHE_DIR + File.separator; // 图片完整路径

    /**
     * 生成图片并保存到缓存文件夹
     *
     * @param text   要显示的字符串
     * @param width  图片宽度
     * @param height 图片高度
     * @param fileName 文件名称  例如 123.jpg
     */
    public static String generateImage(String text, int width, int height,String fileName) {
        // 创建一个白底的BufferedImage
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 设置字体和颜色
        Font font = new Font("Alibaba PuHuiTi", Font.BOLD, 40);
        g2d.setFont(font);
        g2d.setColor(Color.BLACK);

        // 计算字符串的宽度和高度
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int textHeight = fm.getHeight();

        // 计算字符串的绘制位置
        int x = (width - textWidth) / 2;
        int y = (height - textHeight) / 2 + fm.getAscent();

        // 绘制字符串
        g2d.drawString(text, x, y);

        // 释放资源
        g2d.dispose();

        // 保存图片到缓存文件夹
        try {
            File outputFile = new File(IMAGE_PATH+fileName);
            ImageIO.write(image, "jpg", outputFile);
            return IMAGE_PATH+fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static boolean isImageExists(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param absolutePath 文件的绝对路径
     * @return 如果文件存在返回 true，否则返回 false
     */
    public static boolean isFileExists(String absolutePath) {
        Path path = Paths.get(absolutePath);
        return Files.exists(path);
    }

    public static boolean isImageExistsWithGet(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("User-Agent", "Java Client");

            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 生成图片，左上开头
     * @param text
     * @param width
     * @param height
     * @param fileName
     * @return
     */
    public static String generateMultiLineImage(String text, int width,int height, String fileName) {
        String[] lines = text.split("\n");

        // 设置字体样式
        Font font = new Font("Alibaba PuHuiTi", Font.BOLD, 20);

        // 创建临时图像用于计算字体大小
        BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2dTemp = tempImage.createGraphics();
        g2dTemp.setFont(font);
        FontMetrics fm = g2dTemp.getFontMetrics();
        int lineHeight = fm.getHeight();
        int ascent = fm.getAscent();
        g2dTemp.dispose();

        // 创建实际图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setFont(font);
        g2d.setColor(Color.BLACK);

        // 绘制文本
        int y = 10 + ascent;
        int lineCount = 0;

        for (String line : lines) {
            if (y + lineHeight > height) {
                // 如果超出高度，则画 ...
                if (lineCount == 0) {
                    // 整段都放不下，尝试截断
                    String truncated = ContentUtils.truncateLineToFit(line, width, fm, "...");
                    g2d.drawString(truncated, 10, y);
                } else {
                    g2d.drawString("...", 10, y);
                }
                break;
            }

            g2d.drawString(line, 10, y);
            y += lineHeight + 5; // 每行间距 5px
            lineCount++;
        }

        g2d.dispose();

        // 保存图片到缓存文件夹
        try {
            File outputFile = new File(IMAGE_PATH+fileName);
            ImageIO.write(image, "jpg", outputFile);
            return IMAGE_PATH+fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
