package ChatRoomMember

import (
	"context"
	"wechat-api/ent/wpchatroom"
	"wechat-api/ent/wpchatroommember"
	"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 GetChatroomMemberListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetChatroomMemberListLogic) GetChatroomMemberList(req *types.ChatroomMemberListReq) (resp *types.ChatroomMemberListResp, err error) {
	// todo: add your logic here and delete this line
	wxInfo, err := l.svcCtx.DB.Wx.Query().Where(wx.Wxid(*req.OwnerWxid)).First(l.ctx)

	if err != nil {
		l.Error("查询微信信息失败", err)
		return
	}

	resp = &types.ChatroomMemberListResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
	}

	if wxInfo.ServerID == 0 {
		hookClient := hook.NewHook("", "", "")
		_ = hookClient.RequestChatRoomInfo(*req.ChatRoom, wxInfo.Wxid)
		// 获取群成员
		wpChatroom, _ := l.svcCtx.DB.WpChatroom.Query().
			Where(wpchatroom.WxWxid(*req.OwnerWxid), wpchatroom.ChatroomID(*req.ChatRoom)).
			Only(l.ctx)
		if wpChatroom != nil && wpChatroom.MemberList != nil {
			for _, m := range wpChatroom.MemberList {
				member, _ := l.svcCtx.DB.WpChatroomMember.Query().
					Where(wpchatroommember.WxWxidEQ(*req.OwnerWxid), wpchatroommember.WxidEQ(m)).
					Only(l.ctx)
				if member != nil {
					resp.Data.Data = append(resp.Data.Data, types.ChatroomMemberInfo{
						Wxid:      &m,
						ChatRoom:  req.ChatRoom,
						OwnerWxid: req.OwnerWxid,
						Account:   &member.Nickname,
					})
				}
			}
		}
	} 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)

		chatrooMmemberDetail, err := hookClient.GetChatrooMmemberDetail(*req.ChatRoom)

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

		for _, v := range chatrooMmemberDetail.Member {
			resp.Data.Data = append(resp.Data.Data, types.ChatroomMemberInfo{
				Wxid:      &v.Wxid,
				ChatRoom:  req.ChatRoom,
				OwnerWxid: req.OwnerWxid,
				Account:   &v.Nickname,
			})
		}
	}

	return resp, nil
}
