package com.fdkankan.common.util;

import com.qiniu.common.Zone;
import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;

public class QiniuUtil {

    public static String accessKey = "dlPPwgZky_F-iP8CbSbJpiAtAcqw3BYwb9rdHMrS";
    public static String secretKey = "YEtkLKDsImXB-8m1CT1zV_YwCwwGvrUvo2ktj9KZ";
    public static Zone zone = Zone.zone1();
    public static String bucket = "scene3d";
    public static String remoteUrl = "https://4dkanzhan.4dkankan.com/";

    public static void main(String[] args) throws IOException {
//        crop4K("4k.jpg", "http://www.baidu.com");
//        thumb("test111.jpg", "128", "128", "http://www.baidu.com");

        /*try{
            File f = new File("D:/usr/local/szggkfzlg/upload/20190125181036.png");
            FileInputStream fi = new FileInputStream(f);
            try{
                BufferedImage sourceImg =ImageIO.read(fi);//判断图片是否损坏
                int picWidth= sourceImg.getWidth(); //确保图片是正确的（正确的图片可以取得宽度）
            }catch (Exception e) {
                // TODO: handle exception
                fi.close();//关闭IO流才能操作图片
            }finally{
                fi.close();//最后一定要关闭IO流
            }
        }catch (Exception e  ) {
            // TODO: handle exception
            System.out.println(e.toString());
        }*/

        getVideoFrame("a.mp4", "png", "6.010", null, null, null, "a_framw.png", "http://www.baidu.com");
    }

    /**
     * 视频帧缩略图接口(vframe)用于从视频流中截取指定时刻的单帧画面并按指定大小缩放成图片
     * @param key 文件名  a.mp4
     * @param suffixName 输出的目标截图格式，支持jpg、png等。
     * @param second 指定截取视频的时刻，单位：秒，精确到毫秒。
     * @param width 缩略图宽度，单位：像素（px），取值范围为1-3840， 可不传。
     * @param height 缩略图高度，单位：像素（px），取值范围为1-2160， 可不传。
     * @param rotate 指定顺时针旋转的度数，可取值为90、180、270、auto，默认为不旋转，可不传。
     * @param newKey 新文件名称
     * @param notifyURL 回调地址
     * @throws IOException
     */
    public static void getVideoFrame(String key, String suffixName, String second, Integer width, Integer height, Integer rotate, String newKey, String notifyURL) throws IOException {
        StringBuffer sb = new StringBuffer("vframe/").append(suffixName).append("/offset/").append(second);
        if (width != null){
            sb.append("/w/").append(width);
        }
        if (height != null){
            sb.append("/h/").append(height);
        }
        if (rotate != null){
            sb.append("/rotate/").append(rotate);
        }

        String fop = URLEncoder.encode(sb.toString(), "utf-8");
        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
        ops.append("|saveas/").append(saveAs);

        ops.append("&notifyURL=").append(notifyURL);

        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
        entity.setContentType("application/x-www-form-urlencoded");
        post.setEntity(entity);

        Auth auth = Auth.create(accessKey, secretKey);
        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
        post.setHeader("Authorization", "QBox " + si);
        HttpClient client = new DefaultHttpClient();
        HttpResponse res = client.execute(post);
        String ret = EntityUtils.toString(res.getEntity(), "UTF-8");
        System.out.println(ret);

    }

    /**
     * 给视频添加水印
     * @param key a.mp4
     * @param text  4dage
     * @param fontColor #FFFF00
     * @param newKey new_a.mp4
     * @param notifyURL 回调地址
     * @throws IOException
     */
    public static void waterMark(String key, String text, String fontColor, String newKey, String notifyURL) throws IOException {
        String fop = "avthumb/mp4/";
        fop = URLEncoder.encode(fop, "utf-8");
        //水印文字
        String wmText = UrlSafeBase64.encodeToString(text);
        //水印文字的颜色
        String wmFontColor = UrlSafeBase64.encodeToString(fontColor);
        //设置avthumb 接口
        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
        ops.append("avthumb/mp4/wmText/").append(wmText).append("/wmGravityText/NorthEast/wmFontColor/").append(wmFontColor);
        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
        ops.append("|saveas/").append(saveAs);
        ops.append("&notifyURL=").append(notifyURL);

        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
        entity.setContentType("application/x-www-form-urlencoded");
        post.setEntity(entity);

        Auth auth = Auth.create(accessKey, secretKey);
        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
        post.setHeader("Authorization", "QBox " + si);
        HttpClient client = new DefaultHttpClient();
        HttpResponse res = client.execute(post);
        String ret = EntityUtils.toString(res.getEntity(), "UTF-8");
        System.out.println(ret);
    }

    /**
     * 将4K图片裁剪成64张512*512
     * @param key
     * @param notifyURL  回调地址 "http://wwww.cn/qn/notify&force=1"
     * @throws IOException
     */
    public static void crop4K(String key, String notifyURL) throws IOException {
        String fop = "imageMogr2/auto-orient/";
        fop = URLEncoder.encode(fop, "utf-8");

        String fileName = key.substring(0, key.lastIndexOf("."));
        String suffixName = key.substring(key.lastIndexOf("."));

        Auth auth = Auth.create(accessKey, secretKey);

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
                System.out.println(ret);
            }
        }
    }

    /**
     * 将2K图片裁剪成16张512*512
     * @param key
     * @param notifyURL 回调地址 "http://wwww.cn/qn/notify&force=1"
     * @throws IOException
     */
    public static void crop2k(String key, String notifyURL) throws IOException {
        String fop = "imageMogr2/auto-orient/";
        fop = URLEncoder.encode(fop, "utf-8");

        String fileName = key.substring(0, key.lastIndexOf("."));
        String suffixName = key.substring(key.lastIndexOf("."));

        Auth auth = Auth.create(accessKey, secretKey);

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
                System.out.println(ret);
            }
        }
    }

    /**
     * 将1K图片裁剪成4张512*512
     * @param key
     * @param notifyURL 回调地址 "http://wwww.cn/qn/notify&force=1"
     * @throws IOException
     */
    public static void crop1k(String key, String notifyURL) throws IOException {
        String fop = "imageMogr2/auto-orient/";
        fop = URLEncoder.encode(fop, "utf-8");

        String fileName = key.substring(0, key.lastIndexOf("."));
        String suffixName = key.substring(key.lastIndexOf("."));

        Auth auth = Auth.create(accessKey, secretKey);

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                String ret = crop(key, notifyURL, fop, fileName, suffixName, auth, i, j);
                System.out.println(ret);
            }
        }
    }

    private static String crop(String key, String notifyURL, String fop, String fileName, String suffixName, Auth auth, int i, int j) throws IOException {
        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
        ops.append("crop/!512x512a" + j * 512 + "a" + i * 512);

        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + fileName + "_" + j + "_" + i + suffixName);
        ops.append("|saveas/").append(saveAs);
        ops.append("&notifyURL=").append(notifyURL);
        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
        entity.setContentType("application/x-www-form-urlencoded");
        post.setEntity(entity);

        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
        post.setHeader("Authorization", "QBox " + si);
        HttpClient client = new DefaultHttpClient();
        HttpResponse res = client.execute(post);
        return EntityUtils.toString(res.getEntity(), "UTF-8");
    }

    /**
     * 将七牛云上的图片缩放成指定大小的图片
     * @param key
     * @param width
     * @param height
     * @param notifyURL
     * @throws IOException
     */
    public static void thumb(String key, String width, String height, String notifyURL, String newKey) throws IOException {
        String fop = "imageMogr2/auto-orient/";
        fop = URLEncoder.encode(fop, "utf-8");

        String fileName = key.substring(0, key.lastIndexOf("."));
        String suffixName = key.substring(key.lastIndexOf("."));

        Auth auth = Auth.create(accessKey, secretKey);

        StringBuffer ops = new StringBuffer("bucket=").append(bucket).append("&key=").append(key).append("&fops=").append(fop);
        ops.append("thumbnail/"+width+"x"+height+"!");

        //saveAs新生成文件的名称
        newKey = StringUtils.isNotEmpty(newKey) ? newKey : (fileName + "_thumb" + suffixName);
        String saveAs = UrlSafeBase64.encodeToString(bucket + ":" + newKey);
        ops.append("|saveas/").append(saveAs);
        ops.append("&notifyURL=").append(notifyURL);
        HttpPost post = new HttpPost("http://api.qiniu.com/pfop/");
        post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        StringEntity entity = new StringEntity(ops.toString(), "utf-8");
        entity.setContentType("application/x-www-form-urlencoded");
        post.setEntity(entity);

        String si = auth.signRequest("http://api.qiniu.com/pfop/", ops.toString().getBytes(), "application/x-www-form-urlencoded");
        post.setHeader("Authorization", "QBox " + si);
        HttpClient client = new DefaultHttpClient();
        HttpResponse res = client.execute(post);
        System.out.println(EntityUtils.toString(res.getEntity(), "UTF-8"));
    }

}
