package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public class ImgUpload {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //设置好账号的ACCESS_KEY和SECRET_KEY
    //private static String ACCESS_KEY = "qY9PLBDlLNzkvI3hrDRYJcqCbMX_TmI0Y38Fp-lu";
    //private static String SECRET_KEY = "Db4zv3XYsf7jNPuLFAV_CVRVQcgYCdX4pVk8BayH";
    // 下面是千冻网的
    private static String ACCESS_KEY = "BmkpzQjmX8tJlnI4APClBqANktcGwxRDO92vO-aV";
    private static String SECRET_KEY = "hAv5B8bi-M2SKZ_YsOKqQ62VuL_AQCj5jqnN4AMC";
    //要上传的空间
    private static String bucketname = "qiandong";

    String BASE_URL = "https://image.qiandongwang.cn/";


    //密钥配置
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    ///////////////////////指定上传的Zone的信息//////////////////
    //第一种方式: 指定具体的要上传的zone
    //注：该具体指定的方式和以下自动识别的方式选择其一即可
    //要上传的空间(bucket)的存储区域为华东时
    // Zone z = Zone.zone0();
    //要上传的空间(bucket)的存储区域为华北时
    // Zone z = Zone.zone1();
    //要上传的空间(bucket)的存储区域为华南时
    // Zone z = Zone.zone2();

    //第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
    Zone z = Zone.zone2();  // 华南
    Configuration c = new Configuration(z);

    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken(String path) {
        if (StringUtils.isBlank(path)) {
            path = "IMG";
        }
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("saveKey", path + "$(etag)$(ext)"));
    }

    public String upload(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType));
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }

    public String upload(InputStream inputStream, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response response = uploadManager.put(inputStream, fileType, auth.uploadToken(bucketname, fileType), null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            if (StringUtils.isNotBlank(putRet.hash)) {
                // 访问链接
                filePath = BASE_URL + putRet.key;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }

    public String uploadOffice(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType),null,"application/vnd.openxmlformats-officedocument.wordprocessingml.document",false);
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }public String uploadOfficeDoc(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response res = uploadManager.put(data, null, getUpToken(fileType),null,"application/msword",false);
            //打印返回的信息
            System.out.println(res.bodyString());
            filePath = BASE_URL + res.jsonToMap().get("key").toString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息\
            logger.error(r.toString());
        } finally {
            return filePath;
        }
    }

    public Boolean delete(String filePath)throws IOException{
        boolean fla = true;
        c = new Configuration(z);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, c);
        try {
            bucketManager.delete(bucketname, filePath);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            logger.error(ex.response.toString());
            fla = false;
        }
        return fla;
    }
}
