package card_info_t_mall_game

import (
	"context"
	"fmt"
	"kami/internal/errHandler"
	"kami/internal/service"
	"kami/utility/cache"

	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"

	"github.com/gogf/gf/v2/errors/gcode"

	"kami/api/card_info_t_mall_game/v1"
)

func (c *ControllerV1) TMallGameAccountGetOneRandom(ctx context.Context, req *v1.TMallGameAccountGetOneRandomReq) (res *v1.TMallGameAccountGetOneRandomRes, err error) {
	//优先从缓存中把账号取出来
	res = new(v1.TMallGameAccountGetOneRandomRes)
	var accountNumberPoint *gvar.Var
	gmlock.LockFunc("TMallGameAccountCache", func() {
		accountNumberPoint, err = cache.NewCache().Get(ctx, fmt.Sprintf("TMallGameAccount:%s", req.OrderNo))
	})
	accountService := service.RechargeTMallGameAccount()
	if err == nil && accountNumberPoint != nil && !accountNumberPoint.IsNil() &&
		accountService.CheckAccountNumberNormal(ctx, accountNumberPoint.String(), nil) {
		res.AccountNumber = accountNumberPoint.String()
		return
	}
	var cachedKey []string
	gmlock.LockFunc("TMallGameAccountAllKey", func() {
		cachedKey, err = cache.NewCache().KeyStrings(ctx)
	})
	//提取出所有需要的账号
	var accountNumbers []string
	for _, key := range cachedKey {
		if gstr.Contains(key, "TMallGameAccount:") {
			an, _ := cache.NewCache().Get(ctx, key)
			if an != nil && !an.IsNil() {
				accountNumbers = append(accountNumbers, an.String())
			}
		}
	}
	var accountNumber string
	gmlock.LockFunc("TMallGameAccountGetRandom", func() {
		accountNumber, err = accountService.GetRandomOne(ctx, accountNumbers)
	})
	res.AccountNumber = accountNumber
	err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "获取充值账户错误")
	if err == nil {
		err = cache.NewCache().Set(ctx, fmt.Sprintf("TMallGameAccount:%s", req.OrderNo), accountNumber, gtime.D)
		glog.Info(ctx, "缓存订单", req.OrderNo, "缓存充值账号", accountNumber)
	}
	return
}
