package com.czg.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;

/**
 * @author yjjie
 * @date 2026/1/4 13:58
 */
@Slf4j
public class UploadFileUtil {

    // 匹配常见的图片扩展名
    private static final Pattern PATTERN = Pattern.compile("\\.(jpg|jpeg|png|gif|bmp|webp|svg|ico)(?:[\\?#]|$)", Pattern.CASE_INSENSITIVE);

    /**
     * 使用正则表达式提取图片后缀
     */
    public static String extractImageExtension(String imageUrl) {
        java.util.regex.Matcher matcher = PATTERN.matcher(imageUrl);

        if (matcher.find()) {
            String extension = matcher.group(1).toLowerCase();
            // 处理jpeg的情况
            return "jpeg".equals(extension) ? "jpg" : extension;
        }
        // 默认后缀
        return "png";
    }

    /**
     * 根据图片URL获取图片文件
     *
     * @param url 图片URL
     * @return 图片文件
     */
    public static File getFileByUrl(String url) throws IOException {
        byte[] bytes = downloadImage(url);

        Path tempFile = Files.createTempFile("image_", "." + extractImageExtension(url));
        Files.write(tempFile, bytes);

        return tempFile.toFile();
    }

    /**
     * 下载图片
     * @param url 图片地址
     * @return 图片字节数组
     */
    public static byte[] downloadImage(String url) {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();

        try {
            HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());

            if (response.statusCode() != 200) {
                throw new RuntimeException("Failed to download image, status code: " + response.statusCode());
            }

            return response.body();
        } catch (Exception e) {
            log.error("Failed to download image: {}", e.getMessage());
            return new byte[0];
        }
    }

    /**
     * 从URL中提取文件名
     *
     * @param url 图片URL
     * @return 提取的文件名，失败则返回默认名
     */
    public static String extractFileNameFromUrl(String url) {
        try {
            if (url.contains("/")) {
                String fileName = url.substring(url.lastIndexOf("/") + 1);
                // 如果文件名包含参数，截取?之前的部分
                if (fileName.contains("?")) {
                    fileName = fileName.substring(0, fileName.indexOf("?"));
                }
                // 如果提取的文件名有效，直接返回
                if (fileName.contains(".")) {
                    return fileName;
                }
            }
        } catch (Exception e) {
            log.warn("提取文件名失败，使用默认文件名", e);
        }
        // 默认文件名
        return "upload_" + System.currentTimeMillis() + ".png";
    }
}
