package card_info_c_trip

import (
	"context"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"
	redeemModel "kami/utility/integration/redeem"
	redeem "kami/utility/integration/redeem/client"

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

	"kami/api/card_info_c_trip/v1"

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

func (c *ControllerV1) AccountCookieBatchAdd(ctx context.Context, req *v1.AccountCookieBatchAddReq) (res *v1.AccountCookieBatchAddRes, err error) {
	userInfo, err := service.SysAuth().LoginOnlyLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}

	for _, info := range req.List {

		client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryCTrip)

		if err2 != nil {
			glog.Error(ctx, "获取客户端失败", err2)
			return
		}

		cookieUserInfo, err2 := client.QueryUserInfoWithCache(ctx, gstr.Trim(info.Cookie), gtime.M*30)
		if err2 != nil || !cookieUserInfo.Ok {
			continue
		}

		balanceInfo, err2 := client.QueryBalanceWithCache(ctx, &redeemModel.QueryBalanceReq{
			Cookie: gstr.Trim(info.Cookie),
		}, gtime.M*30)
		if err2 != nil {
			continue
		}

		_ = service.CardRedeemAccount().Add(ctx, &model.RedeemAccountAddInput{
			Cookie:         gstr.Trim(info.Cookie),
			Name:           info.Name,
			MaxAmountLimit: info.MaxAmountLimit,
			MaxCountLimit:  info.MaxCountLimit,
			Username:       cookieUserInfo.Username,
			Nickname:       cookieUserInfo.NickName,
			Balance:        balanceInfo.Money,
			UserId:         userInfo.Id,
			Category:       consts.CardRedeemAccountCategoryOriginalJD,
		}, nil)
	}
	_ = service.CardRedeemOrder().TriggerValidateAndConsume()
	return
}
