import { Client } from '@stomp/stompjs'
import { ref } from 'vue'

// 解决 global 未定义问题
if (typeof global === 'undefined') {
  window.global = window
}

export function useWebSocket() {
  const isConnected = ref(false)
  const userId = ref(`user_${Math.random().toString(36).substr(2, 9)}`)
  const broadcastMessages = ref([])
  const userMessages = ref([])
  let stompClient = null

  // 连接WebSocket
  const connect = () => {
    const url = 'ws://localhost:9020/ws' // 端口改为9020
    stompClient = new Client({
      brokerURL: url,
      reconnectDelay: 5000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
      onConnect: () => {
        isConnected.value = true

        // 订阅广播频道
        stompClient.subscribe('/topic/broadcast', (message) => {
          broadcastMessages.value.push({
            content: message.body,
            timestamp: new Date().toLocaleTimeString()
          })
        })

        // 订阅个人频道
        stompClient.subscribe(`/user/queue/user`, (message) => {
          userMessages.value.push({
            content: message.body,
            timestamp: new Date().toLocaleTimeString()
          })
        })
      },
      onStompError: (frame) => {
        console.error('Broker reported error: ' + frame.headers['message'])
        console.error('Additional details: ' + frame.body)
      },
      onWebSocketClose: () => {
        isConnected.value = false
      }
    })

    stompClient.activate()
  }

  // 断开连接
  const disconnect = () => {
    if (stompClient) {
      stompClient.deactivate()
      isConnected.value = false
    }
  }

  // 清空广播消息
  const clearBroadcastMessages = () => {
    broadcastMessages.value = []
  }

  // 清空用户消息
  const clearUserMessages = () => {
    userMessages.value = []
  }

  return {
    broadcastMessages,
    userMessages,
    isConnected,
    userId,
    connect,
    disconnect,
    clearBroadcastMessages,
    clearUserMessages
  }
}
