package com.bcxin.identify.util.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.bcxin.identify.util.sys.ConfigUtil;
import com.google.common.io.Files;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class BcxinFileUtil {

	/**
	 * 获取网络文件大小
	 */
	public static long getFileLength(String downloadUrl){
		if (downloadUrl == null || "".equals(downloadUrl)){
			return 0L ;
		}
		long length = 0;
		if (downloadUrl.contains("oss") || downloadUrl.contains("obs")) {
			HttpURLConnection conn = null;
			try {
				URL url = new URL(downloadUrl);
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("HEAD");
				conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
				length = conn.getContentLength();
			} catch (IOException e) {
				length = 0L;
			} finally {
				conn.disconnect();
			}
		}

		if (length > 0) {
			return length;
		}

		String randomName = UUID.randomUUID().toString();
		String fileName = randomName + "." + Files.getFileExtension(downloadUrl);
		FileUtil.mkdir(ConfigUtil.getValue("material_path"));
		File localFile = new File(ConfigUtil.getValue("material_path") + fileName);
		HttpUtil.downloadFile(downloadUrl,localFile);
		return localFile.length();
	}

	/**
	 * 通过文件url生成base64字符串
	 *
	 * @param imgURL
	 * @return
	 * @auth llc
	 * @date 2019-04-17
	 */
	public static String getInputStreamByUrl(String imgURL) {
		ByteArrayOutputStream outPut = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		try {
			// 创建URL
			URL url = new URL(imgURL);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10 * 1000);

			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				//连接失败/链接失效/图片不存在
				return "fail";
			}
			/* jdk7自动关闭流 */
			try (InputStream inStream = conn.getInputStream();) {
				int len = -1;
				while ((len = inStream.read(data)) != -1) {
					outPut.write(data, 0, len);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(outPut.toByteArray());
	}

	/**
	 * 字节转base64
	 * @param bt
	 * @return
	 */
	public static String byteToBase64(byte[] bt) {
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bt);
	}

	/**
	 * 获取文件名后缀名
	 * @param fileName
	 * @return
	 */
	public static String getFileExtension(String fileName) {
		if (!fileName.isEmpty()) {
			return fileName.substring(fileName.lastIndexOf(".")+1);
		}
		return null;
	}
}
