export class WebSocketManager {
  constructor(url, callback) {
      this.url = url
      this.callback = callback
      this.socket = null
      this.connected = false
      this.error = null
  }

  connect() {
      if (this.socket && this.socket.readyState === WebSocket.OPEN) {
          return
      }
      this.socket = new WebSocket(this.url);
      console.log("🚀 ~ WebSocketClient ~ connect ~ this.url:", this.url)
      // 连接成功
      this.socket.onopen = () => {
          console.log('WebSocket connected')
          this.connected = true
      }
      this.socket.onmessage = (event) => {
          console.log('message', event)
          this.callback(event.data)
      }
      this.socket.onerror = (event) => {
          console.error('WebSocket error:', event)
          this.error = event
      }
      this.socket.onclose = () => {
          console.log('WebSocket closed')
          this.connected = false
      }
  }

  disconnect() {
      if (this.socket) {
          this.socket.close()
      }
  }

  sendMessage(message) {
      if (this.socket.readyState !== WebSocket.OPEN) {
          return
      }
      this.socket.send(JSON.stringify(message))
  }

  // sendApiRequest() {
  //     axios.get(this.apiEndpoint).then(response => {
  //         // 处理 API 返回数据并发送给服务端
  //         const data = response.data
  //         this.sendMessage(data)
  //     }).catch(error => {
  //         console.error('API request error:', error)
  //     })
  // }
}