// WebSocket 连接管理类
class WebSocketManager {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000 // 3秒后重连
    this.listeners = {}
    this.isConnecting = false
    this.severName = 'ai';
// 定义WebSocket连接的URL
    this.webSocketUrl = `ws://192.168.2.53:8080/ws/${this.severName}`;
  }

  // 初始化WebSocket连接
  init() {
    const url = this.webSocketUrl
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket连接已存在')
      return
    }

    if (this.isConnecting) return
    this.isConnecting = true

    try {
      this.ws = new WebSocket(url)
      
      this.ws.onopen = () => {
        console.log('WebSocket连接已建立')
        this.isConnecting = false
        this.reconnectAttempts = 0
        this.emit('open')
      }

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          this.emit('message', data)
          // 可以根据消息类型分发到不同的监听器
          if (data.type) {
            this.emit(`message:${data.type}`, data)
          }
        } catch (error) {
          console.error('WebSocket消息解析错误:', error)
          this.emit('error', error)
        }
      }

      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        this.isConnecting = false
        this.emit('close')
        this.attemptReconnect(url)
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
        this.isConnecting = false
        this.emit('error', error)
      }
    } catch (error) {
      console.error('WebSocket初始化失败:', error)
      this.isConnecting = false
      this.attemptReconnect(url)
    }
  }

  // 重连机制
  attemptReconnect(url) {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数已达上限')
      return
    }

    this.reconnectAttempts++
    console.log(`WebSocket将在${this.reconnectInterval}ms后尝试第${this.reconnectAttempts}次重连`)
    
    setTimeout(() => {
      this.init(url)
    }, this.reconnectInterval)
  }

  // 发送消息
  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      const message = typeof data === 'string' ? data : JSON.stringify(data)
      this.ws.send(message)
      return true
    }
    console.error('WebSocket连接未建立，无法发送消息')
    return false
  }

  // 关闭连接
  close() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  // 事件监听相关方法
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = []
    }
    this.listeners[event].push(callback)
  }

  off(event, callback) {
    if (this.listeners[event]) {
      if (callback) {
        this.listeners[event] = this.listeners[event].filter(cb => cb !== callback)
      } else {
        delete this.listeners[event]
      }
    }
  }

  emit(event, data) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error(`WebSocket事件${event}处理错误:`, error)
        }
      })
    }
  }

  // 获取连接状态
  getReadyState() {
    return this.ws ? this.ws.readyState : WebSocket.CLOSED
  }

  // 连接是否打开
  isOpen() {
    return this.getReadyState() === WebSocket.OPEN
  }
}


// 创建单例WebSocket管理器实例
const wsManager = new WebSocketManager()
// 将WebSocket管理器挂载到Vue原型上，使其在所有组件中可用
Vue.prototype.$ws = wsManager

// 导出WebSocket管理器实例供其他模块使用
export { wsManager }