// src/utils/websocket.js
import { wsConfig } from "@/config";
class WebSocketClient {
    constructor(url) {
      this.url = url;
      this.ws = null;
      this.reconnectTimeout = null;
    }
  
    // 初始化 WebSocket 连接
    connect(callback) {
      if (this.ws) {
        console.warn("WebSocket 已经连接");
        return;
      }
  
      this.ws = new WebSocket(this.url);
  
      // 连接成功
      this.ws.onopen = () => {
        console.log("WebSocket 连接成功:", this.url);
        if (callback) callback(true);
      };
  
      // 接收消息
      this.ws.onmessage = (event) => {
        console.log("收到 WebSocket 消息:", event.data);
      };
  
      // 连接关闭
      this.ws.onclose = () => {
        console.log("WebSocket 连接关闭，尝试重连...");
        this.ws = null;
        this.reconnect();
      };
  
      // 连接错误
      this.ws.onerror = (error) => {
        console.error("WebSocket 错误:", error);
        this.ws.close();
      };
    }
  
    // 发送消息
    sendMessage(message) {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(message);
      } else {
        console.warn("WebSocket 未连接，消息发送失败");
      }
    }
  
    // 关闭 WebSocket
    close() {
      if (this.ws) {
        this.ws.close();
      }
    }
  
    // 断线重连
    reconnect() {
      if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = setTimeout(() => {
        console.log("尝试重新连接 WebSocket...");
        this.connect();
      }, 3000);
    }
  }
  
  // 导出 WebSocket 客户端
  export const wsClient = new WebSocketClient(wsConfig.equipmentList);
  //导出树状结构WebSocket客户端
  export const wsClientTree = new WebSocketClient(wsConfig.equipmentTree);