package Wxhook

import (
	"context"
	"github.com/suyuan32/simple-admin-common/enum/errorcode"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/ent/predicate"
	"wechat-api/ent/wx"
	"wechat-api/hook"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *SendTextMsgLogic) SendTextMsg(req *types.SendTextMsgReq) (resp *types.BaseMsgResp, err error) {

	//根据wx实体的wxid查询
	var predicates []predicate.Wx
	if req.WxWxid != nil {
		predicates = append(predicates, wx.WxidContains(*req.WxWxid))
	}

	wxInfo, err := l.svcCtx.DB.Wx.Query().Where(predicates...).Only(l.ctx)

	//根据wx实体的主键ID查询
	//wxInfo, err := l.svcCtx.DB.Wx.Get(l.ctx, *req.AgentWxId)

	l.Infof("wxInfo = %v", wxInfo)

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

	privateIP := ""
	adminPort := ""
	port := ""

	if wxInfo.ServerID != 0 {
		serverInfo, err := l.svcCtx.DB.Server.Get(l.ctx, wxInfo.ServerID)
		if err != nil {
			l.Error("查询服务器信息失败", err)
			return nil, err
		}
		privateIP = serverInfo.PrivateIP
		adminPort = serverInfo.AdminPort
		port = wxInfo.Port
	}

	hookClient := hook.NewHook(privateIP, adminPort, port)

	err = hookClient.SendTextMsg(*req.Wxid, *req.Msg, wxInfo.Wxid)

	if err != nil {
		l.Error("发送微信文本消息失败", err)
		return nil, err
	}

	resp = &types.BaseMsgResp{
		Msg:  errormsg.Success,
		Code: errorcode.OK,
	}

	return resp, nil
}
