package logic

import (
	"dubbo.apache.org/dubbo-go/v3/common/logger"
	"encoding/json"
	"errors"
	"fmt"
	"fonchain-fiee/pkg/model"
	"fonchain-fiee/pkg/utils"
	"time"
)

const (
	grantType    = "client_credentials"
	clientId     = "SjscdLEybzyxiV7lXKA5iSvZ"
	clientSecret = "22fCduMdCarO6WWOi4WiSmt9rIeez3FW"
)

var accessToken string
var expiresIn uint64

func GetImageAccessToken() (string, error) {
	var (
		resObj model.BaiduAccessToken
		err    error
		// daoAccessToken entity.AccessToken
	)
	if expiresIn == 0 || expiresIn < uint64(time.Now().Unix()) {
		fmt.Println(1)
		if resObj, err = getAccessTokenWithApi(); err != nil { //从链上获取
			return "", err
		}
		accessToken = resObj.Access_token
		expiresIn = resObj.Expires_in
	}

	return accessToken, nil

}

func getAccessTokenWithApi() (model.BaiduAccessToken, error) {
	var (
		resObj model.BaiduAccessToken
		err    error
	)
	url := "https://aip.baidubce.com/oauth/2.0/token"
	urlReq := "?grant_type=" + grantType + "&client_id=" + clientId + "&client_secret=" + clientSecret
	res := utils.Get(url + urlReq)
	if err = json.Unmarshal([]byte(res), &resObj); err != nil {
		logger.Error("getAccessTokenWithApi json err", err)
		return resObj, err
	}
	if resObj.Error != "" {
		logger.Error("getAccessTokenWithApi err", err)
		return resObj, errors.New(resObj.Error_description)
	}
	return resObj, err
}
