package tao_vegetable

import (
	"encoding/json"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability304"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability304/request"
)

const (
	AppKey     = "34402634"
	AppSecret  = "fda9a7045262e3aa1f26ca508a9be242"
	ServerUrl  = "https://eco.taobao.com/router/rest"             // 正式环境https
	ServerUrl2 = "https://qimen.api.taobao.com/top/router/qmtest" // 沙箱环境https
	ServerUrl3 = "http://qimen.api.taobao.com/top/router/qm"      // 正式环境http
	ServerUrl4 = "http://qimen.api.taobao.com/top/router/qmtest"  // 沙箱环境http
)

func NewTaoVegetable(appKey, appSecret, serverUrl string) *API {
	return &API{client: topsdk.NewDefaultTopClient(appKey, appSecret, serverUrl, 10000, 10000)}
}

type API struct {
	client        topsdk.TopClient
	token         string
	refreshToken  string
	vendorOrgCode string
}

func (a *API) GetVendorOrgCode() string {
	return a.vendorOrgCode
}
func (a *API) SetVendorOrgCode(vendorOrgCode string) {
	a.vendorOrgCode = vendorOrgCode
}

func (a *API) GetAppSecret() string {
	return a.client.AppSecret
}

func (a *API) SetToken(token string) {
	a.token = token
}

func (a *API) GetToken() string {
	return a.token
}

func (a *API) SetRefreshToken(refreshToken string) {
	a.refreshToken = refreshToken
}

func (a *API) GetStoreToken(code, uuId string) (*StoreTokenInfo, error) {
	param := &request.TaobaoTopAuthTokenCreateRequest{
		Code: &code,
	}
	data, err := ability304.NewAbility304(&a.client).TaobaoTopAuthTokenCreate(param)
	if err != nil {
		return nil, err
	}

	var token *StoreTokenInfo
	if err := json.Unmarshal([]byte(data.TokenResult), &token); err != nil {
		return nil, err
	}
	return token, err
}

func (a *API) GetRefreshToken(refreshToken string) (*StoreTokenInfo, error) {
	param := &request.TaobaoTopAuthTokenRefreshRequest{
		RefreshToken: &refreshToken,
	}
	data, err := ability304.NewAbility304(&a.client).TaobaoTopAuthTokenRefresh(param)
	if err != nil {
		return nil, err
	}

	var token *StoreTokenInfo
	if err := json.Unmarshal([]byte(data.TokenResult), &token); err != nil {
		return nil, err
	}
	return token, err
}
