<template>
  <div class="chat-widget" :class="{ 'chat-widget--expanded': isExpanded }">
    <!-- 聊天按钮 -->
    <el-button
      v-if="!isExpanded"
      type="primary"
      circle
      size="large"
      class="chat-toggle-btn"
      @click="toggleExpanded"
    >
      <el-icon><ChatDotRound /></el-icon>
    </el-button>
    
    <!-- 聊天窗口 -->
    <div v-else class="chat-window">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="chat-title">
          <el-icon><Robot /></el-icon>
          <span>{{ $t('chat.title') }}</span>
        </div>
        <div class="chat-actions">
          <el-button
            type="text"
            size="small"
            @click="toggleExpanded"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="messages.length === 0" class="chat-empty">
          <el-icon><ChatDotRound /></el-icon>
          <p>{{ $t('chat.welcome') }}</p>
          <p class="chat-empty-desc">{{ $t('chat.welcomeDesc') }}</p>
        </div>
        
        <div
          v-for="message in messages"
          :key="message.id"
          class="chat-message"
          :class="`chat-message--${message.role}`"
        >
          <div class="message-avatar">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <el-icon v-else-if="message.role === 'assistant'"><Robot /></el-icon>
            <el-icon v-else><InfoFilled /></el-icon>
          </div>
          
          <div class="message-content">
            <div class="message-text" v-html="message.content"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            
            <!-- 元数据 -->
            <div v-if="message.metadata" class="message-metadata">
              <div v-if="message.metadata.knowledge_used?.length" class="knowledge-info">
                <el-icon><Lightbulb /></el-icon>
                <span>基于 {{ message.metadata.knowledge_used.length }} 条知识库信息生成</span>
              </div>
              
              <div v-if="message.metadata.confidence_score" class="confidence-score">
                置信度: {{ (message.metadata.confidence_score * 100).toFixed(1) }}%
              </div>
              
              <div v-if="message.metadata.work_order_id" class="work-order-info">
                <el-icon><Ticket /></el-icon>
                <span>关联工单: {{ message.metadata.work_order_id }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 打字指示器 -->
        <div v-if="isTyping" class="typing-indicator">
          <div class="message-avatar">
            <el-icon><Robot /></el-icon>
          </div>
          <div class="message-content">
            <div class="typing-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-group">
          <el-input
            v-model="inputMessage"
            :placeholder="$t('chat.inputPlaceholder')"
            :disabled="!hasActiveSession"
            @keyup.enter="handleSendMessage"
            class="message-input"
          />
          <el-button
            type="primary"
            :disabled="!hasActiveSession || !inputMessage.trim()"
            @click="handleSendMessage"
            class="send-btn"
          >
            <el-icon><Position /></el-icon>
          </el-button>
        </div>
        
        <!-- 快速操作 -->
        <div v-if="hasActiveSession" class="quick-actions">
          <el-button
            v-for="action in quickActions"
            :key="action.key"
            size="small"
            @click="handleQuickAction(action.message)"
            class="quick-action-btn"
          >
            {{ action.label }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useChatStore } from '@/stores/useChatStore'
import { ElMessage } from 'element-plus'

const { t } = useI18n()
const chatStore = useChatStore()

// 状态
const isExpanded = ref(false)
const inputMessage = ref('')
const messagesContainer = ref<HTMLElement>()

// 计算属性
const messages = computed(() => chatStore.messages)
const isTyping = computed(() => chatStore.isTyping)
const hasActiveSession = computed(() => chatStore.hasActiveSession)

// 快速操作
const quickActions = computed(() => [
  { key: 'remoteStart', label: t('chat.quickActions.remoteStart'), message: '我的车辆无法远程启动' },
  { key: 'appDisplay', label: t('chat.quickActions.appDisplay'), message: 'APP显示车辆信息错误' },
  { key: 'bluetoothAuth', label: t('chat.quickActions.bluetoothAuth'), message: '蓝牙授权失败' },
  { key: 'unbindVehicle', label: t('chat.quickActions.unbindVehicle'), message: '如何解绑车辆' }
])

// 方法
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

const handleSendMessage = async () => {
  if (!inputMessage.value.trim() || !hasActiveSession.value) {
    return
  }
  
  const message = inputMessage.value.trim()
  inputMessage.value = ''
  
  try {
    await chatStore.sendMessage(message)
  } catch (error) {
    ElMessage.error('发送消息失败')
    console.error('发送消息失败:', error)
  }
}

const handleQuickAction = async (message: string) => {
  inputMessage.value = message
  await handleSendMessage()
}

const formatTime = (timestamp: Date) => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return timestamp.toLocaleDateString()
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

// 监听打字状态变化
watch(isTyping, () => {
  scrollToBottom()
})
</script>

<style scoped lang="scss">
.chat-widget {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  
  &--expanded {
    width: 400px;
    height: 600px;
    background: var(--el-bg-color);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid var(--el-border-color);
    display: flex;
    flex-direction: column;
  }
}

.chat-toggle-btn {
  width: 60px;
  height: 60px;
  font-size: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.chat-window {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--el-color-primary);
  color: white;
  border-radius: 12px 12px 0 0;
  
  .chat-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
  }
  
  .chat-actions {
    .el-button {
      color: white;
    }
  }
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: var(--el-bg-color-page);
}

.chat-empty {
  text-align: center;
  padding: 40px 20px;
  color: var(--el-text-color-secondary);
  
  .el-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }
  
  p {
    margin: 8px 0;
  }
  
  .chat-empty-desc {
    font-size: 14px;
    color: var(--el-text-color-placeholder);
  }
}

.chat-message {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
  gap: 8px;
  
  &--user {
    flex-direction: row-reverse;
    
    .message-content {
      background: var(--el-color-primary);
      color: white;
      border-radius: 18px 18px 4px 18px;
    }
  }
  
  &--assistant {
    .message-content {
      background: var(--el-bg-color);
      color: var(--el-text-color-primary);
      border: 1px solid var(--el-border-color);
      border-radius: 18px 18px 18px 4px;
    }
  }
  
  &--system {
    justify-content: center;
    
    .message-content {
      background: var(--el-color-info-light-9);
      color: var(--el-color-info);
      border-radius: 12px;
      font-size: 14px;
      text-align: center;
    }
  }
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: var(--el-color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  position: relative;
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 4px;
}

.message-metadata {
  margin-top: 8px;
  
  .knowledge-info,
  .confidence-score,
  .work-order-info {
    font-size: 12px;
    opacity: 0.8;
    margin-top: 4px;
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .knowledge-info {
    color: var(--el-color-info);
  }
  
  .confidence-score {
    color: var(--el-color-success);
  }
  
  .work-order-info {
    color: var(--el-color-warning);
  }
}

.typing-indicator {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 16px;
}

.typing-dots {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 18px 18px 18px 4px;
  
  span {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--el-color-primary);
    animation: typing 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  padding: 16px;
  border-top: 1px solid var(--el-border-color);
  background: var(--el-bg-color);
  border-radius: 0 0 12px 12px;
}

.input-group {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  
  .message-input {
    flex: 1;
  }
  
  .send-btn {
    flex-shrink: 0;
  }
}

.quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-action-btn {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
}

// 暗色主题适配
:global(.dark) {
  .chat-widget--expanded {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  }
  
  .chat-toggle-btn {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  }
}
</style>
