package com.ruoyi.common.utils.qiniu;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.TimeUnit;

/**
 * 七牛云工具类
 * @author wjh
 * 2024/3/26
 */
public class QiNiuUtils {
    public static final String ACCESS_KEY = SpringUtils.getRequiredProperty("qiniu.accessKey");
    public static final String SECRET_KEY = SpringUtils.getRequiredProperty("qiniu.secretKey");
    public static final String BUCKET = SpringUtils.getRequiredProperty("qiniu.bucket");
    public static final Long EXPIRE_SECONDS = Long.parseLong(SpringUtils.getRequiredProperty("qiniu.expireSeconds"));   // 过期时间（秒）
    public static final String DOMAIN = SpringUtils.getRequiredProperty("qiniu.domain");   // 外链域名
    private static final String CACHE_KEY = SpringUtils.getRequiredProperty("qiniu.cacheKey");    // 缓存key
    private static final Configuration CFG;
    private static final UploadManager UPLOAD_MANAGER;
    private static final RedisCache REDIS_CACHE = SpringUtils.getBean(RedisCache.class);

    static {
        // zone0华东区域,zone1是华北区域,zone2是华南区域
        CFG = new Configuration(Region.region2());
        UPLOAD_MANAGER  = new UploadManager(CFG);
    }

    /**
     * 获取文件上传的token
     * @return token
     */
    public static String getToken() {
        String tokenCache = REDIS_CACHE.getCacheObject(CACHE_KEY);
        if (tokenCache == null) {
            StringMap putPolicy = new StringMap();
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            tokenCache = auth.uploadToken(BUCKET,null, EXPIRE_SECONDS, putPolicy);
            REDIS_CACHE.setCacheObject(CACHE_KEY, tokenCache, EXPIRE_SECONDS.intValue(), TimeUnit.SECONDS);
        }
        return tokenCache;
    }

    /**
     * 将文件上传到七牛云
     */
    public static String upload(FileInputStream fileStream) throws Exception {
        // 生成上传凭证，然后准备上传
        Response response = UPLOAD_MANAGER.put(fileStream, null, getToken(), null, null);
        // 解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return putRet.key;
    }

    public static String upload(MultipartFile file) throws Exception {
        File tempFile = File.createTempFile("temp-",  "." + FileUploadUtils.getExtension(file));
        file.transferTo(tempFile);
        try (FileInputStream fis = new FileInputStream(tempFile)){
            return upload(fis);
        }
    }

    /**
     * Base64上传到七牛云
     * @param base64
     * @return
     */
    public static String uploadBase64(String base64) throws Exception{
        byte[] bytes = base64.getBytes();
        byte[] decode = Base64Utils.decode(bytes);
        Response response = UPLOAD_MANAGER.put(decode, null, getToken());
        // 解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return putRet.key;
    }
}
