package tmall

import (
	"context"
	"encoding/json"
	"errors"
	"kami/utility/cache"
	"kami/utility/config"
	tmallModel "kami/utility/integration/tmall/models"
	"time"
	"topsdk"
	"topsdk/ability304"
	"topsdk/ability304/request"
	"topsdk/ability304/response"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/duke-git/lancet/v2/retry"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
)

func (c *InnerClient) OAuth2Login(ctx context.Context, code string) (res *tmallModel.OAuthResponse, err error) {
	cfg, err := config.NewConfig(ctx).GetTMallGame()
	if err != nil {
		return
	}
	cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*5, 1000*5)
	resp := new(response.TaobaoTopAuthTokenCreateResponse)
	if err2 := retry.Retry(func() error {
		resp, err = ability304.NewAbility304(&cli).TaobaoTopAuthTokenCreate(&request.TaobaoTopAuthTokenCreateRequest{
			Code: &code,
		})
		if pointer.IsNil(resp) || resp.RequestId == "" || err != nil {
			err = gerror.New(err.Error())
		}
		return err
	}, retry.Context(ctx), retry.RetryTimes(5)); err2 != nil {
		return nil, errors.Join(err, gerror.New("淘宝授权错误"))
	}
	glog.Info(ctx, "淘宝授权结果", resp)
	res = &tmallModel.OAuthResponse{}
	if err2 := json.Unmarshal([]byte(resp.TokenResult), &res); err2 == nil {
		_ = cache.NewCache().Set(ctx, cache.TMallGameThirdPartyCacheKeyTMall, *res, time.Duration(res.ExpiresIn)*gtime.S)
	}
	return
}

func (c *InnerClient) OAuth2TokenRefresh(ctx context.Context, refreshToken string) (res *tmallModel.OAuthResponse, err error) {
	cfg, err := config.NewConfig(ctx).GetTMallGame()
	if err != nil {
		return
	}
	//重试次数
	retResponse := &response.TaobaoTopAuthTokenRefreshResponse{}
	if err2 := retry.Retry(func() error {
		cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*5, 1000*5)
		retResponse, err = ability304.NewAbility304(&cli).TaobaoTopAuthTokenRefresh(&request.TaobaoTopAuthTokenRefreshRequest{
			RefreshToken: &refreshToken,
		})
		if pointer.IsNil(retResponse) || retResponse.RequestId == "" || err != nil {
			err = gerror.New(err.Error())
		}
		return err
	}, retry.Context(ctx), retry.RetryTimes(5)); err2 != nil {
		return nil, errors.Join(err, gerror.New("淘宝刷新token错误"))
	}
	res = &tmallModel.OAuthResponse{}
	if err = json.Unmarshal([]byte(retResponse.TokenResult), &res); err == nil {
		_ = cache.NewCache().Set(ctx, cache.TMallGameThirdPartyCacheKeyTMall, *res, time.Duration(res.ExpiresIn)*gtime.S)
	}
	return
}
