package admin_user

import (
	"context"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/common/ctxdata"
	"tydata-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminUserInfoLogic) AdminUserInfo(req *types.AdminUserInfoReq) (resp *types.AdminUserInfoResp, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败, %+v", err)
	}

	user, err := l.svcCtx.AdminUserModel.FindOne(l.ctx, userId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID信息失败, %+v", err)
	}
	// 获取权限
	adminUserRoleBuilder := l.svcCtx.AdminUserRoleModel.SelectBuilder().Where(squirrel.Eq{"user_id": user.Id})
	permissions, err := l.svcCtx.AdminUserRoleModel.FindAll(l.ctx, adminUserRoleBuilder, "role_id DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("获取权限失败"), "用户登录, 获取权限失败, 用户名: %s", user.Username)
	}

	// 获取角色ID数组
	roleIds := make([]int64, 0)
	for _, permission := range permissions {
		roleIds = append(roleIds, permission.RoleId)
	}

	// 获取角色名称
	roles := make([]string, 0)
	for _, roleId := range roleIds {
		role, err := l.svcCtx.AdminRoleModel.FindOne(l.ctx, roleId)
		if err != nil {
			continue
		}
		roles = append(roles, role.RoleCode)
	}
	return &types.AdminUserInfoResp{
		Username: user.Username,
		RealName: user.RealName,
		Roles:    roles,
	}, nil
}
