package wxcarduser

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"wechat-api/ent/predicate"
	"wechat-api/ent/wxcarduser"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetWxCardUserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetWxCardUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWxCardUserListLogic {
	return &GetWxCardUserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *GetWxCardUserListLogic) GetWxCardUserList(req *types.WxCardUserListReq) (*types.WxCardUserListResp, error) {
	var predicates []predicate.WxCardUser

	if req.Wxid != nil && *req.Wxid != "" {
		predicates = append(predicates, wxcarduser.Wxid(*req.Wxid))
	}
	if req.Account != nil && *req.Account != "" {
		predicates = append(predicates, wxcarduser.AccountContains(*req.Account))
	}
	if req.Nickname != nil && *req.Nickname != "" {
		predicates = append(predicates, wxcarduser.NicknameContains(*req.Nickname))
	}

	data, err := l.svcCtx.DB.WxCardUser.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.WxCardUserListResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
	}

	for _, v := range data.List {
		resp.Data.Data = append(resp.Data.Data, types.WxCardUserInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &v.ID,
				CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			},
			Wxid:     &v.Wxid,
			OpenId:   &v.OpenID,
			Avatar:   &v.Avatar,
			Phone:    &v.Phone,
			Account:  &v.Account,
			Nickname: &v.Nickname,
			Remark:   &v.Remark,
		})
	}

	return resp, nil
}
