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 SendPicMsgLocalLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *SendPicMsgLocalLogic) SendPicMsgLocal(req *types.SendPicMsgLocalReq) (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
	}

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

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

	err = hookClient.SendPicMsgLocal(*req.Wxid, *req.Picpath)

	if err != nil {
		l.Error("发送微信图片（本地）失败", err)
		return
	}

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

	return
}
