package com.fdkankan.common.util;

import com.google.gson.Gson;
import com.qiniu.cdn.CdnManager;
import com.qiniu.cdn.CdnResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
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.StringMap;
import com.qiniu.util.UrlSafeBase64;

import java.io.File;

public class QiniuUpload {

	//删除文件
	public static void delete(String key) throws QiniuException{
		Configuration cfg = new Configuration(QiniuUtil.zone);
		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
        bucketManager.delete(QiniuUtil.bucket, key);
	}

	//刷新文件
	public static void refresh(String url) throws QiniuException{
		String [] urls = {url};
		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
		CdnManager c = new CdnManager(auth);
		CdnResult.RefreshResult response = c.refreshUrls(urls);
	}


	/**
	 * 上传单个文件到七牛云
	 * @param key
	 * @param localFilePath
	 */
	public static boolean setFileToBucket(String key, String localFilePath){
		Configuration cfg = new Configuration(QiniuUtil.zone);
		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
		UploadManager uploadManager = new UploadManager(cfg);
		
		String upToken = auth.uploadToken(QiniuUtil.bucket);
		
		try {
		    Response response = uploadManager.put(localFilePath, key, upToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		    return true;
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		    }
		    return false;
		}
	}
	
	/**
	 * 上传本地目录下所有文件到七牛云上
	 * @param remoteFolder
	 * @param localFolderPath
	 */
	public static void setFilesToBucket(String remoteFolder, String localFolderPath) {
		Configuration cfg = new Configuration(QiniuUtil.zone);
		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
		UploadManager uploadManager = new UploadManager(cfg);
		
		File file = new File(localFolderPath);
		File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
		if (files == null) {// 如果目录为空，直接退出
			return;
		}

		// 遍历，目录下的所有文件
		for (File f : files) {
			if (f.isFile()) {
				String key = f.getName();
				if (remoteFolder != null) {
					key = remoteFolder + key;
				} 
				// 再上传文件
				String upToken = auth.uploadToken(QiniuUtil.bucket);
				try {
					Response res = uploadManager.put(f, key, upToken);
					System.out.println(res.bodyString());
				} catch (QiniuException e) {
					Response r = e.response;
					System.err.println(r.toString());
					try {
						System.err.println(r.bodyString());
					} catch (QiniuException ex2) {
					}
				}
			} else if (f.isDirectory()) {
				String key = f.getName() + "/";
				if (remoteFolder != null) {
					key = remoteFolder + key;
				}
				setFilesToBucket(key, f.getAbsolutePath());
			}
		}
	}

	/**
	 * 测试七牛上传后，自动进行数据处理操作，并另存处理后的文件
	 * @param domain 存储空间所对应的域名
	 * @param file 上传文件
	 */
	public static void testFops(String domain, File file) {
		//通过AK,SK创建Auth 对象
		Auth auth = Auth.create(QiniuUtil.accessKey, QiniuUtil.secretKey);
		Configuration cfg = new Configuration(QiniuUtil.zone);
		//上传对象
		UploadManager uploadMgr = new UploadManager(cfg);
		//私有队列
		String pipeline = "av-pipeline";
		//水印文字
		String wmText = UrlSafeBase64.encodeToString("Word For Test");
		//水印文字的颜色
		String wmFontColor = UrlSafeBase64.encodeToString("#FFFF00");
		//设置avthumb 接口
		StringBuffer ops = new StringBuffer("");
		ops.append("avthumb/mp4/wmText/" + wmText +"/wmGravityText/NorthEast/wmFontColor/" + wmFontColor);
		String saveAs = UrlSafeBase64.encodeToString(QiniuUtil.bucket + ":" + "new_" + file.getName());
		//通过管道符 "|" 拼接 saveas 接口， 保存 数据处理后的视频
		ops.append("|saveas/" + saveAs);
		//saveas 接口 需要签名 sign
		String sign = domain + "/" + file.getName() + "?" + ops.toString();
		String encodeSign = UrlSafeBase64.encodeToString(sign);
		ops.append("/sign/" + encodeSign);
		//指定 数据处理 的 上传策略， 当文件上传成功后，自定执行数据处理操作，即：ops 的接口，图片加水印，另存为 new_file.getName();
		StringMap putPolicy = new StringMap();
		putPolicy.put("persistentOps", ops.toString())      //数据处理接口及参数
				.put("persistentPipeline", pipeline);      //私有数据处理队列

		//获取上传凭证， 包含上传策略
		String uploadToken = auth.uploadToken(QiniuUtil.bucket, file.getName(), 3600, putPolicy);

		try {
			//上传
			Response resp = uploadMgr.put(file, file.getName(), uploadToken);
			//查看结果
			System.out.println(resp.statusCode + ":" + resp.bodyString());
		} catch (QiniuException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

    public static void main(String[] args) {
        QiniuUpload upload = new QiniuUpload();
        try {
            QiniuUpload.delete("head/13211064273/head.png");
//            QiniuUpload.refresh("http://scene3d.4dage.com/head/13211064273/head.png");
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }
}
