package com.ghy.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.ghy.common.config.QiniuConfig;
import com.ghy.common.utils.uuid.UUID;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;

public class QiniuUtils {

    public static String getUpToken() {
        Auth auth = Auth.create("QTNOppkvtufxTxLjt1V7YZwvzV2Rc6WLD5yXLBVY", "V8SM9nkbO-dft4JmG7UaCH6RYxXdqzrvQ0zWO2W3");
        return auth.uploadToken("gqz");
    }

    public static String upload(byte[] uploadBytes) throws QiniuException {

        String key = UUID.randomUUID().toString().replaceAll("-", "");

        Configuration cfg = new Configuration(Region.region2());//设置华南的服务器
        UploadManager uploadManager = new UploadManager(cfg);

        String upToken = getUpToken();
        Response response = uploadManager.put(uploadBytes, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        return "https://gqz.opsoul.com/" + putRet.key;
    }

}
