package org.dromara.settlement.common;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.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.StringMap;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import java.net.HttpURLConnection;
import java.net.URL;
import org.dromara.settlement.domain.qiniu.UploadPolicy;
import org.dromara.settlement.domain.qiniu.ImageInfo;

public class QiniuUtils {
	private static final Logger log = LoggerFactory.getLogger(QiniuUtils.class);

	/**
	 * 获取上传凭证 config 上传配置
	 *
	 * @return
	 */
	public static String getUptoken(String accessKey,String secretKey,String bucket,UploadPolicy policy, String pipeline) {
		try {
			Auth auth = getAuth(accessKey,secretKey);
			// 请确保该bucket已经存在
			if(policy != null && policy.getDeadline() == 0)
				policy.setDeadline(3600L);// 默认1个小时，秒
			StringMap map = null;
			if (policy != null) {
				map = new StringMap();
				if (!StringUtils.isBlank(policy.getScope()))
					map.put("scope",policy.getScope());
				if (!StringUtils.isBlank(policy.getCallbackUrl()))
					map.put("callbackUrl",policy.getCallbackUrl());
				if (!StringUtils.isBlank(policy.getCallbackBody()))
					map.put("callbackBody",policy.getCallbackBody());
				if (!StringUtils.isBlank(policy.getReturnUrl()))
					map.put("returnUrl",policy.getReturnUrl());
				if (!StringUtils.isBlank(policy.getReturnBody()))
					map.put("returnBody",policy.getReturnBody());
				if (!StringUtils.isBlank(policy.getEndUser()))
					map.put("endUser",policy.getEndUser());
				if (!StringUtils.isBlank(policy.getSaveKey()))
					map.put("saveKey",policy.getSaveKey());
				if (policy.getInsertOnly() > 0)
					map.put("insertOnly",policy.getInsertOnly());
				if (policy.getDetectMime() > 0)
					map.put("detectMime",policy.getDetectMime());
				if (policy.getFsizeLimit() > 0)
					map.put("fsizeLimit",policy.getFsizeLimit());
				if (!StringUtils.isBlank(policy.getPersistentNotifyUrl()))
					map.put("persistentNotifyUrl",policy
							.getPersistentNotifyUrl());
				if (!StringUtils.isBlank(policy.getPersistentOps()))
					map.put("persistentOps",policy.getPersistentOps());
				if (!StringUtils.isBlank(pipeline))
					map.put("persistentPipeline",pipeline);
			}
			if(map != null)
				return auth.uploadToken(bucket, null, policy.getDeadline(), map);
			return auth.uploadToken(bucket);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}

	public static Auth getAuth(String accessKey,String secretKey) {
		return Auth.create(accessKey, secretKey);
	}

	public static String getFilePath(String domain,String key) {
		if (StringUtils.isNotBlank(key)
				&& key.indexOf("/") == -1) {
			return domain + key;
		}
		return key;
	}

	/**
	 * 根据URL获取对应七牛的key
	 *
	 * @param url
	 * @return
	 */
	public static String getKeyByUrl(String domain,String url) {
		String prefix = domain;
		if (StringUtils.isNotBlank(url) && url.indexOf(prefix) != -1)
			return url.substring(prefix.length());
		return url;
	}

	/**
	 * 获取七牛中图片基础信息
	 * @author 张涛
	 * @date 2016年3月22日
	 * @param url
	 * @return
	 */
	public static ImageInfo getImageInfo(String url){
		ImageInfo imageInfo = null;
		String oldUrl = url;
		try {
			url += "?imageInfo";
			PostDataTools post = PostDataTools.getIstance();
			String result =  post.sendMessageNullParam(url, RequestMethod.GET,null,false);
			imageInfo = JSONObject.parseObject(result, ImageInfo.class);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			imageInfo = new ImageInfo();
			log.error(e.getMessage(), e);
		}
		imageInfo.setUrl(oldUrl);
		return imageInfo;
	}

	/**
	 * 获取上传七牛的文件大小
	 *
	 * @param key
	 * @return
	 */
	public static Long getFileSize(String domain,String key) {
		/*
		 * RSClient client = new RSClient(getMac()); Entry statRet =
		 * client.stat(getBucket(), key); if(statRet != null) return
		 * statRet.getFsize(); return Long.valueOf("0");
		 */
		HttpURLConnection connection = null;
		try {
			URL url = new URL(getFilePath(domain,key));
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			int res = connection.getResponseCode();
			if (res == 200) {
				return Integer.valueOf(connection.getContentLength())
						.longValue();
			}
		} catch (Exception e) {
			return Long.parseLong(0+"");
		} finally {
			if (connection != null)
				connection.disconnect();
		}
        return Long.parseLong(0+"");
	}

	public static DefaultPutRet upLoadFile(String accessKey,String secretKey,String bucket,String display,String fileName)
	{
//		ImageUtil.GenerateImage(display, "d:/soft/" +fileName + ".jpg");
		DefaultPutRet putRet = null;
		Configuration cfg = new Configuration(Zone.zone0());                //zong1() 代表华北地区
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = getAuth(accessKey,secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
        	byte[] b = Base64.decodeBase64(new String(display).getBytes());
            Response response = uploadManager.put(b, fileName, upToken);
            //解析上传成功的结果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        catch(Exception e)
        {
        	e.printStackTrace();
        }
        return putRet;
	}
}
