<template>
  <div class="sse-container">
    <h2>SSE 实时数据连接</h2>
    
    <div class="status-indicator">
      <span class="status-dot" :class="{ connected: isConnected }"></span>
      <span>{{ connectionStatusText }}</span>
    </div>
    
    <div class="controls">
      <button @click="connect" :disabled="isConnected">连接</button>
      <button @click="disconnect" :disabled="!isConnected">断开</button>
      <button @click="clearMessages">清空消息</button>
    </div>
    
    <div class="message-list">
      <div v-if="messages.length === 0" class="empty-message">
        暂无消息，请先连接服务器
      </div>
      
      <div v-for="(msg, index) in messages" :key="index" class="message-item" :class="msg.type">
        <div class="message-header">
          <span class="message-type">{{ msg.type.toUpperCase() }}</span>
          <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
        </div>
        <div class="message-content">{{ msg.content }}</div>
      </div>
    </div>
  </div>
  
  <!-- WebSocket 连接部分 -->
  <div class="ws-container">
    <h2>WebSocket 实时数据连接</h2>
    
    <div class="status-indicator">
      <span class="status-dot" :class="{ connected: isWsConnected }"></span>
      <span>{{ wsConnectionStatusText }}</span>
    </div>
    
    <div class="controls">
      <button @click="connectWs" :disabled="isWsConnected">连接</button>
      <button @click="disconnectWs" :disabled="!isWsConnected">断开</button>
      <button @click="clearWsMessages">清空消息</button>
    </div>
    
    <div class="message-list">
      <div v-if="wsMessages.length === 0" class="empty-message">
        暂无消息，请先连接WebSocket服务器
      </div>
      
      <div v-for="(msg, index) in wsMessages" :key="index" class="message-item" :class="msg.type">
        <div class="message-header">
          <span class="message-type">{{ msg.type.toUpperCase() }}</span>
          <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
        </div>
        <div class="message-content">{{ msg.content }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SSEConnection',
  data() {
    return {
      isConnected: false,
      eventSource: null,
      messages: [],
      retryCount: 0,
      maxRetries: 5,
      retryDelay: 3000,
      // WebSocket相关数据
      isWsConnected: false,
      wsConnection: null,
      wsMessages: [],
      wsRetryCount: 0,
      wsMaxRetries: 5,
      wsRetryDelay: 3000,
    };
  },
  computed: {
    connectionStatusText() {
      return this.isConnected ? '已连接' : '未连接';
    },
    wsConnectionStatusText() {
      return this.isWsConnected ? '已连接' : '未连接';
    }
  },
  methods: {
    async connect() {
      if (this.isConnected) return;
      
      try {
        // 获取JWT token
        const token = localStorage.getItem('token');
        
        // 请求参数
        const requestData = {
         
            message: "压缩空气系统中变频器的应用如何实现节能？",
            user_id: 13817302290,
            session_id: ""/* 35fe2491-dca8-4a1e-b927-43bba0c2b669 */
  
        };

        // 调用接口获取SSE URL
        const response = await fetch('http://192.168.100.187:8062/api/agents/chat/multimodal/ ', {
          method: 'POST',
          mode: 'cors',
          credentials: 'include',
          headers: {
            'Authorization': `JWT ${token}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(requestData)
        });
        
        if (!response.ok) {
          throw new Error('获取SSE URL失败');
        }
        
        // 尝试从响应头获取SSE URL
        console.log('Response Headers:', response.headers);
        console.log('All Headers:', Array.from(response.headers.entries()));
        let sseUrl = response.headers.get('X-Sse-Url');
        
        // 如果响应头中没有，尝试从响应体中获取
        if (!sseUrl) {
          const responseData = await response.json();
          console.log('Response Data:', responseData);
          sseUrl = responseData.data.sse_url || responseData.sse_url;
          if (!sseUrl) {
            throw new Error('未找到SSE URL');
          }
        }
        
        // 将token添加到SSE URL中
        const urlWithToken = `http://192.168.100.187:8062${sseUrl}${sseUrl.includes('?') ? '&' : '?'}token=JWT ${token}`;
        
        this.eventSource = new EventSource(urlWithToken);
        
        // 通用消息处理器
        this.eventSource.onmessage = (event) => {
          console.log('收到SSE消息:', event.data);
          try {
            const data = JSON.parse(event.data);
            let messageContent = '';
            let messageType = 'message';

            switch(data.type) {
              case 'connected':
                messageContent = `已连接 - 会话ID: ${data.session_id}`;
                messageType = 'system';
                break;
              case 'heartbeat':
                // 不显示心跳消息
                return;
              case 'thinking_step':
                messageContent = data.data.content;
                messageType = 'thinking';
                break;
              case 'completed':
                messageContent = '会话已完成';
                messageType = 'system';
                break;
              default:
                messageContent = JSON.stringify(data);
            }

            if (messageContent) {
              this.addMessage(messageContent, messageType);
            }
          } catch (error) {
            console.error('解析SSE消息失败:', error);
            this.addMessage(`消息解析错误: ${error.message}`, 'error');
          }
        };
        
        // 自定义事件处理器
        this.eventSource.addEventListener('status', (event) => {
          const data = JSON.parse(event.data);
          this.addMessage(`状态更新: ${data.status}`, 'status');
        });
        
        this.eventSource.addEventListener('error', (event) => {
          this.addMessage(`错误: ${event.message || '连接错误'}`, 'error');
        });
        
        // 错误处理
        this.eventSource.onerror = (error) => {
          if (this.eventSource.readyState === EventSource.CLOSED) {
            this.addMessage('连接已关闭', 'system');
          } else {
            this.addMessage(`连接错误: ${error.message}`, 'error');
            this.attemptReconnect();
          }
        };
        
        this.isConnected = true;
        this.retryCount = 0;
        this.addMessage('成功连接到SSE服务器', 'system');
      } catch (error) {
        this.addMessage(`连接失败: ${error.message}`, 'error');
        this.attemptReconnect();
      }
    },
    
    disconnect() {
      if (this.eventSource) {
        this.eventSource.close();
        this.eventSource = null;
        this.isConnected = false;
        this.addMessage('已手动断开连接', 'system');
      }
    },
    
    attemptReconnect() {
      if (this.retryCount < this.maxRetries) {
        this.retryCount++;
        this.addMessage(`尝试重新连接 (${this.retryCount}/${this.maxRetries})...`, 'system');
        
        setTimeout(() => {
          this.connect();
        }, this.retryDelay);
      } else {
        this.addMessage('达到最大重试次数，停止尝试连接', 'error');
        this.isConnected = false;
      }
    },
    
    addMessage(content, type = 'message') {
      this.messages.unshift({
        content,
        type,
        timestamp: new Date()
      });
      
      // 限制消息数量
      if (this.messages.length > 100) {
        this.messages.pop();
      }
    },
    
    clearMessages() {
      this.messages = [];
    },
    
    formatTime(date) {
      return date.toLocaleTimeString();
    },
    
    // WebSocket相关方法
    async connectWs() {
      if (this.isWsConnected) return;
      
      try {
        const token = localStorage.getItem('token');
        const wsUrl = `ws://192.168.100.187:8062/ws/thinking/13/35fe2491-dca8-4a1e-b927-43bba0c2b669/?token=JWT ${token}`;
        
        this.wsConnection = new WebSocket(wsUrl);
        
        this.wsConnection.onopen = () => {
          this.isWsConnected = true;
          this.wsRetryCount = 0;
          this.addWsMessage('成功连接到WebSocket服务器', 'system');
        };
        
        this.wsConnection.onmessage = (event) => {
          console.log('收到WebSocket消息:', event.data);
          try {
            const data = JSON.parse(event.data);
            let messageContent = '';
            let messageType = 'message';

            switch(data.type) {
              case 'connected':
                messageContent = `已连接 - 会话ID: ${data.session_id}`;
                messageType = 'system';
                break;
              case 'thinking_step':
                messageContent = data.data.content;
                messageType = 'thinking';
                break;
              case 'completed':
                messageContent = '会话已完成';
                messageType = 'system';
                break;
              default:
                messageContent = JSON.stringify(data);
            }

            if (messageContent) {
              this.addWsMessage(messageContent, messageType);
            }
          } catch (error) {
            console.error('解析WebSocket消息失败:', error);
            this.addWsMessage(`消息解析错误: ${error.message}`, 'error');
          }
        };
        
        this.wsConnection.onerror = (error) => {
          this.addWsMessage(`连接错误: ${error.message || '未知错误'}`, 'error');
          this.attemptWsReconnect();
        };
        
        this.wsConnection.onclose = () => {
          this.isWsConnected = false;
          this.addWsMessage('连接已关闭', 'system');
        };
        
      } catch (error) {
        this.addWsMessage(`连接失败: ${error.message}`, 'error');
        this.attemptWsReconnect();
      }
    },
    
    disconnectWs() {
      if (this.wsConnection) {
        this.wsConnection.close();
        this.wsConnection = null;
        this.isWsConnected = false;
        this.addWsMessage('已手动断开连接', 'system');
      }
    },
    
    attemptWsReconnect() {
      if (this.wsRetryCount < this.wsMaxRetries) {
        this.wsRetryCount++;
        this.addWsMessage(`尝试重新连接 (${this.wsRetryCount}/${this.wsMaxRetries})...`, 'system');
        
        setTimeout(() => {
          this.connectWs();
        }, this.wsRetryDelay);
      } else {
        this.addWsMessage('达到最大重试次数，停止尝试连接', 'error');
        this.isWsConnected = false;
      }
    },
    
    addWsMessage(content, type = 'message') {
      this.wsMessages.unshift({
        content,
        type,
        timestamp: new Date()
      });
      
      // 限制消息数量
      if (this.wsMessages.length > 100) {
        this.wsMessages.pop();
      }
    },
    
    clearWsMessages() {
      this.wsMessages = [];
    },
  },
  
  beforeUnmount() {
    // 组件卸载前关闭所有连接
    if (this.eventSource) {
      this.eventSource.close();
    }
    if (this.wsConnection) {
      this.wsConnection.close();
    }
  }
};
</script>

<style scoped>
.sse-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 15px 0;
  font-size: 1.1em;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #ccc;
}

.status-dot.connected {
  background-color: #4CAF50;
  box-shadow: 0 0 8px #4CAF50;
}

.controls {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.controls button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: #f0f0f0;
  transition: background-color 0.3s;
}

.controls button:hover {
  background-color: #e0e0e0;
}

.controls button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.message-list {
  border: 1px solid #eee;
  border-radius: 4px;
  max-height: 500px;
  overflow-y: auto;
  padding: 10px;
}

.empty-message {
  text-align: center;
  padding: 20px;
  color: #888;
}

.message-item {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f9f9f9;
  border-left: 4px solid #ddd;
}

.message-item.system {
  border-left-color: #2196F3;
}

.message-item.status {
  border-left-color: #4CAF50;
}

.message-item.error {
  border-left-color: #f44336;
}

.message-item.thinking {
  border-left-color: #9c27b0;
  background-color: #f3e5f5;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9em;
  color: #666;
}

.message-type {
  font-weight: bold;
}

.message-content {
  word-break: break-word;
}

.ws-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
  border-top: 1px solid #eee;
}
</style>