package Wxhook

import (
	"context"
	"fmt"
	"github.com/suyuan32/simple-admin-common/enum/errorcode"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"time"
	"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
	}

	var ctype uint64
	if req.Ctype != nil && *req.Ctype != 0 {
		ctype = *req.Ctype
	}

	var hookClient *hook.Hook
	if ctype == 3 {
		hookClient = hook.NewWecomHook("", adminPort, port)
	} else {
		hookClient = hook.NewHook(privateIP, adminPort, port)
	}
	msgId := time.Now().UnixNano() / int64(time.Microsecond)
	l.svcCtx.Rds.Set(l.ctx, fmt.Sprintf("MsgId_FriendId:%d", msgId), *req.Wxid, 10*time.Minute)
	err = hookClient.SendTextMsg(*req.Wxid, *req.Msg, wxInfo.Wxid, msgId)
	if err != nil {
		l.Errorf("发送微信文本消息失败:%v\n", err)
		return nil, err
	}

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

	return resp, nil
}
