package com.backendsys.utils;

import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Value;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ResourceUtil {

    /**
     * 获取远程图片的宽高 (注意使用频率，可能会使内存激增)
     */
    public static Dimension getRemoteImageSize(String imageUrl) throws IOException {

        // 检查 imageUrl 是否为空或无效
        if (imageUrl == null || imageUrl.trim().isEmpty()) {
            return null;
        }

        URL url = new URL(imageUrl);
        BufferedImage image = ImageIO.read(url);
        int width = image.getWidth();
        int height = image.getHeight();
        return new Dimension(width, height);
    }


    /**
     * 判断网络图片是否存在
     * imgUrl 图片地址链接
     */
    public static Boolean checkImageValid(String imgUrl) {
        Integer RESPONSE_CODE = 0;
        String CONTENT_TYPE = "";

        try {
            URL url = new URL(imgUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            RESPONSE_CODE = connection.getResponseCode();
            CONTENT_TYPE = connection.getHeaderField("Content-Type");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("远程资源异常: " + imgUrl);
        }

        if (RESPONSE_CODE == HttpURLConnection.HTTP_OK && CONTENT_TYPE != null && CONTENT_TYPE.startsWith("image")) {
//            System.out.println("posted ok!");
            return true;
        } else {
//            System.out.println("Bad post...");
            throw new RuntimeException("远程资源异常: " + imgUrl);
        }
    }

    /**
     * 下载图片到本地，并返回本地图片的路径
     * (在使用 Docker 部署的情况下，下载路径也应该定义为容器与镜像互相映射的对应路径)
     */
    public static String downloadImage(String remoteUrl, String uploadDirectory) {

        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String fileName = remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1);
        // 去掉文件名中(?)后面的查询字符串
        if (fileName.contains("?")) {
            fileName = fileName.substring(0, fileName.indexOf("?"));
        }

        String localDir = "/" + dateDir; // 修改为相对路径，避免跨平台路径分隔符问题
        String localPath = localDir  + "/" + fileName; // "/"   // File.separator +

        try {
            // 使用 Hutool 工具类下载远程图片
            byte[] imageData = HttpUtil.downloadBytes(remoteUrl);

            // 创建本地目录
            Files.createDirectories(Paths.get(uploadDirectory + localDir));

            // 将下载的图片数据保存到本地文件
            Path filePath = Paths.get(uploadDirectory + localPath);

            Files.write(filePath, imageData);

        } catch (IOException e) {
            e.printStackTrace(); // 也可以选择抛出异常供调用者处理
            return null; // 或者其他错误处理逻辑
        }

        // 返回当前本地图片的路径
        return "/uploads" + localPath;
    }

    /**
     * 判断 URL 文件后缀类型
     * ResourceUtil.checkUrlSuffix("http://../d.png", new String[]{"jpg", "png"})
     */
    public static boolean checkUrlSuffix(String urlString, String[] allowedExtensions) {
        try {
            URL url = new URL(urlString);
            String path = url.getPath();
            if (path != null && !path.isEmpty()) {
                String[] parts = path.split("\\.");
                if (parts.length > 1) {
                    String extension = parts[parts.length - 1].toLowerCase(); // 转换为小写;
                    List<String> allowedExtensionList = Arrays.asList(allowedExtensions);
                    return allowedExtensionList.contains(extension);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
