package NatsServer

import (
	"FollowUp_Notice/Nats"
	"FollowUp_Notice/logs"
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"strings"
	"time"
)

func Qiniu_UploadFile(localFile string, name string) (string, bool) {
	logs.Println("Qiniu_UploadFile =>", localFile, name)

	// 获取 七牛云的 配置信息
	msg, err := Nats.Nats.Request("Qiniu_Token", []byte(""), 3*time.Second)
	if err != nil {
		return string(msg.Data), false
	}
	fmt.Printf("Qiniu_Token : %s\n", string(msg.Data))
	Qiniu_cs := strings.Split(string(msg.Data), "|")
	Qiniu_AccessKey := Qiniu_cs[0]
	Qiniu_SecretKey := Qiniu_cs[1]
	Qiniu_BUCKET := Qiniu_cs[2]
	Qiniu_Url := Qiniu_cs[3]

	// 开始上传 七牛云
	Qiniu := qbox.NewMac(Qiniu_AccessKey, Qiniu_SecretKey)
	// 自定义返回值结构体
	type MyPutRet struct {
		Key    string
		Hash   string
		Fsize  int
		Bucket string
		Name   string
	}
	//key := "your file save key"
	// 使用 returnBody 自定义回复格式
	putPolicy := storage.PutPolicy{
		Scope:      Qiniu_BUCKET,
		ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}`,
	}
	//mac := qbox.NewMac(conf.Qiniu_AccessKey, conf.Qiniu_SecretKey)
	upToken := putPolicy.UploadToken(Qiniu)
	cfg := storage.Config{}
	formUploader := storage.NewFormUploader(&cfg)
	ret := MyPutRet{}
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
	}
	err = formUploader.PutFile(context.Background(), &ret, upToken, name, localFile, &putExtra)
	if err != nil {
		logs.Println("七牛云", "上传文件失败 "+localFile, err.Error())
		return "", false
	}
	fmt.Println(ret.Bucket, ret.Key, ret.Fsize, ret.Hash, ret.Name)
	return Qiniu_Url + "/" + name, true

}
