package tmall

import (
	"context"
	"kami/utility/integration/tmall"

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

// CronAuthTask 遍历刷新授权信息
func (c *InnerClient) CronAuthTask(ctx context.Context) (err error) {
	//检查OAuth Token是否正常
	tokenInfo, err := tmall.GetCachedOAuthToken(ctx)
	if err != nil || tokenInfo == nil || pointer.IsNil(tokenInfo) {
		return
	}
	//请求订单列表
	if _, err2 := client.GetTradeGetListByCreatedTime(ctx, tmall.ENUM_TRADE_NO_CREATE_PAY, gtime.M); err2 != nil {
		glog.Error(ctx, "获取订单列表失败", err2, tokenInfo)
		_ = tmall.ClearCachedOAuthToken(ctx)
		return
	}
	//判断还有10分钟过期，清空token消息
	if gtime.NewFromTimeStamp(tokenInfo.ExpireTime).Sub(gtime.Now()) <= gtime.M*10 {
		glog.Info(ctx, "Token即将过期，清空缓存")
		_ = tmall.ClearCachedOAuthToken(ctx)
	}
	if gtime.NewFromTimeStamp(tokenInfo.ExpireTime).Sub(gtime.Now()) <= gtime.H {
		glog.Info(ctx, "Token即将过期，尝试刷新")
		_, err = c.OAuth2TokenRefresh(ctx, tokenInfo.RefreshToken)
	}
	return
}
