/**
 * WebSocket组合式函数
 * 用于在Vue组件中方便地使用WebSocket实时数据
 */
import { ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import { initWebSocket, disconnect, subscribeToDevice, getConnectionStatus, reconnect } from '@/utils/websocket'

export function useWebSocket() {
  const isConnected = ref(false)
  const robotPose = ref(null)
  const taskInfo = ref(null)
  const trajectory = ref(null)
  const arriveEvent = ref(null)
  const mapData = ref(null)
  const navigationReply = ref(null)
  const planningReply = ref(null)
  const asmState = ref(null)
  const rawMessages = ref({})

  // 回调函数
  let onConnectCallback = null
  let onDisconnectCallback = null
  let onMessageCallback = null
  let onErrorCallback = null

  // 内部消息处理函数
  function handleMessage(type, data) {
    switch (type) {
      case 'pose':
        robotPose.value = data
        break
      case 'task':
        taskInfo.value = data
        break
      case 'trajectory':
        trajectory.value = data
        break
      case 'arrive':
        arriveEvent.value = data
        break
      case 'map':
        mapData.value = data
        break
      case 'navigation':
        navigationReply.value = data
        break
      case 'planning':
        planningReply.value = data
        break
      case 'asm':
        asmState.value = data
        break
      case 'raw':
        // 存储原始消息
        if (!rawMessages.value[data.topic]) {
          rawMessages.value[data.topic] = []
        }
        rawMessages.value[data.topic].push(data)
        break
    }

    // 触发通用消息回调
    if (onMessageCallback) onMessageCallback(type, data)
  }

  function connect() {
    initWebSocket({
      onConnect: () => {
        isConnected.value = true
        if (onConnectCallback) onConnectCallback()
      },
      onDisconnect: () => {
        isConnected.value = false
        if (onDisconnectCallback) onDisconnectCallback()
      },
      onMessage: handleMessage,
      onError: (error) => {
        if (onErrorCallback) onErrorCallback(error)
      }
    })
  }

  /**
   * 初始化 WebSocket 连接
   * @param {Object} config 配置对象
   * @param {string} config.deviceId 设备ID
   * @param {Function} config.onConnect 连接成功回调
   * @param {Function} config.onDisconnect 断开连接回调
   * @param {Function} config.onMessage 消息接收回调
   * @param {Function} config.onError 错误回调
   */
  function initWebSocketConnection(config = {}) {
    const { deviceId, onConnect, onDisconnect, onMessage, onError } = config

    onConnectCallback = onConnect
    onDisconnectCallback = onDisconnect
    onMessageCallback = onMessage
    onErrorCallback = onError

    initWebSocket({
      deviceId,
      onConnect: () => {
        isConnected.value = true
        if (onConnect) onConnect()
      },
      onDisconnect: () => {
        isConnected.value = false
        if (onDisconnect) onDisconnect()
      },
      onMessage: handleMessage,
      onError: (error) => {
        if (onError) onError(error)
      }
    })
  }

  function switchDevice(newDeviceId) {
    subscribeToDevice(newDeviceId)
  }

  function reconnectWebSocket() {
    reconnect()
  }

  function disconnectWebSocket() {
    disconnect()
  }

  return {
    // 连接状态
    isConnected,

    // 实时数据
    robotPose,
    taskInfo,
    trajectory,
    arriveEvent,
    mapData,
    navigationReply,
    planningReply,
    asmState,
    rawMessages,

    // 方法
    initWebSocket: initWebSocketConnection,
    switchDevice,
    reconnectWebSocket,
    disconnect: disconnectWebSocket,
    getConnectionStatus
  }
}
