package alipayapi

import (
	"git.rosy.net.cn/baseapi/utils"
)

const (
	GrantTypeCode    = "authorization_code"
	GrantTypeRefresh = "refresh_token"
)

type TokenInfo struct {
	AccessToken  string `json:"access_token"`
	AlipayUserID string `json:"alipay_user_id"`
	ExpiresIn    int64  `json:"expires_in"`
	ReExpiresIn  int64  `json:"re_expires_in"`
	RefreshToken string `json:"refresh_token"`
	UserID       string `json:"user_id"`
}

func (a *API) UserInfoAuth(scopes []string, state string) (retVal map[string]interface{}, err error) {
	retVal, err = a.AccessAPI("alipay.user.info.auth", nil, map[string]interface{}{
		"scopes": scopes,
		"state":  state,
	}, false)
	return retVal, err
}

func (a *API) AuthTokenAppQuery(appAuthToken string) (retVal map[string]interface{}, err error) {
	retVal, err = a.AccessAPI("alipay.open.auth.token.app.query", nil, map[string]interface{}{
		"app_auth_token": appAuthToken,
	}, false)
	return retVal, err
}

func (a *API) SystemAuthToken(grantType, code, refreshToken string) (tokenInfo *TokenInfo, err error) {
	params := map[string]interface{}{
		"grant_type": grantType,
	}
	if code != "" {
		params["code"] = code
	}
	if refreshToken != "" {
		params["refresh_token"] = refreshToken
	}
	// 获取证书
	appCertSN, aliPayRootCertSN, _, err := SetCertSnByPath(AppCertPath, AliPayRootCertPath, AliPayPublicCertPath)
	if err != nil {
		return nil, err
	}

	params["app_cert_sn"] = appCertSN
	//params["alipay_public_cert_sn"] = aliPayPublicCertSN
	params["alipay_root_cert_sn"] = aliPayRootCertSN

	retVal, err := a.AccessAPI("alipay.system.oauth.token", params, nil, false)
	if err == nil {
		err = utils.Map2StructByJson(retVal, &tokenInfo, false)
	}
	return tokenInfo, err
}
