package card_info_walmart

import (
	"context"
	"kami/api/commonApi"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/duke-git/lancet/v2/strutil"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/jinzhu/copier"

	v1 "kami/api/card_info_walmart/v1"

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

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

	if req.UserId != "" && userInfo.Id == "" {
		userInfo.Id = req.UserId
	}
	total, list, err := service.CardRedeemAccount().List(ctx, &model.RedeemAccountListInput{
		CommonPageReq: commonApi.CommonPageReq{
			Current:  req.Current,
			PageSize: req.PageSize,
		},
		Name:            req.Name,
		NickName:        req.NickName,
		Cookie:          req.Cookie,
		UserId:          userInfo.Id,
		CreatedUserName: req.CreatedUserName,
		GroupId:         req.GroupId,
		Category:        consts.CardRedeemAccountCategoryWalMart,
	})
	if pointer.IsNil(userInfo) || userInfo.Id == "" {
		slice.ForEach(list, func(index int, item *model.RedeemAccountOutput) {
			item.Cookie = strutil.HideString(item.Cookie, 4, gstr.LenRune(item.Cookie)-4, "*")
		})
	}

	res = &v1.AccountListRes{
		CommonPageRes: commonApi.CommonPageRes[v1.AccountListRecord]{
			Total: total,
			CommonDataRes: commonApi.CommonDataRes[v1.AccountListRecord]{
				List: make([]v1.AccountListRecord, 0),
			},
		},
	}
	_ = copier.CopyWithOption(&res.List, &list, copier.Option{IgnoreEmpty: true, DeepCopy: true})
	err = errHandler.WrapError(ctx, gcode.CodeInternalError, err)
	return
}
