// utils/webSocketService.ts
import { ref, Ref, onUnmounted } from 'vue'
import { Uni } from '@dcloudio/uni-app'

// 消息订阅回调函数类型
type MessageCallback = (message: string) => void

// WebSocket服务接口
interface WebSocketService {
  connected: Ref<boolean>
  connectionStatus: Ref<string>
  messages: Ref<any[]>
  connectWebSocket: (url: string, destination: string) => void
  disconnectWebSocket: () => void
  subscribe: (callback: MessageCallback) => () => void
  sendMessage: (destination: string, content: string) => void
}

// 存储单例WebSocket服务
let webSocketServiceInstance: WebSocketService | null = null

/**
 * 创建或获取全局WebSocket服务实例
 */
export default function useWebSocketService(): WebSocketService {
  // 如果实例已存在，直接返回
  if (webSocketServiceInstance) {
    return webSocketServiceInstance
  }

  // WebSocket状态
  const connected = ref(false)
  const connectionStatus = ref('未连接')
  const messages = ref<any[]>([])
  let socketTask: UniApp.SocketTask | null = null
  let subscribers: MessageCallback[] = [] // 存储消息订阅者

  // STOMP帧构建器
  const buildStompFrame = (command: string, headers: Record<string, string> = {}, body: string = '') => {
    let frame = `${command}\n`
    for (const [key, value] of Object.entries(headers)) {
      frame += `${key}:${value}\n`
    }
    frame += `\n${body}`
    return frame + '\x00'
  }

  // 连接WebSocket
  const connectWebSocket = (url: string, destination: string) => {
    if (connected.value) return

    connectionStatus.value = '连接中...'

    if (socketTask) {
      socketTask.close({})
      socketTask = null
    }

    socketTask = uni.connectSocket({
      url: url,
      protocols: ['v12.stomp', 'v11.stomp'],
      success: () => {
        console.log('开始连接WebSocket')
      },
      fail: (err) => {
        console.error('连接失败:', err)
        connectionStatus.value = '连接失败'
      }
    })

    // 只注册一次全局事件监听器
    socketTask.onOpen((res) => {
      console.log('WebSocket连接已打开', res)
      connected.value = true
      connectionStatus.value = '连接中...'

      // 发送STOMP CONNECT帧
      const connectFrame = buildStompFrame('CONNECT', {
        'accept-version': '1.2',
        'heart-beat': '10000,10000'
      })

      socketTask?.send({
        data: connectFrame
      })
    })

    // 监听消息
    socketTask.onMessage((res) => {
      const data = res.data as string
      const [commandLine, ...headerLines] = data.split('\n')
      const emptyLineIndex = headerLines.findIndex(line => line === '')
      const headers: Record<string, string> = {}

      for (let i = 0; i < emptyLineIndex; i++) {
        const [key, value] = headerLines[i].split(':')
        headers[key] = value
      }

      const body = headerLines.slice(emptyLineIndex + 1).join('\n').replace(/\x00$/, '')

      switch (commandLine) {
        case 'CONNECTED':
          connectionStatus.value = 'STOMP已连接'
          // 订阅主题
          const subscribeFrame = buildStompFrame('SUBSCRIBE', {
            id: 'sub-0',
            destination: destination
          })

          socketTask?.send({
            data: subscribeFrame
          })
          break

        case 'MESSAGE':
          // 通知所有订阅者
          subscribers.forEach(subscriber => {
            subscriber(body)
          })
          break

        case 'ERROR':
          console.error('服务器错误:', body)
          break
      }
    })

    // 监听错误
    socketTask.onError((err) => {
      console.error('WebSocket错误:', err)
      connectionStatus.value = '连接错误'
      connected.value = false
    })

    // 监听关闭
    socketTask.onClose((closeRes) => {
      console.log('WebSocket连接已关闭', closeRes)
      connectionStatus.value = '已断开'
      connected.value = false
    })
  }

  // 断开WebSocket
  const disconnectWebSocket = () => {
    if (socketTask) {
      // 发送STOMP DISCONNECT帧
      const disconnectFrame = buildStompFrame('DISCONNECT', {
        receipt: 'disconnect-receipt'
      })

      socketTask.send({
        data: disconnectFrame,
        success: () => {
          socketTask?.close({
            code: 1000,
            reason: '用户手动关闭',
            success: () => {
              connected.value = false
              connectionStatus.value = '已断开'
            }
          })
        }
      })
    }
  }

  // 订阅消息
  const subscribe = (callback: MessageCallback) => {
    subscribers.push(callback)
    // 返回取消订阅函数
    return () => {
      subscribers = subscribers.filter(sub => sub !== callback)
    }
  }

  // 发送消息
  const sendMessage = (destination: string, content: string) => {
    if (!socketTask || !connected.value) {
      console.error('WebSocket未连接')
      return
    }

    // 构建STOMP SEND帧
    const sendFrame = buildStompFrame('SEND', {
      destination: destination,
      'content-type': 'text/plain'
    }, content)

    socketTask.send({
      data: sendFrame
    })
  }

  // 创建服务实例
  const service: WebSocketService = {
    connected,
    connectionStatus,
    messages,
    connectWebSocket,
    disconnectWebSocket,
    subscribe,
    sendMessage
  }

  // 存储单例
  webSocketServiceInstance = service

  return service
}