<template>
  <div class="p-6 max-w-4xl mx-auto">
    <h1 class="text-2xl font-bold mb-6">WebSocket连接测试</h1>
    
    <!-- 连接状态 -->
    <div class="mb-6 p-4 rounded-lg" :class="statusClass">
      <h2 class="text-lg font-semibold mb-2">连接状态</h2>
      <p>状态: {{ connectionStatus }}</p>
      <p>WebSocket URL: {{ wsUrl }}</p>
      <p>用户ID: {{ userId }}</p>
    </div>

    <!-- 控制按钮 -->
    <div class="mb-6 space-x-4">
      <button 
        @click="connect" 
        :disabled="isConnected"
        class="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
      >
        连接
      </button>
      <button 
        @click="disconnect" 
        :disabled="!isConnected"
        class="px-4 py-2 bg-red-500 text-white rounded disabled:opacity-50"
      >
        断开
      </button>
      <button 
        @click="clearLogs"
        class="px-4 py-2 bg-gray-500 text-white rounded"
      >
        清空日志
      </button>
    </div>

    <!-- 发送消息 -->
    <div class="mb-6">
      <h2 class="text-lg font-semibold mb-2">发送消息</h2>
      <div class="flex space-x-2">
        <input 
          v-model="messageInput"
          @keyup.enter="sendMessage"
          placeholder="输入测试消息..."
          class="flex-1 px-3 py-2 border rounded"
          :disabled="!isConnected"
        >
        <button 
          @click="sendMessage"
          :disabled="!isConnected || !messageInput.trim()"
          class="px-4 py-2 bg-green-500 text-white rounded disabled:opacity-50"
        >
          发送
        </button>
      </div>
    </div>

    <!-- 日志 -->
    <div class="mb-6">
      <h2 class="text-lg font-semibold mb-2">连接日志</h2>
      <div class="bg-gray-100 p-4 rounded-lg h-64 overflow-y-auto">
        <div v-for="(log, index) in logs" :key="index" class="mb-1 text-sm">
          <span class="text-gray-500">{{ log.timestamp }}</span>
          <span :class="log.type === 'error' ? 'text-red-600' : log.type === 'success' ? 'text-green-600' : 'text-blue-600'">
            [{{ log.type.toUpperCase() }}]
          </span>
          {{ log.message }}
        </div>
      </div>
    </div>

    <!-- 接收到的消息 -->
    <div>
      <h2 class="text-lg font-semibold mb-2">接收到的消息</h2>
      <div class="bg-gray-100 p-4 rounded-lg h-64 overflow-y-auto">
        <div v-for="(message, index) in receivedMessages" :key="index" class="mb-2 p-2 bg-white rounded">
          <div class="text-xs text-gray-500 mb-1">{{ message.timestamp }}</div>
          <pre class="text-sm">{{ JSON.stringify(message.data, null, 2) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { stompWebSocketService as webSocketService, type WebSocketMessage } from '@/services/stomp-websocket'
import { envConfig } from '@/config/env'

// 响应式数据
const connectionStatus = ref('DISCONNECTED')
const isConnected = computed(() => connectionStatus.value === 'CONNECTED')
const messageInput = ref('')
const logs = ref<Array<{timestamp: string, type: string, message: string}>>([])
const receivedMessages = ref<Array<{timestamp: string, data: any}>>([])

// 配置
const wsUrl = `${envConfig.apiBaseUrl.replace('http', 'ws').replace('/api', '')}/ws/chat`
const userId = ref(`test_user_${Date.now()}`)

// 计算样式类
const statusClass = computed(() => {
  switch (connectionStatus.value) {
    case 'CONNECTED':
      return 'bg-green-100 border border-green-300'
    case 'CONNECTING':
      return 'bg-yellow-100 border border-yellow-300'
    case 'ERROR':
      return 'bg-red-100 border border-red-300'
    default:
      return 'bg-gray-100 border border-gray-300'
  }
})

// 添加日志
const addLog = (type: string, message: string) => {
  logs.value.push({
    timestamp: new Date().toLocaleTimeString(),
    type,
    message
  })
}

// 连接WebSocket
const connect = async () => {
  try {
    addLog('info', '开始连接WebSocket...')
    
    await webSocketService.connect(userId.value, {
      onConnect: () => {
        addLog('success', 'WebSocket连接成功')
        connectionStatus.value = 'CONNECTED'
      },
      onDisconnect: () => {
        addLog('info', 'WebSocket连接断开')
        connectionStatus.value = 'DISCONNECTED'
      },
      onError: (error) => {
        addLog('error', `WebSocket错误: ${error.userMessage || error.message || '未知错误'}`)
        connectionStatus.value = 'ERROR'
      },
      onStatusChange: (status) => {
        connectionStatus.value = status
        addLog('info', `连接状态变更: ${status}`)
      },
      onMessage: (message: WebSocketMessage) => {
        addLog('success', `收到消息: ${message.type} - ${message.content}`)
        receivedMessages.value.push({
          timestamp: new Date().toLocaleTimeString(),
          data: message
        })
      }
    })
  } catch (error) {
    addLog('error', `连接失败: ${error}`)
  }
}

// 断开连接
const disconnect = () => {
  webSocketService.disconnect()
  addLog('info', '主动断开连接')
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return
  
  try {
    webSocketService.sendChatMessage(messageInput.value.trim())
    addLog('info', `发送消息: ${messageInput.value.trim()}`)
    messageInput.value = ''
  } catch (error) {
    addLog('error', `发送消息失败: ${error}`)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
  receivedMessages.value = []
}

// 生命周期
onMounted(() => {
  addLog('info', 'WebSocket测试页面已加载')
  addLog('info', `WebSocket URL: ${wsUrl}`)
})

onUnmounted(() => {
  if (isConnected.value) {
    disconnect()
  }
})
</script>
