package card_info_walmart

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

	"github.com/duke-git/lancet/v2/pointer"

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

	"kami/api/card_info_walmart/v1"
)

func (c *ControllerV1) AccountLoad(ctx context.Context, req *v1.AccountLoadReq) (res *v1.AccountLoadRes, err error) {
	userInfo, err := service.SysUser().GetUserById(ctx, req.UserId)
	if err != nil || pointer.IsNil(userInfo) || userInfo.Id == "" {
		err = gerror.NewCode(gcode.CodeNotAuthorized, "查询用户失败")
		return
	}
	//	查询分组
	groupId, err := service.CardRedeemAccount().GroupAddOrGetId(ctx, &model.RedeemAccountGroup{
		GroupRecord: &v1.GroupRecord{
			Name:  req.GroupName,
			Notes: "",
		},
		CreatedUserId: userInfo.Id,
		Category:      consts.CardRedeemAccountCategoryWalMart,
	}, nil)
	if groupId == 0 {
		err = gerror.WrapCode(gcode.CodeInvalidParameter, err, "添加分组失败")
		return
	}
	client, err2 := redeemClient.GetClient(consts.CardRedeemAccountCategoryWalMart)
	if err2 != nil {
		err = gerror.WrapCode(gcode.CodeInvalidParameter, err, "添加失败")
		return
	}
	res2, err2 := client.QueryBalance(ctx, &redeem.QueryBalanceReq{
		Cookie:    req.Cookie,
		AccountId: req.Name,
	})
	if pointer.IsNil(res2) || !res2.Ok {
		err = gerror.NewCode(errHandler.ErrCkFailError, "ck失效")
		return
	}
	err = service.CardRedeemAccount().AddWithGroup(ctx, &model.RedeemAccountAddInput{
		Cookie:         req.Cookie,
		Name:           req.Name,
		MaxAmountLimit: int(math.Pow10(4)) * 5,
		MaxCountLimit:  20,
		Status:         int(consts.RedeemAccountNormal),
		UserId:         userInfo.Id,
		Balance:        0,
		GroupId:        int(groupId),
		Category:       consts.CardRedeemAccountCategoryWalMart,
	}, nil)
	if err != nil {
		err = gerror.WrapCode(gcode.CodeInvalidParameter, err, "添加账户失败")
	}
	return
}
