package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/url"
	"time"

	"github.com/gorilla/websocket"
)

// Request 结构体定义
type Request struct {
	Type      string      `json:"type"`
	UUID      string      `json:"uuid"`
	CommandID string      `json:"commandId"`
	Parameter interface{} `json:"parameter"`
}

// Response 结构体定义
type Response struct {
	CommandID string            `json:"commandId"`
	ErrorCode string            `json:"errorCode"`
	Results   map[string]string `json:"results"`
	Status    string            `json:"status"`
	Time      int64             `json:"time"`
	Type      string            `json:"type"`
	UUID      string            `json:"uuid"`
}

// SendWebsocketRequest 发送WebSocket请求并返回sn字段的值
func SendWebsocketRequest(serverURL, path string, request Request) (string, error) {
	// 构建WebSocket连接URL
	u := url.URL{Scheme: "ws", Host: serverURL, Path: path}

	// 创建一个Dialer实例，用于建立WebSocket连接
	dialer := websocket.Dialer{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		// 可选：设置超时等
		HandshakeTimeout: 5 * time.Second,
	}

	// 建立WebSocket连接
	conn, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		return "", fmt.Errorf("dial: %w", err)
	}
	defer conn.Close()

	// 将请求JSON编码为字节
	requestJSON, err := json.Marshal(request)
	if err != nil {
		return "", fmt.Errorf("marshal request: %w", err)
	}

	// 发送WebSocket消息
	err = conn.WriteMessage(websocket.TextMessage, requestJSON)
	if err != nil {
		return "", fmt.Errorf("write: %w", err)
	}

	// 读取WebSocket响应
	_, responseBytes, err := conn.ReadMessage()
	if err != nil {
		return "", fmt.Errorf("read: %w", err)
	}

	// 将响应字节解码为JSON
	var response Response
	err = json.Unmarshal(responseBytes, &response)
	if err != nil {
		return "", fmt.Errorf("unmarshal response: %w", err)
	}

	// 返回sn字段的值
	return response.Results["sn"], nil
}

func main() {
	// 示例使用
	serverURL := "192.168.1.104:9002"
	path := "/"
	request := Request{
		Type:      "request",
		UUID:      "",
		CommandID: "getRobotBaseInfo",
		Parameter: nil,
	}

	sn, err := SendWebsocketRequest(serverURL, path, request)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("SN: %s", sn)
}
