package logic

import (
	"chain-dci/pb/dci"
	"chain-dci/pkg/app"
	errCommon "chain-dci/pkg/err"
	"chain-dci/pkg/msg"
	"chain-dci/pkg/utils"
	"encoding/base64"
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	bccrClient "github.com/antchain-openapi-sdk-go/bccr/client"
	"github.com/jinzhu/copier"
	"strings"
	"time"
	"unicode"
)

type IFile interface {
	Upload(request *dci.GetUploadUrlRequest) error
}

type File struct {
}

/*
		存证API
		GetUploadUrl
	    获取 访问 oss的链接, 注意 如果文件名为中文 则需要 对文件名使用 utf-8 字符集进行 URL编码上传
*/
func GetUploadUrl(req *bccrClient.GetUploadurlRequest) (result *bccrClient.GetUploadurlResponse) {

	result, err := app.ModuleClients.BccrClient.GetUploadurl(req)
	if err != nil {
		errCommon.NoReturnError(err, "调用 蚂蚁链获取 oss url 错误:")
		return
	}
	return
}

/*
		存证API
		Upload
	    上传 实际文件
*/
func (f *File) Upload(req *dci.GetUploadUrlRequest) (res *dci.GetUploadUrlResponse, err error) {

	isChinese := false

	getUploadUrlRequest := new(bccrClient.GetUploadurlRequest)

	var fileName string
	// 拆分 文件名 和 文件链接
	fileArr := strings.Split(req.FileName, "/")
	fileName = fileArr[len(fileArr)-1]
	fmt.Println("no encode  fileName is :", fileArr[len(fileArr)-1])

	//  如果文件名包含 中文 则需要对 fileName 进行 utf-8 字符集进行 URL编码
	for _, c := range fileName {
		if unicode.Is(unicode.Scripts["Han"], c) {
			isChinese = true
		}
	}

	if isChinese {
		fileName = base64.URLEncoding.EncodeToString([]byte(fileName))
	}
	getUploadUrlRequest.SetFileName(fileName)

	clientToken, err := createToken(time.Now().UnixMilli(), fileName, app.ModuleClients.SfNode.Generate().Base64())
	if err != nil {
		return nil, errCommon.ReturnError(err, msg.ErrCreateClientToken, "创建clientToken 失败: ")
	}
	getUploadUrlRequest.SetClientToken(clientToken)
	fmt.Println(clientToken)
	fmt.Println(len(clientToken))
	fmt.Println("encode  fileName is :", fileName)

	getUploadUrlResponse := GetUploadUrl(getUploadUrlRequest)
	res = new(dci.GetUploadUrlResponse)
	_ = copier.CopyWithOption(&res, getUploadUrlResponse, copier.Option{DeepCopy: true})

	//if tea.ToString(getUploadUrlResponse.ResultCode) != "OK" {
	//	return res, errCommon.ReturnError(err, err.Error(), "获取授权访问OSS链接 错误:")
	//}
	if tea.ToString(getUploadUrlResponse.Url) == "" || tea.ToString(getUploadUrlResponse.FileId) == "" {
		return res, errCommon.ReturnError(err, err.Error(), "获取授权访问OSS链接 错误:")
	}

	code, result := utils.PutFromFileUrlWithStream(tea.ToString(res.Url), fileName, req.FileName)
	if code != 200 {
		return res, errCommon.ReturnError(err, result, "上传文件 错误:")
	}
	return
}
