package Wxhook

import (
	"context"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/hook"

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

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *RefreshLoginQRLogic) RefreshLoginQR(req *types.RefreshLoginQRReq) (resp *types.RefreshLoginQRResp, err error) {
	//wxInfo, err := l.svcCtx.DB.Wx.Query().Where(wx.ServerIDEQ(*req.ServerId)).Where(wx.PortEQ(*req.Port)).Limit(1).Only(l.ctx)
	//if err != nil {
	//	l.Error("查询微信信息失败", err)
	//	return
	//}

	// 获取服务器信息
	server, err := l.svcCtx.DB.Server.Get(l.ctx, *req.ServerId)
	if err != nil {
		l.Error("获取服务器信息失败", err)
		return
	}
	hookClient := hook.NewHook(server.PrivateIP, server.AdminPort, *req.Port)
	//_, _ = hookClient.TerminateThisWeChat(wxInfo.ProcessID)
	// 如端口未被占用则启动微信
	portOccupied, err := hookClient.GetPortOccupiedInfo(*req.Port)
	if err != nil {
		l.Error("获取端口占用信息失败", err)
		return nil, err
	}
	if portOccupied.Occupied != "1" {
		l.Info("端口未被占用，启动微信")
		start, err := hookClient.StartWechat(*req.Port)
		if err != nil {
			l.Error("启动微信失败", err)
			return nil, err
		}
		if start.Success != "1" {
			err = errorx.NewDefaultError("微信启动失败")
			return nil, err
		}
	}

	loginStatus, err := hookClient.IsLoginStatus()
	if err != nil {
		l.Error("查询登录状态失败", err)
		return nil, errorx.NewDefaultError("查询登录状态失败")
	}
	resp = &types.RefreshLoginQRResp{}
	resp.Msg = errormsg.Success
	resp.Data = types.LoginQRStatus{
		Status:     loginStatus.Onlinestatus,
		StatusDesc: loginStatus.Msg,
	}

	if loginStatus.Onlinestatus == "5" {
		err = hookClient.RefreshLoginQRCode()
		if err != nil {
			return nil, err
		}
	}

	if loginStatus.Onlinestatus == "0" || loginStatus.Onlinestatus == "5" {
		LoginQRCode, err := hookClient.GetLoginQRCode()
		if err != nil {
			return nil, err
		}
		if LoginQRCode.Base64 == "" {
			err = errorx.NewDefaultError("二维码获取失败")
			return nil, err
		}
		resp.Data.QRCode = LoginQRCode.Base64
		resp.Data.StatusDesc = "扫码登陆"
		return resp, nil
	}

	return resp, nil
}
