package Wxhook

import (
	"context"
	"github.com/suyuan32/simple-admin-common/enum/errorcode"
	"math/rand"
	"strconv"
	"time"
	"wechat-api/hook"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *LogoutLogic) Logout(req *types.IDReq) (resp *types.BaseMsgResp, err error) {
	wxInfo, err := l.svcCtx.DB.Wx.Get(l.ctx, req.Id)
	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)
	logout, err := hookClient.Logout()
	if err != nil {
		l.Error("退出登录失败", err)
		return
	}
	//  在下面生成一个随机数
	tmpWxid := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(1000000)
	l.svcCtx.DB.Wx.UpdateOne(wxInfo).
		SetStatus(0).
		SetWxid("temp-" + strconv.Itoa(tmpWxid)).
		Save(l.ctx)

	resp = &types.BaseMsgResp{
		Msg: logout.Msg,
	}
	if logout.Code == "1" {
		resp.Code = errorcode.OK
	} else {
		resp.Code = errorcode.Unknown
	}
	_, _ = hookClient.TerminateThisWeChat(wxInfo.ProcessID)
	return
}
