package logic

import (
	"fmt"
	"fusenapi/utils/auth"
	"fusenapi/utils/basic"
	"fusenapi/utils/chinese_to_pinyin"
	"fusenapi/utils/ldap_lib"
	"strings"

	"context"

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

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

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

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

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

func (l *UpdateLdapUserLogic) UpdateLdapUser(req *types.UpdateLdapUserReq, userinfo *auth.UserInfo) (resp *basic.Response) {
	req.UserDN = strings.Trim(req.UserDN, " ")
	req.Mobile = strings.Trim(req.Mobile, " ")
	req.Password = strings.Trim(req.Password, " ")
	req.Avatar = strings.Trim(req.Avatar, " ")
	req.UserName = strings.Trim(req.UserName, " ")
	if req.Password != "" {
		//todo 验证下是不是本人
	}
	if len(req.UserDN) <= 3 || req.UserDN[:3] != "cn=" {
		return resp.SetStatusWithMessage(basic.CodeRequestParamsErr, "参数错误,无效的用户DN")
	}
	//把用户名转pinyin
	userNamePinyin := chinese_to_pinyin.ChineseToPinyin(req.UserName)
	ldapServer := ldap_lib.NewLdap(l.svcCtx.Ldap, l.svcCtx.Config.Ldap.BaseDN, l.svcCtx.Config.Ldap.RootDN)
	err := ldapServer.Update(req.UserDN, map[string][]string{
		"homeDirectory": {"/home/users/" + userNamePinyin},
		"sn":            {req.UserName},
		"uid":           {userNamePinyin},
		"mobile":        {req.Mobile},
		"userPassword":  {req.Password},
		"postalAddress": {req.Avatar},
		"postalCode":    {fmt.Sprintf("%d", req.Status)},
	})
	if err != nil {
		logx.Error(err)
		return resp.SetStatusWithMessage(basic.CodeServiceErr, "更新用户失败,", err.Error())
	}
	return resp.SetStatusWithMessage(basic.CodeOK, "更新用户成功")
}

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