// const baseUrl = 'ws://' + window.location.host + '/ws';
const baseUrl = 'ws://' + '192.168.193.1:7710' + '/ws';

export default class WebSocketManager {
  constructor(url, messageHandler) {
    this.url = baseUrl + url; // WebSocket 服务器地址
    this.messageHandler = messageHandler; // 处理推送消息的回调函数
    this.ws = null; // WebSocket 实例
    this.reconnectInterval = 5000; // 重连间隔，单位：毫秒
    this.isConnected = false; // 连接状态
    this.retryCount = 0; // 重试次数
  }

  init() {
    if (this.ws) {
      this.ws.close();
    }

    this.ws = new WebSocket(this.url);

    this.ws.onopen = () => {
      console.log('WebSocket 连接成功');
      this.isConnected = true;
      this.retryCount = 0; 
    };

    this.ws.onmessage = (event) => {
      const index = event.data.indexOf('{');
      const data = JSON.parse(event.data.slice(index, event.data.length) + '');
      this.messageHandler(data.actionId);
    };

    this.ws.onclose = () => {
      console.log('WebSocket 连接关闭');
      this.isConnected = false;
      this.retryConnection();
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket 出错:', error);
      this.isConnected = false;
      this.retryConnection();
    };
  }

  retryConnection() {
    if (this.retryCount < 5) {
      setTimeout(() => {
        console.log('尝试重新连接 WebSocket');
        this.retryCount++;
        this.init();
      }, this.reconnectInterval);
    } else {
      console.error('WebSocket 重新连接失败');
    }
  }

  sendMessage(message) {
    if (this.isConnected && this.ws) {
      this.ws.send(message);
    } else {
      console.log('WebSocket 未连接，无法发送消息');
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
    }
  }
}
