<template>
  <div class="ai-assistant-container">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="back-btn" @click="$router.push('/profile')">
        <span class="back-icon">←</span>
        <span class="back-text">返回</span>
      </div>
      <div class="session-info">
        <div class="info-item">
          <span class="info-label">会话ID:</span>
          <span class="info-value">{{ conversationId }}</span>
        </div>
      </div>
    </div>

    <!-- 聊天主体区域 -->
    <div class="chat-container">
      <div class="chat-messages" ref="chatMessages">
        <!-- 聊天消息列表 -->
        <div v-if="messages.length === 0" class="empty-chat">
          <div class="welcome-message">
            <h3>欢迎使用AI智能助手</h3>
            <p>您可以向我咨询彩票相关的任何问题，我将尽力为您解答！</p>
          </div>
        </div>
        <div v-for="(msg, index) in messages" :key="index" class="message-wrapper" :class="{ 'user-message': msg.type === 'USER', 'ai-message': msg.type === 'AI' }">
          <div class="message-avatar">
            <div v-if="msg.type === 'USER'" class="user-avatar">用户</div>
            <div v-else class="ai-avatar">AI</div>
          </div>
          <div class="message-content">
            <div class="message-bubble" :class="{ 'user-bubble': msg.type === 'USER', 'ai-bubble': msg.type === 'AI' }">
              <div class="message-text" v-html="formatMessage(msg.content)"></div>
              <div v-if="msg.type === 'USER'" class="message-time">{{ msg.time }}</div>
              <div v-else class="message-time">{{ msg.time }}</div>
            </div>
          </div>
        </div>
        
        <!-- 正在输入指示器 -->
        <div v-if="isAITyping" class="message-wrapper ai-message">
          <div class="message-avatar">
            <div class="ai-avatar">AI</div>
          </div>
          <div class="message-content">
            <div class="message-bubble ai-bubble">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input-container">
        <div class="input-wrapper">
          <textarea 
            v-model="userInput" 
            class="chat-input" 
            placeholder="请输入您的问题..." 
            @keydown.enter.prevent="sendMessage"
            :disabled="isAITyping"
            ref="chatInput"
          ></textarea>
          <button 
            class="send-btn" 
            @click="sendMessage" 
            :disabled="!userInput.trim() || isAITyping"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { userStore } from '../store/user'

export default {
  name: 'AIAssistant',
  data() {
    return {
      userInput: '',
      messages: [],
      conversationId: '',
      isAITyping: false,
      eventSource: null
    }
  },
  mounted() {
    // 生成会话ID
    this.generateConversationId()
    // 添加欢迎消息
    this.addAIMessage('您好！我是彩票智能助手，请问有什么可以帮助您的？')
    // 自动聚焦输入框
    this.$nextTick(() => {
      this.$refs.chatInput.focus()
    })
  },
  beforeUnmount() {
    // 组件销毁前关闭SSE连接
    this.closeEventSource()
  },
  methods: {
    // 生成10位随机会话ID
    generateConversationId() {
      const min = 1000000000 // 10位数的最小值
      const max = 9999999999 // 10位数的最大值
      this.conversationId = Math.floor(Math.random() * (max - min + 1) + min).toString()
    },
    
    // 发送消息
    sendMessage() {
      if (!this.userInput.trim() || this.isAITyping) return
      
      // 获取用户ID
      const userId = userStore.user?.id
      if (!userId) {
        this.$router.push('/login')
        return
      }
      
      // 添加用户消息到列表
      this.addUserMessage(this.userInput)
      
      // 保存用户输入并清空输入框
      const message = this.userInput
      this.userInput = ''
      
      // 显示AI正在输入状态
      this.isAITyping = true
      
      // 滚动到底部
      this.scrollToBottom()
      
      // 关闭之前的SSE连接
      this.closeEventSource()
      
      // 创建新的SSE连接
      const url = `http://47.117.22.239:8123/api/chat/sse?message=${encodeURIComponent(message)}&conversationId=${this.conversationId}&userId=${userId}`
      this.eventSource = new EventSource(url)
      
      let aiResponse = ''
      
      this.eventSource.onmessage = (event) => {
        // 将收到的文本添加到响应中
        aiResponse += event.data
        
        // 更新最后一条AI消息或添加新消息
        if (this.messages.length > 0 && this.messages[this.messages.length - 1].type === 'AI') {
          this.messages[this.messages.length - 1].content = aiResponse
        } else {
          this.addAIMessage(aiResponse)
        }
        
        // 滚动到底部
        this.scrollToBottom()
      }
      
      this.eventSource.onerror = (error) => {
        console.error('SSE错误:', error)
        this.isAITyping = false
        this.closeEventSource()
        
        // 如果没有收到任何响应，添加错误消息
        if (!aiResponse) {
          this.addAIMessage('抱歉，服务器连接出现问题，请稍后再试。')
        }
      }
      
      this.eventSource.onopen = () => {
        console.log('SSE连接已打开')
      }
      
      // 添加完成事件处理
      this.eventSource.addEventListener('complete', () => {
        console.log('流式响应完成')
        this.isAITyping = false
        this.closeEventSource()
      })
    },
    
    // 关闭SSE连接
    closeEventSource() {
      if (this.eventSource) {
        this.eventSource.close()
        this.eventSource = null
      }
      this.isAITyping = false
    },
    
    // 添加用户消息
    addUserMessage(content) {
      this.messages.push({
        type: 'USER',
        content: content,
        time: this.getCurrentTime()
      })
    },
    
    // 添加AI消息
    addAIMessage(content) {
      this.messages.push({
        type: 'AI',
        content: content,
        time: this.getCurrentTime()
      })
    },
    
    // 获取当前时间
    getCurrentTime() {
      const now = new Date()
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.chatMessages) {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
        }
      })
    },
    
    // 格式化消息内容（处理换行符等）
    formatMessage(text) {
      if (!text) return ''
      return text.replace(/\n/g, '<br>')
    }
  }
}
</script>

<style scoped>
/* 整体容器样式 */
.ai-assistant-container {
  min-height: 100vh;
  height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
  overflow: hidden;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f44336;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.back-btn:hover {
  opacity: 0.8;
}

.back-icon {
  font-size: 16px;
  font-weight: bold;
}

.back-text {
  font-size: 14px;
  font-weight: 500;
}

.session-info {
  font-size: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.info-label {
  font-weight: 600;
}

.info-value {
  font-family: monospace;
}

/* 聊天区域样式 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  width: 100%;
  height: calc(100vh - 50px); /* 减去顶部导航栏高度 */
  position: relative;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: calc(100vh - 130px); /* 减去顶部导航栏和输入区域的高度 */
}

/* 空聊天时的欢迎消息 */
.empty-chat {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}

.welcome-message {
  text-align: center;
  padding: 30px;
  background: #f0f7ff;
  border-radius: 12px;
  max-width: 80%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.welcome-message h3 {
  color: #4a6fff;
  margin-bottom: 15px;
  font-size: 22px;
}

.welcome-message p {
  color: #666;
  line-height: 1.6;
  font-size: 16px;
}

/* 消息样式 */
.message-wrapper {
  display: flex;
  margin-bottom: 15px;
  animation: fadeIn 0.3s ease;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  margin: 0 10px;
}

.user-avatar {
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ai-avatar {
  background: linear-gradient(135deg, #4a6fff, #6c4aff);
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-bubble {
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  color: white;
  border-top-right-radius: 4px;
}

.ai-bubble {
  background: #f0f7ff;
  color: #333;
  border-top-left-radius: 4px;
}

.message-text {
  line-height: 1.5;
  word-break: break-word;
  font-size: 15px;
}

.message-time {
  font-size: 11px;
  opacity: 0.7;
  text-align: right;
  margin-top: 5px;
}

/* 输入区域样式 */
.chat-input-container {
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  width: 100%;
  box-sizing: border-box;
}

.input-wrapper {
  display: flex;
  gap: 10px;
  position: relative;
}

.chat-input {
  flex: 1;
  border: 1px solid #ced4da;
  border-radius: 24px;
  padding: 12px 20px;
  font-size: 15px;
  resize: none;
  height: 50px;
  max-height: 100px;
  overflow-y: auto;
  background: white;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.chat-input:focus {
  outline: none;
  border-color: #4a6fff;
  box-shadow: 0 0 0 3px rgba(74, 111, 255, 0.1);
}

.chat-input:disabled {
  background: #e9ecef;
  cursor: not-allowed;
}

.send-btn {
  background: linear-gradient(135deg, #4a6fff, #6c4aff);
  color: white;
  border: none;
  border-radius: 24px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
}

.send-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(74, 111, 255, 0.3);
}

.send-btn:disabled {
  background: #cbd3ff;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 正在输入指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 5px 0;
}

.typing-indicator span {
  display: block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6c4aff;
  opacity: 0.7;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
  100% {
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式样式 */
@media (max-width: 768px) {
  .message-content {
    max-width: 80%;
  }
}

@media (max-width: 480px) {
  .chat-messages {
    padding: 15px 10px;
  }
  
  .message-avatar {
    width: 35px;
    height: 35px;
    font-size: 12px;
    margin: 0 5px;
  }
  
  .message-content {
    max-width: 90%;
  }
  
  .message-bubble {
    padding: 10px 12px;
  }
  
  .message-text {
    font-size: 14px;
  }
  
  .welcome-message {
    padding: 20px;
  }
  
  .welcome-message h3 {
    font-size: 18px;
  }
  
  .welcome-message p {
    font-size: 14px;
  }
  
  .chat-input {
    padding: 10px 15px;
    font-size: 14px;
    height: 45px;
  }
  
  .send-btn {
    min-width: 70px;
    padding: 0 15px;
    height: 45px;
    font-size: 13px;
  }
  
  .top-nav {
    padding: 8px 10px;
  }
  
  .back-text {
    font-size: 12px;
  }
  
  .session-info {
    font-size: 11px;
  }
}
</style> 