package contact

import (
	"context"
	"wechat-api/ent/predicate"
	"wechat-api/hook"

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AddNewFriendLogic) AddNewFriend(req *types.AddNewFriendReq) (*types.BaseMsgResp, error) {
	organizationId := l.ctx.Value("organizationId").(uint64)
	isAdmin := l.ctx.Value("isAdmin").(bool)
	var predicates []predicate.Wx
	predicates = append(predicates, wx.Wxid(req.OwnerWxid))
	if !isAdmin {
		predicates = append(predicates, wx.OrganizationIDEQ(organizationId))
	}
	wxInfo, err := l.svcCtx.DB.Wx.Query().Where(predicates...).First(l.ctx)
	if err != nil {
		l.Error("查询微信信息失败", err)
		return nil, err
	}

	if wxInfo.ServerID == 0 {
		hookClient := hook.NewHook("", "", "")
		err = hookClient.AddFriendInChatRoom(req.Gid, req.OwnerWxid, req.Wxid, req.Desc)
		if err != nil {
			l.Error("添加好友失败", err)
			return nil, err
		}
	} else {
		serverInfo, err := l.svcCtx.DB.Server.Get(l.ctx, wxInfo.ServerID)
		if err != nil {
			l.Error("查询服务器信息失败", err)
			return nil, err
		}

		hookClient := hook.NewHook(serverInfo.PrivateIP, serverInfo.AdminPort, wxInfo.Port)

		//通过群id获取群成员详细信息
		ChatroomMemberDetailInfo, err := hookClient.GetChatroomMemberDetailInfo(req.Gid, req.Wxid)

		if err != nil {
			l.Error("获取群成员详细信息失败", err)
			return nil, err
		}

		v3 := req.Wxid
		v4 := ""

		if ChatroomMemberDetailInfo.V3 != "" {
			v3 = ChatroomMemberDetailInfo.V3
		}

		if ChatroomMemberDetailInfo.V4 != "" {
			v4 = ChatroomMemberDetailInfo.V4
		}

		AddNewFriendResult, err := hookClient.AddNewFriend(v3, v4, req.Desc, req.AddType, "0")
		if err != nil {
			l.Error("添加好友失败", err)
			return nil, err
		}

		if AddNewFriendResult.Status != "0" {
			l.Error("添加好友失败", err)
			return nil, err
		}
	}

	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
}