package card_redeem_account

import (
	"context"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/entity"
	"kami/utility/config"
	"kami/utility/integration/redeem"
	redeemClient "kami/utility/integration/redeem/client"

	"github.com/gogf/gf/v2/net/gtrace"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
)

func (a *sCardRedeemAccount) CheckAccountStatus(ctx context.Context, category consts.CardRedeemAccountCategory) (err error) {
	ctx, span := gtrace.NewTracer("检测账号状态").Start(ctx, "账号状态", trace.WithNewRoot(),
		trace.WithAttributes(
			attribute.String("category", gconv.String(category)),
		),
	)
	defer span.End()
	m := dao.V1CardRedeemAccountInfo.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1CardRedeemAccountInfo.Columns().Status, consts.RedeemAccountNormal).
		Where(dao.V1CardRedeemAccountInfo.Columns().Category, category)
	total, _ := m.Count()
	client, err := redeemClient.GetClient(category)
	if err != nil {
		glog.Error(ctx, "获取客户端失败", err)
	}
	for i := 0; i < total/10+1; i++ {

		gtrace.NewSpan(ctx, "查询余额", trace.WithAttributes(
			attribute.String("category", gconv.String(category)),
			attribute.Int("page", i+1),
		))

		list := make([]*entity.V1CardRedeemAccountInfo, 0)
		_ = m.Page(i+1, 10).Scan(&list)
		for _, accountInfo := range list {

			gtrace.NewSpan(ctx, "查询具体余额", trace.WithAttributes(
				attribute.String("category", gconv.String(category)),
				attribute.String("accountInfo", gconv.String(accountInfo)),
			))

			result, err2 := client.QueryBalance(ctx, &redeem.QueryBalanceReq{
				Cookie:    accountInfo.Cookie,
				AccountId: accountInfo.Id,
			})
			if err2 != nil {
				glog.Error(ctx, "查询余额失败", err2)
				continue
			}
			if !result.Ok {
				if err = a.UpdateStatus(ctx, accountInfo.Id, consts.RedeemAccountForbidden, nil); err != nil {
					glog.Error(ctx, "更新状态失败", err)
				}
			}
		}
	}
	return
}
