package com.app.ydl.marketing.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Date;

/**
 * 七牛云文件上传工具类
 */
@Component
public class QiniuUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;


    /**
     * 生成新文件名
     *
     * @param fileName 原文件名
     */
    private String getNewFileName(String fileName) {
        String ext = fileName.substring(fileName.lastIndexOf("."));
        return new StringBuilder().append(System.currentTimeMillis()).append(RandomUtil.randomString(6)).append(ext).toString();
    }

    /**
     * 上传对象
     *
     * @param inputStream 文件流
     * @param fileName    文件名称，含扩展名
     * @return
     */
    public String putObject(InputStream inputStream, String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration();
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "course/" + DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + this.getNewFileName(fileName);

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.toJavaObject(JSONObject.parseObject(response.bodyString()), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        return new StringBuilder(domain).append("/").append(key).toString();
    }

}
