package card_apple_account

import (
	"context"

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"

	"kami/internal/model"
	"kami/internal/service"
	"kami/utility/cache"
	"kami/utility/utils"

	"github.com/shopspring/decimal"
)

// GetNextUser 从sysUser表中查询所有用户，获取排序后的当前用户后面下一个Id
func (a *sAppleAccount) GetNextUser(ctx context.Context, originalUserId string, amount decimal.Decimal) (targetId string, err error) {
	users, err := service.SysUser().GetUsersAll(ctx)
	targetId = ""
	if err != nil {
		return
	}
	if len(users) == 0 {
		return
	}
	// 添加一个空值，代表添加的是管理员账户
	users = append(users, &model.SysUserSimpleOutput{Id: ""})
	currentIndex := -1
	// 查找当前id在users里的位置
	for i, user := range users {
		if user.Id == originalUserId {
			currentIndex = i
			break
		}
	}
	// 如果不在当前users里，返回第一个数
	if currentIndex == -1 {
		targetId = users[0].Id
		return
	}
	userPaymentService := service.SysUserPayment()
	for range len(users) {
		currentIndex = utils.GetTargetIndex(currentIndex+1, len(users))
		// 表示管理员
		if users[currentIndex].Id == "" {
			break
		}
		isEnough, _ := userPaymentService.CheckBalanceEnough(ctx, &model.SysUserPaymentCheckBalanceInput{
			UserId: users[currentIndex].Id,
			Amount: amount,
		})
		if isEnough {
			targetId = users[currentIndex].Id
			break
		}
	}
	return
}

func (a *sAppleAccount) SetCurrentTargetAccount(ctx context.Context, m *model.AccountIdInfo) (err error) {
	if m.AccountId == "" {
		m.UserId = ""
	}
	err = cache.NewCache().Set(ctx, cache.PrefixAppleMachineAccount.String(), m, 0)
	return
}

func (a *sAppleAccount) GetCurrentTargetAccount(ctx context.Context) (m model.AccountIdInfo, err error) {
	m = model.AccountIdInfo{}
	v, err := cache.NewCache().Get(ctx, cache.PrefixAppleMachineAccount.String())
	if err != nil {
		return
	}
	err = v.Scan(&m)
	return
}

func (a *sAppleAccount) GetAllTargetAccount(ctx context.Context) (m []*model.AccountIdInfo, err error) {
	keys, err := cache.NewCache().KeyStrings(ctx)
	m = make([]*model.AccountIdInfo, 0)
	if err != nil {
		return
	}
	slice.ForEach(keys, func(index int, item string) {
		tmpKeyList := gstr.Split(item, ":")
		if len(tmpKeyList) != 2 || tmpKeyList[0] != gconv.String(cache.PrefixAppleMachineAccount) {
			return
		}
		v, err2 := cache.NewCache().Get(ctx, item)
		if err2 != nil {
			return
		}
		tmpM := model.AccountIdInfo{}
		err2 = v.Scan(&m)
		if err2 != nil {
			return
		}
		m = append(m, &tmpM)
	})
	return
}

func (a *sAppleAccount) GetExcludeAccounts(ctx context.Context) (m []*model.AccountIdInfo, err error) {
	keys, err := cache.NewCache().KeyStrings(ctx)
	m = make([]*model.AccountIdInfo, 0)
	if err != nil {
		return
	}
	slice.ForEach(keys, func(index int, item string) {
		tmpKeyList := gstr.Split(item, ":")
		if len(tmpKeyList) != 2 || tmpKeyList[0] != cache.PrefixAppleMachineAccount.String() {
			return
		}
		v, err2 := cache.NewCache().Get(ctx, item)
		if err2 != nil {
			return
		}
		tmpM := model.AccountIdInfo{}
		err2 = v.Scan(&m)
		if err2 != nil {
			return
		}
		m = append(m, &tmpM)
	})
	return
}

// ClearCurrentTargetAccount 清空缓存
func (a *sAppleAccount) ClearCurrentTargetAccount(ctx context.Context) (err error) {
	_, err = cache.NewCache().Remove(ctx, cache.PrefixAppleMachineAccount.String())
	return
}
