package com.ruoyi.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import java.io.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class QiniuUploadUtil {

	//设置账号的ACCESS_KEY和SECRET_KEY密钥配置
	static String ACCESS_KEY = "A3MK35bMQiqNeik5Cvv7v6huki8r6S8ISO1c9iM2";
	static String SECRET_KEY = "FqDnpJXCifV5sHCWZnj_tqVxXDS3wfnPZT152yB0";
	static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	static String bucketname = "cf-img";

	public static String putInputStream(InputStream in,String name){
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = name;
		try {
			String upToken = auth.uploadToken(bucketname);
		    Response response = uploadManager.put(in,key,upToken,null, null);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		    System.out.println(putRet.toString());
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		    	
		    }
		}
		return "http://fileimg.makalu.cc/"+name;	
	}


	/**
	 * base64图片上传
	 * @param file64  base64
	 * @param name    文件名称
	 * @throws Exception
	 * "http://upload.qiniup.com/putb64/"华东空间上传域名
	 * "http://upload-z1.qiniu.com/putb64/"华北空间上传域名
	 * "http://upload-z2.qiniu.com/putb64/"华南空间上传域名
	 * "http://upload-na0.qiniu.com/putb64/"北美空间上传域名
	 *  @return
	 *   code 上传状态（200上传成功）
	 *   url  上传地址（code为200，才有url地址）
	 */
	public static String put64image(String file64,String name) throws Exception {

		if(file64.contains(",")){
			file64 = file64.substring(file64.indexOf(",")+1,file64.length());
		}

		String upToken = auth.uploadToken(bucketname);
		//-1代表自动获取长度（非华东空间需要修改上传域名）
		String url = "http://upload.qiniup.com/putb64/"+ -1 +"/key/"+ UrlSafeBase64.encodeToString(name);
		RequestBody rb = RequestBody.create(null, file64);
		Request request = new Request.Builder().
				url(url).
				addHeader("Content-Type", "application/octet-stream")
				.addHeader("Authorization", "UpToken " + upToken)
				.post(rb).build();
		OkHttpClient client = new OkHttpClient.Builder()
				.readTimeout(240, TimeUnit.SECONDS)//设置读取超时时间
				.writeTimeout(120,TimeUnit.SECONDS)//设置写的超时时间
				.connectTimeout(120,TimeUnit.SECONDS)//设置连接超时时间
				.build();
		Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);
		okhttp3.Response response = client.newCall(request).execute();
		String code = response.toString().substring(response.toString().indexOf("code=")+5,response.toString().indexOf(", message"));
		String message = response.toString().substring(response.toString().indexOf("message=")+8,response.toString().indexOf(", url"));
		System.out.println(code+"==================="+message);
		String path = "";
		if(code.equals("200")){
			path =  "http://fileimg.makalu.cc/"+name;
		}
		response.body().close();
		return path;

	}


	/**
	 * 通过发送http get 请求获取文件资源
	 * @param url
	 * @param filepath
	 * @return
	 */
	private static void download(String url, String filepath) {
		OkHttpClient client = new OkHttpClient();
		Request req = new Request.Builder().url(url).build();
		okhttp3.Response resp = null;
		try {
			resp = client.newCall(req).execute();
			if(resp.isSuccessful()) {
				ResponseBody body = resp.body();
				InputStream is = body.byteStream();
				byte[] data = readInputStream(is);
				File imgFile = new File(filepath);          //下载到本地的图片命名
				FileOutputStream fops = new FileOutputStream(imgFile);
				fops.write(data);
				fops.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Unexpected code " + resp);
		}
	}

	/**
	 * 读取字节输入流内容
	 * @param is
	 * @return
	 */
	public  static byte[] readInputStream(InputStream is) {
		ByteArrayOutputStream writer = new ByteArrayOutputStream();
		byte[] buff = new byte[1024 * 2];
		int len = 0;
		try {
			while((len = is.read(buff)) != -1) {
				writer.write(buff, 0, len);
			}
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer.toByteArray();
	}

	/**
	 * 删除指定文件及文件夹
	 * @param file
	 */
	public static void delete(File file) {
		if(!file.exists()) return;

		if(file.isFile() || file.list()==null) {
			file.delete();
		}else {
			File[] files = file.listFiles();
			for(File a:files) {
				delete(a);
			}
			file.delete();
		}
	}

	/**
	 * 文件下载
	 *
	 * @param targetUrl
	 */
	public static String downloadUtil(String targetUrl) {
		String downloadUrl = auth.privateDownloadUrl(targetUrl);
		String fileName =  targetUrl.substring(targetUrl.length()-4,targetUrl.length());
		String filePath = System.getProperty("user.dir").split("/ats")[0] +"/"+ UUID.randomUUID()+fileName;
		new File(filePath);
		//下载文件
		download(downloadUrl, filePath);
		return filePath;
	}

	/**生成Token*/
	public static String getToken() {
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		String upToken = auth.uploadToken(bucketname);
		return upToken;
	}

	public static void main(String[] args) {
		try {
			InputStream inputStream = new FileInputStream("C:\\Users\\wxw\\Desktop\\2222.png");
			String fileName =   UUID.randomUUID().toString().replace("-", "")+".png";
			String path = putInputStream(inputStream,fileName);
			System.out.println(path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

    
}
