package com.ruoyi.common.utils;

import com.alibaba.fastjson2.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 static final Logger log = LoggerFactory.getLogger(ImgUpload.class);
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static String ACCESS_KEY = "XfYrjoMYsmwr_mRgGVDvDh9A-CAm3qpA2OqqHNyO";
    private static String SECRET_KEY = "tWJjsaYPBBACuyw8CfaF9h2BRUziuje_zwrz4GyE";
    //要上传的空间
    private static String bucketname = "xiaoniu666666";

    String BASE_URL = "https://image.xnszz.com/";


    //密钥配置
    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)").put("insertOnly", 0));
    }

    public String upload(byte[] data, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response response = uploadManager.put(data, fileType, getUpToken(fileType));
            // 上传结果
            log.info(response.bodyString());
            //解析上传成功的结果
            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 uploadStream(InputStream inputStream, String fileType) throws IOException {
        String filePath = null;
        try {
            //调用put方法上传
            Response response = uploadManager.put(inputStream, fileType, getUpToken(fileType), null, null);
            // 上传结果
            log.info(response.bodyString());
            //解析上传成功的结果
            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;
    }
}
