package logic

import (
	"context"
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"fusenapi/utils/ldap_lib"
	"github.com/go-ldap/ldap/v3"
	"strconv"
	"strings"

	"fusenapi/server/ldap-admin/internal/svc"
	"fusenapi/server/ldap-admin/internal/types"

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

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

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

// 处理进入前逻辑w,r
// func (l *GetLdapUserInfoLogic) BeforeLogic(w http.ResponseWriter, r *http.Request) {
// }

func (l *GetLdapUserInfoLogic) GetLdapUserInfo(req *types.GetLdapUserInfoReq, userinfo *auth.UserInfo) (resp *basic.Response) {
	if len(req.UserDN) <= 3 || req.UserDN[:3] != "cn=" {
		return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "参数错误,用户DN错误")
	}
	ldapServer := ldap_lib.NewLdap(l.svcCtx.Ldap, l.svcCtx.Config.Ldap.BaseDN, l.svcCtx.Config.Ldap.RootDN)
	res, err := ldapServer.Search(req.UserDN, ldap.ScopeWholeSubtree, "(objectClass=inetOrgPerson)", nil, nil)
	if err != nil {
		logx.Error(err)
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "获取用户信息失败:"+err.Error())
	}
	if len(res.Entries) != 1 {
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "查询到不到用户信息")
	}
	apiRsp := types.GetLdapUserInfoRsp{
		UserId: 0,
		Status: 0,
	}
	for _, entry := range res.Entries {
		apiRsp.UserDN = entry.DN
		for _, attr := range entry.Attributes {
			switch attr.Name {
			case "uidNumber": //用户id
				if len(attr.Values) == 0 {
					return resp.SetStatusWithMessage(basic.CodeServiceErr, "用户id不存在")
				}
				apiRsp.UserId, err = strconv.ParseInt(attr.Values[0], 10, 64)
				if err != nil {
					logx.Error(err)
					return resp.SetStatusWithMessage(basic.CodeServiceErr, "用户id转数字失败")
				}
			case "sn": //用户真名
				apiRsp.UserName = strings.Join(attr.Values, "")
			case "mail": //邮箱
				apiRsp.Email = strings.Join(attr.Values, "")
			case "mobile": //手机号
				apiRsp.Mobile = strings.Join(attr.Values, "")
			case "postalAddress": //头像
				apiRsp.Avatar = strings.Join(attr.Values, "")
			case "postalCode": //状态
				if len(attr.Values) == 0 {
					return resp.SetStatusWithMessage(basic.CodeServiceErr, "用户状态不存在")
				}
				apiRsp.Status, err = strconv.ParseInt(attr.Values[0], 10, 64)
				if err != nil {
					logx.Error(err)
					return resp.SetStatusWithMessage(basic.CodeServiceErr, "用户状态转数字失败")
				}
			}
		}
	}
	if apiRsp.UserId == 0 {
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "查询到的不是用户信息!!!")
	}
	return resp.SetStatusWithMessage(basic.CodeOK, "success", apiRsp)
}

// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *GetLdapUserInfoLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }