package MessageHandlers

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"wechat-api/ent/wx"
	"wechat-api/hook"
	"wechat-api/internal/pkg/wechat_ws"
	"wechat-api/internal/svc"
	"wechat-api/workphone"
)

type FriendPushNoticeHandler struct {
	svcCtx *svc.ServiceContext
}

func NewFriendPushNoticeHandler(svcCtx *svc.ServiceContext) *FriendPushNoticeHandler {
	return &FriendPushNoticeHandler{
		svcCtx: svcCtx,
	}
}

func (f *FriendPushNoticeHandler) Handler(msg *wechat_ws.MsgJsonObject) error {
	if msg.MsgType == "FriendPushNotice" {
		message := workphone.FriendPushNoticeMessage{}
		err := json.Unmarshal([]byte(msg.Message), &message)
		if err != nil {
			return err
		}
		// 拿到租户 id
		wx_info, err := f.svcCtx.DB.Wx.Query().
			Where(
				wx.WxidEQ(message.WeChatId), // Additional filter by organizationId
			).
			Only(context.TODO())
		hookClient := hook.NewHook("", "", "")
		for _, friend := range message.Friends {
			if message.WeChatId == "wxid_ifzo7uu0cl3b22" {
				friendType := 1
				if friend.Type == 1 {
					friendType = 2
					_ = hookClient.RequestChatRoomInfo(friend.FriendId, message.WeChatId)
				} else {
					friendType = 1
				}
				_, err = f.svcCtx.DB.Contact.Create().
					SetWxWxid(message.WeChatId).
					SetType(friendType).
					SetWxid(friend.FriendId).
					SetAccount(friend.FriendNo).
					SetNickname(friend.FriendNick).
					SetMarkname(friend.Memo).
					SetHeadimg(friend.Avatar).
					//SetSex(cast.ToInt(friend.Gender)).
					SetOrganizationID(wx_info.OrganizationID).
					OnConflict().
					UpdateNewValues().
					SetOrganizationID(wx_info.OrganizationID).
					ID(context.TODO())

				if err != nil {
					logx.Error("Contact.Create: ", wx_info.OrganizationID)
					return err
				}
			}
		}
	}
	return nil
}
