package com.ruoyi.common.utils;

import com.qiniu.util.Auth;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class QiniuBase64UploadUtil {

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

    /**
     * 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 Map<String,Object> put64image(String file64,String name) throws Exception {
        ;
        //-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"));
        Map<String,Object> result = new HashMap<>();
        result.put("code", code);
        result.put("message", message);
        if(code.equals("200")){
            result.put("url", "http://fileimg.makalu.cc/"+name);
        }
        response.body().close();
        System.out.println(result);
        return result;

    }
    /**
     * 测试
     * base64没有data头
     */
//    public static void main(String[] args) throws Exception {
//        String file64 = "";
//        new QiniuBase64UploadUtil().put64image(file64,"face-"+UUID.randomUUID()+".jpg");
//    }
}
