<template>
  <div class="chat-container">
    <!-- 聊天历史区域 -->
    <div class="chat-history" ref="chatHistory">
      <div
        v-for="(msg, index) in history"
        :key="index"
        :class="['message', msg.sender]"
      >
        <!-- 消息头像 -->
        <div class="avatar">
          <div v-if="msg.sender === 'user'" class="user-avatar">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path
                d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10zm0 2c-5.523 0-10 4.477-10 10h20c0-5.523-4.477-10-10-10z"
              />
            </svg>
          </div>
          <div v-else class="ai-avatar">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path d="M20 9V6H4v3h16zm0 5v-2H4v2h16zm-8 5v-2H4v2h8z" />
            </svg>
          </div>
        </div>

        <!-- 消息内容区域 -->
        <div class="message-content">
          <div class="sender">
            {{ msg.sender === 'user' ? 'You' : 'AI Assistant' }}
          </div>
          <div class="content">
            <div
              v-if="
                msg.sender === 'assistant' &&
                index === history.length - 1 &&
                loading
              "
              class="loading-indicator"
            >
              <div class="dot-flashing"></div>
              <span>Thinking...</span>
            </div>
            <div v-else>{{ msg.content }}</div>
          </div>
          <div class="timestamp">{{ formatTimestamp(msg.timestamp) }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="Type your message..."
          :disabled="loading"
        />
        <button
          @click="sendMessage"
          :disabled="loading || !inputMessage.trim()"
        >
          <svg
            v-if="loading"
            xmlns="http://www.w3.org/2000/svg"
            class="spinner"
            viewBox="0 0 24 24"
          >
            <circle
              cx="12"
              cy="12"
              r="10"
              fill="none"
              stroke="currentColor"
              stroke-width="4"
            ></circle>
          </svg>
          <span v-else>Send</span>
        </button>
      </div>
      <div class="hint-text">Press Enter to send</div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { baseURL } from '@/utils/request'

const inputMessage = ref('')
const sessionToken = ref('')
const history = ref([])
const loading = ref(false)
const chatHistory = ref(null)

// 添加时间戳到消息
const appendToHistory = (content, sender) => {
  history.value.push({
    content,
    sender,
    timestamp: new Date()
  })
  scrollToBottom()
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatHistory.value) {
      chatHistory.value.scrollTop = chatHistory.value.scrollHeight
    }
  })
}

// 处理窗口大小变化
const handleResize = () => {
  scrollToBottom()
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
  scrollToBottom()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 格式化时间戳
const formatTimestamp = (date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return

  const userMessage = inputMessage.value
  appendToHistory(userMessage, 'user')
  inputMessage.value = ''
  loading.value = true

  try {
    const response = await fetch(baseURL + '/chat/ask', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        content: userMessage,
        sessionToken: sessionToken.value
      })
    })

    if (!response.body) throw new Error('No response body')

    const reader = response.body.getReader()
    const decoder = new TextDecoder()

    // 添加初始空消息用于流式更新
    appendToHistory('', 'assistant')

    const readChunk = async () => {
      const { value, done } = await reader.read()
      if (done) {
        sessionToken.value =
          response.headers.get('X-Session-Token') || sessionToken.value
        loading.value = false
        return
      }

      const chunk = decoder.decode(value, { stream: true })
      // 更新最后一条消息
      const lastIndex = history.value.length - 1
      history.value[lastIndex].content += chunk

      scrollToBottom()
      readChunk()
    }

    await readChunk()
  } catch (error) {
    console.error('Error:', error)
    const lastIndex = history.value.length - 1
    if (lastIndex >= 0) {
      history.value[lastIndex].content = 'Error: ' + error.message
    }
    loading.value = false
  }
}
</script>

<style scoped>
:root {
  --primary-color: #4285f4;
  --user-bg: #e3f2fd;
  --ai-bg: #f5f5f5;
  --border-radius: 16px;
  --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 基础布局 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  box-shadow: var(--shadow);
  border-radius: 8px;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, #f9f9ff, #ffffff);
}

/* 消息样式 */
.message {
  display: flex;
  margin-bottom: 24px;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.assistant {
  align-self: flex-start;
}

.avatar {
  display: flex;
  align-items: flex-start;
  padding-top: 5px;
}

.user-avatar,
.ai-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar {
  background: var(--primary-color);
}

.user-avatar svg {
  width: 20px;
  height: 20px;
  fill: white;
}

.ai-avatar {
  background: #666;
}

.ai-avatar svg {
  width: 20px;
  height: 20px;
  fill: white;
}

.message-content {
  margin: 0 12px;
  max-width: calc(100% - 60px);
}

.message.user .message-content {
  align-items: flex-end;
}

.sender {
  font-weight: 600;
  font-size: 0.85rem;
  margin-bottom: 6px;
  color: #555;
}

.message.user .sender {
  text-align: right;
}

.content {
  padding: 12px 16px;
  border-radius: var(--border-radius);
  font-size: 1rem;
  line-height: 1.5;
  word-wrap: break-word;
  box-shadow: var(--shadow);
}

.message.user .content {
  background: var(--user-bg);
  border-top-right-radius: 4px;
}

.message.assistant .content {
  background: var(--ai-bg);
  border-top-left-radius: 4px;
}

.timestamp {
  font-size: 0.7rem;
  color: #999;
  margin-top: 4px;
}

.message.user .timestamp {
  text-align: right;
}

/* 输入区域 */
.input-area {
  padding: 15px 20px;
  background: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

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

input {
  flex: 1;
  padding: 14px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background: #f9f9f9;
}

input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
  background: #fff;
}

button {
  padding: 0 24px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 100px;
  transition: all 0.3s ease;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
  opacity: 0.7;
}

button:not(:disabled):hover {
  background: #3367d6;
  transform: translateY(-1px);
}

.hint-text {
  text-align: center;
  font-size: 0.8rem;
  color: #999;
  margin-top: 8px;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #666;
}

.dot-flashing {
  position: relative;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #999;
  color: #999;
  animation: dotFlashing 1s infinite linear alternate;
  animation-delay: 0.5s;
}

.dot-flashing::before,
.dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #999;
  color: #999;
}

.dot-flashing::before {
  left: -15px;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 15px;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dotFlashing {
  0% {
    background-color: #999;
  }
  50%,
  100% {
    background-color: #e0e0e0;
  }
}

.spinner {
  width: 20px;
  height: 20px;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: 100vh;
    border-radius: 0;
    max-width: 100%;
  }

  .message {
    max-width: 90%;
  }

  .input-wrapper {
    flex-direction: column;
  }

  button {
    min-width: auto;
    padding: 12px;
  }

  .avatar {
    display: none;
  }

  .message-content {
    max-width: 100%;
    margin: 0;
  }

  .chat-history {
    padding: 10px;
  }

  .input-area {
    padding: 10px;
  }

  input {
    padding: 12px;
  }
}

@media (max-width: 480px) {
  .sender {
    font-size: 0.8rem;
  }

  .content {
    padding: 10px 14px;
    font-size: 0.95rem;
  }

  .timestamp {
    font-size: 0.65rem;
  }

  .hint-text {
    display: none;
  }
}
</style>
