package com.library.util;

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.util.Auth;
import com.qiniu.util.StringMap;
import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Description: 保存图片工具类
 * Company: youjiang
 * @author Kwum
 * @date 2016年10月17日 下午5:09:34
 * @version 1.0
 */

public class QiniuUtils {
	//设置好账号的ACCESS_KEY和SECRET_KEY
    // private static String ACCESS_KEY ="5hILYOS8yK0havuWevEe5R3Qh-AUEGwEvLjHvBuH";

    private static String ACCESS_KEY = "";
    private static String SECRET_KEY = "";

    private static String domain = "";
    //要上传的空间
    private static String bucketname = "";
    //密钥配置
    private static Auth auth ;
    //第一种方式: 指定具体的要上传的zone
    private static Zone z;
    private static Configuration c ;
    //创建上传对象
    private static UploadManager uploadManager;
    
    private static StringMap policy = new StringMap();

    //yipage@163.com
    //yipage_wechat

    static{
    	try {
			auth = Auth.create(ACCESS_KEY, SECRET_KEY);
			long epoch = System.currentTimeMillis()/1000 + 3600;
	        //3. 构建上传管理对象
	        policy.put("scope", bucketname);
	        policy.put("deadline", epoch);
//	        policy.putNotEmpty("mimeLimit", "image/*");
	    	z = Zone.zone0();
	    	c = new Configuration(z);
	    	uploadManager = new UploadManager(c);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken() {
    	long expireSeconds = 36000;
        return auth.uploadToken(bucketname, null, expireSeconds, policy);
    }
    
   
    
    
    public static String saveImg(HttpServletRequest request,
                                 byte[] file, String fileName) throws IOException {
    	
        try {
        	long name = System.nanoTime();//获取系统当前时间（唯一值）
        	String ext = fileName.substring(fileName.lastIndexOf("."));
        	//上传到七牛后保存的文件名
            String key = name+ext;
            //调用put方法上传
            Response res = uploadManager.put(file, key, getUpToken());
            //打印返回的信息
            JSONObject json = JSONObject.fromObject(res.bodyString());
            return json.getString("key");
            
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
            	e1.printStackTrace();
            }
        }
        return "";
    }
    
    public static String getPathByUploadImage(HttpServletRequest request,
                                              byte[] file, String fileName)throws Exception{
    	String imgName =  saveImg(request, file, fileName);
    	String imgPath = "http://"+domain+"/"+imgName;
    	return imgPath;
    }
    
    public static String saveFile(byte[] byteArray,
    		 String fileName) throws IOException {
        try {
        	long name = System.nanoTime();//获取系统当前时间（唯一值）
        	String ext = fileName.substring(fileName.lastIndexOf("."));
        	//上传到七牛后保存的文件名
            String key = name+ext;
            //调用put方法上传
            Response res =  uploadManager.put(byteArray, key, getUpToken());
            //打印返回的信息
            JSONObject json = JSONObject.fromObject(res.bodyString());
            String imgName = json.getString("key");
            //String imgPath = "http://"+domain+"/"+imgName;
            return imgName;
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            	e1.printStackTrace();
            }
        }
        return "";
    }
    
    
    public static void main(String[] args) {
    		System.out.println(getUpToken());
	}
}

