package org.springblade.api.utils;

import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Slf4j
public class FileUtils {

	public static File getFileByUrl(String fileUrl, String suffix){
		try {
			// 从URL获取文件内容
			URL url = new URL(fileUrl);
			URLConnection urlConnection = url.openConnection();
			HttpsURLConnection https = (HttpsURLConnection) urlConnection;
			trustAllHosts(https);
			https.setHostnameVerifier(DO_NOT_VERIFY);

			// 创建一个临时文件
			File tempFile = File.createTempFile("tempfile", suffix);
			try (InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
				 OutputStream outputStream = Files.newOutputStream(tempFile.toPath())) {

				// 复制文件内容到临时文件
				byte[] buffer = new byte[4096];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}
				return tempFile;
			}

		} catch (IOException e) {
			log.error("文件上传异常",e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 覆盖java默认的证书验证
	 */
	private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return new java.security.cert.X509Certificate[]{};
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		}
	}};

	/**
	 * 设置不验证主机
	 */
	private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	/**
	 * 信任所有
	 * @param connection
	 * @return
	 */
	private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
		SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			SSLSocketFactory newFactory = sc.getSocketFactory();
			connection.setSSLSocketFactory(newFactory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oldFactory;
	}

	public static void main(String[] args) {
		System.out.println(getFileByUrl("https://ai.my-123.cn/pic/product-line/upload/20240714/902fde34b3811d3bfbab1ed3487fd0b8.jpg", ".jpg"));
	}
}
