
class WebSocketClient {
    constructor(userId, options = {}) {
      this.system = '3';
      this.userId = userId;
      // const baseURL = import.meta.env.VITE_APP_BASE_API
      const baseURL = 'https://goldshulin.com/prod-api';
      const url = baseURL.split('/')[2];
      const header = baseURL.split('/')[0] === 'https:' ? 'wss' : 'ws';
      this.url = `${header}://${url}/websocket/${this.system}/${this.userId}`;
			console.log("TCL: WebSocketClient -> constructor -> this.url", this.url)
      this.options = {
        reconnectInterval: 3000, // 重连间隔时间
        heartbeatInterval: 30000, // 心跳间隔时间
        heartbeatMessage: 'ping', // 心跳消息
        ...options
      }
      
      this.ws = null
      this.reconnectTimer = null
      this.heartbeatTimer = null
      this.messageCallbacks = new Map()
      this.isConnected = false
      this.isReconnecting = false
    }
  
    // 连接WebSocket
    connect() {
      try {
        this.ws = new WebSocket(this.url)
        this.bindEvents()
      } catch (error) {
        console.error('WebSocket连接错误:', error)
        this.reconnect()
      }
    }
  
    // 绑定事件
    bindEvents() {
      this.ws.onopen = () => {
        console.log('WebSocket连接成功')
        this.isConnected = true
        this.isReconnecting = false
        this.startHeartbeat()
        this.emit('connect')
      }
  
      this.ws.onclose = () => {
        console.log('WebSocket连接关闭')
        this.isConnected = false
        this.stopHeartbeat()
        this.emit('disconnect')
        this.reconnect()
      }
  
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.emit('error', error)
      }
  
      this.ws.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data)
          // 处理心跳响应
          if (message === 'pong') {
            return
          }
          this.handleMessage(message)
        } catch (error) {
          console.error('消息解析错误:', error)
        }
      }
    }
  
    // 重连
    reconnect() {
      if (this.isReconnecting) return
      
      this.isReconnecting = true
      this.reconnectTimer = setTimeout(() => {
        console.log('尝试重新连接...')
        this.connect()
      }, this.options.reconnectInterval)
    }
  
    // 开始心跳
    startHeartbeat() {
      this.heartbeatTimer = setInterval(() => {
        this.send(this.options.heartbeatMessage)
      }, this.options.heartbeatInterval)
    }
  
    // 停止心跳
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer)
        this.heartbeatTimer = null
      }
    }
  
    // 发送消息
    send(data) {
      if (!this.isConnected) {
        console.warn('WebSocket未连接')
        return false
      }
  
      try {
        const message = typeof data === 'string' ? data : JSON.stringify(data)
        this.ws.send(message)
        return true
      } catch (error) {
        console.error('发送消息错误:', error)
        return false
      }
    }
  
    // 处理接收到的消息
    handleMessage(message) {
      const { type, data } = message
      if (this.messageCallbacks.has(type)) {
        this.messageCallbacks.get(type).forEach(callback => callback(data))
      }
      this.emit('message', message)
    }
  
    // 订阅消息
    on(type, callback) {
      if (!this.messageCallbacks.has(type)) {
        this.messageCallbacks.set(type, new Set())
      }
      this.messageCallbacks.get(type).add(callback)
    }
  
    // 取消订阅
    off(type, callback) {
      if (this.messageCallbacks.has(type)) {
        if (callback) {
          this.messageCallbacks.get(type).delete(callback)
        } else {
          this.messageCallbacks.delete(type)
        }
      }
    }
  
    // 事件发射器
    emit(event, data) {
      if (this.messageCallbacks.has(event)) {
        this.messageCallbacks.get(event).forEach(callback => callback(data))
      }
    }
  
    // 关闭连接
    close() {
      if (this.ws) {
        this.ws.close()
      }
      this.stopHeartbeat()
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
    }
  }
  
  // 使用示例
  /*
  const ws = new WebSocketClient('ws://your-websocket-server.com', {
    reconnectInterval: 3000,
    heartbeatInterval: 30000,
    heartbeatMessage: 'ping'
  })
  
  // 连接WebSocket
  ws.connect()
  
  // 监听连接事件
  ws.on('connect', () => {
    console.log('连接成功')
  })
  
  // 监听断开连接事件
  ws.on('disconnect', () => {
    console.log('连接断开')
  })
  
  // 监听错误事件
  ws.on('error', (error) => {
    console.error('发生错误:', error)
  })
  
  // 监听消息事件
  ws.on('message', (message) => {
    console.log('收到消息:', message)
  })
  
  // 订阅特定类型的消息
  ws.on('chat', (data) => {
    console.log('收到聊天消息:', data)
  })
  
  // 发送消息
  ws.send({
    type: 'chat',
    data: {
      content: 'Hello!',
      timestamp: Date.now()
    }
  })
  
  // 关闭连接
  ws.close()
  */
  
  export default WebSocketClient
  