package user

import (
	"context"

	"sundynix-micro-go/app/system/api/internal/svc"
	"sundynix-micro-go/app/system/api/internal/types"
	"sundynix-micro-go/app/system/rpc/system"

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

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

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

func (l *GetUserListLogic) GetUserList(req *types.UserListReq) (resp interface{}, err error) {
	rpcResp, err := l.svcCtx.SystemRpc.GetUserList(l.ctx, &system.GetUserListReq{
		Current:  int32(req.Current),
		PageSize: int32(req.PageSize),
		Name:     req.Name,
		Account:  req.Account,
	})
	if err != nil {
		return nil, err
	}
	var list []map[string]interface{}
	for _, u := range rpcResp.List {
		var roles []map[string]interface{}
		for _, r := range u.Roles {
			roles = append(roles, map[string]interface{}{
				"id":   r.Id,
				"name": r.Name,
				"code": r.Code,
			})
		}

		list = append(list, map[string]interface{}{
			"id":        u.Id,
			"name":      u.Name,
			"account":   u.Account,
			"nickName":  u.NickName,
			"phone":     u.Phone,
			"gender":    u.Gender,
			"createdAt": u.CreatedAt,
			"roles":     roles,
		})
	}
	return map[string]interface{}{"list": list, "total": rpcResp.Total}, nil
}
