<template>
  <div class="chat-page">
    <el-row :gutter="20">
      <!-- 左侧控制面板 -->
      <el-col :span="6">
        <el-card class="control-panel">
          <template #header>
            <div class="card-header">
              <el-icon><Setting /></el-icon>
              <span>{{ $t('chat.title') }}</span>
            </div>
          </template>
          
          <div class="control-content">
            <!-- 用户设置 -->
            <div class="control-section">
              <h4>{{ $t('chat.userId') }}</h4>
              <el-input
                v-model="userId"
                :placeholder="$t('chat.userId')"
                @change="handleUserIdChange"
              />
            </div>
            
            <div class="control-section">
              <h4>{{ $t('chat.workOrderId') }}</h4>
              <el-input
                v-model="workOrderId"
                :placeholder="$t('chat.workOrderIdPlaceholder')"
                type="number"
                @change="handleWorkOrderIdChange"
              />
            </div>
            
            <!-- 控制按钮 -->
            <div class="control-section">
              <div class="control-buttons">
                <el-button
                  type="primary"
                  :loading="loading"
                  :disabled="hasActiveSession"
                  @click="handleStartChat"
                  class="control-btn"
                >
                  <el-icon><VideoPlay /></el-icon>
                  {{ $t('chat.startChat') }}
                </el-button>
                
                <el-button
                  type="danger"
                  :loading="loading"
                  :disabled="!hasActiveSession"
                  @click="handleEndChat"
                  class="control-btn"
                >
                  <el-icon><VideoPause /></el-icon>
                  {{ $t('chat.endChat') }}
                </el-button>
                
                <el-button
                  type="success"
                  :loading="loading"
                  :disabled="!hasActiveSession"
                  @click="showWorkOrderModal = true"
                  class="control-btn"
                >
                  <el-icon><Plus /></el-icon>
                  {{ $t('chat.createWorkOrder') }}
                </el-button>
              </div>
            </div>
            
            <!-- 快速操作 -->
            <div class="control-section">
              <h4>{{ $t('chat.quickActions') }}</h4>
              <div class="quick-actions">
                <el-button
                  v-for="action in quickActions"
                  :key="action.key"
                  size="small"
                  @click="handleQuickAction(action.message)"
                  :disabled="!hasActiveSession"
                  class="quick-action-btn"
                >
                  {{ action.label }}
                </el-button>
              </div>
            </div>
            
            <!-- 会话信息 -->
            <div class="control-section">
              <h4>{{ $t('chat.sessionInfo') }}</h4>
              <div class="session-info">
                <div v-if="currentSession" class="session-details">
                  <div class="session-item">
                    <span class="session-label">{{ $t('common.status') }}:</span>
                    <el-tag :type="hasActiveSession ? 'success' : 'info'">
                      {{ hasActiveSession ? '活跃' : '已结束' }}
                    </el-tag>
                  </div>
                  <div class="session-item">
                    <span class="session-label">{{ $t('common.time') }}:</span>
                    <span>{{ formatTime(currentSession.createdAt) }}</span>
                  </div>
                  <div class="session-item">
                    <span class="session-label">{{ $t('common.message') }}:</span>
                    <span>{{ messageCount }}</span>
                  </div>
                </div>
                <div v-else class="session-empty">
                  {{ $t('chat.welcomeDesc') }}
                </div>
              </div>
            </div>
            
            <!-- 连接状态 -->
            <div class="control-section">
              <h4>{{ $t('chat.connectionStatus') }}</h4>
              <div class="connection-status">
                <el-tag :type="isConnected ? 'success' : 'danger'">
                  <el-icon><CircleCheck v-if="isConnected" /><CircleClose v-else /></el-icon>
                  {{ isConnected ? $t('chat.connected') : $t('chat.disconnected') }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧聊天区域 -->
      <el-col :span="18">
        <el-card class="chat-area">
          <template #header>
            <div class="card-header">
              <el-icon><Robot /></el-icon>
              <span>TSP智能助手</span>
              <div class="header-subtitle">基于知识库的智能客服系统</div>
            </div>
          </template>
          
          <div class="chat-container">
            <!-- 消息列表 -->
            <div class="chat-messages" ref="messagesContainer">
              <div v-if="messages.length === 0" class="chat-empty">
                <el-icon size="64"><ChatDotRound /></el-icon>
                <h3>{{ $t('chat.welcome') }}</h3>
                <p>{{ $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"
                  type="textarea"
                  :rows="3"
                  resize="none"
                />
                <el-button
                  type="primary"
                  :disabled="!hasActiveSession || !inputMessage.trim()"
                  @click="handleSendMessage"
                  class="send-btn"
                >
                  <el-icon><Position /></el-icon>
                  {{ $t('chat.sendMessage') }}
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 创建工单模态框 -->
    <el-dialog
      v-model="showWorkOrderModal"
      :title="$t('chat.workOrder.title')"
      width="500px"
    >
      <el-form :model="workOrderForm" label-width="100px">
        <el-form-item :label="$t('chat.workOrder.titleLabel')" required>
          <el-input v-model="workOrderForm.title" />
        </el-form-item>
        
        <el-form-item :label="$t('chat.workOrder.descriptionLabel')" required>
          <el-input
            v-model="workOrderForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('chat.workOrder.categoryLabel')">
              <el-select v-model="workOrderForm.category">
                <el-option
                  v-for="(label, key) in workOrderCategories"
                  :key="key"
                  :label="label"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item :label="$t('chat.workOrder.priorityLabel')">
              <el-select v-model="workOrderForm.priority">
                <el-option
                  v-for="(label, key) in workOrderPriorities"
                  :key="key"
                  :label="label"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="showWorkOrderModal = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleCreateWorkOrder"
        >
          {{ $t('chat.createWorkOrder') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

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

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

// 工单表单
const workOrderForm = ref({
  title: '',
  description: '',
  category: 'technical',
  priority: 'medium'
})

// 计算属性
const userId = computed({
  get: () => chatStore.userId,
  set: (value) => chatStore.setUserId(value)
})

const workOrderId = computed({
  get: () => chatStore.workOrderId,
  set: (value) => chatStore.setWorkOrderId(value)
})

const messages = computed(() => chatStore.messages)
const isTyping = computed(() => chatStore.isTyping)
const isConnected = computed(() => chatStore.isConnected)
const hasActiveSession = computed(() => chatStore.hasActiveSession)
const currentSession = computed(() => chatStore.currentSession)
const messageCount = computed(() => chatStore.messageCount)

// 快速操作
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 workOrderCategories = computed(() => ({
  technical: t('chat.workOrder.categories.technical'),
  app: t('chat.workOrder.categories.app'),
  remoteControl: t('chat.workOrder.categories.remoteControl'),
  vehicleBinding: t('chat.workOrder.categories.vehicleBinding'),
  other: t('chat.workOrder.categories.other')
}))

const workOrderPriorities = computed(() => ({
  low: t('chat.workOrder.priorities.low'),
  medium: t('chat.workOrder.priorities.medium'),
  high: t('chat.workOrder.priorities.high'),
  urgent: t('chat.workOrder.priorities.urgent')
}))

// 方法
const handleStartChat = async () => {
  loading.value = true
  try {
    const success = await chatStore.startChat()
    if (success) {
      ElMessage.success('对话已开始')
    } else {
      ElMessage.error('启动对话失败')
    }
  } catch (error) {
    ElMessage.error('启动对话失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleEndChat = async () => {
  loading.value = true
  try {
    await chatStore.endChat()
    ElMessage.success('对话已结束')
  } catch (error) {
    ElMessage.error('结束对话失败')
  } finally {
    loading.value = false
  }
}

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 handleCreateWorkOrder = async () => {
  if (!workOrderForm.value.title || !workOrderForm.value.description) {
    ElMessage.warning('请填写工单标题和描述')
    return
  }
  
  loading.value = true
  try {
    await chatStore.createWorkOrder(workOrderForm.value)
    showWorkOrderModal.value = false
    workOrderForm.value = {
      title: '',
      description: '',
      category: 'technical',
      priority: 'medium'
    }
  } catch (error) {
    ElMessage.error('创建工单失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleUserIdChange = (value: string) => {
  chatStore.setUserId(value)
}

const handleWorkOrderIdChange = (value: string) => {
  chatStore.setWorkOrderId(value)
}

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()
})

// 生命周期
onMounted(() => {
  // 尝试连接WebSocket
  chatStore.connectWebSocket().catch(error => {
    console.error('WebSocket连接失败:', error)
  })
})
</script>

<style scoped lang="scss">
.chat-page {
  .control-panel {
    height: calc(100vh - 120px);
    
    .control-content {
      height: calc(100% - 60px);
      overflow-y: auto;
      
      .control-section {
        margin-bottom: 24px;
        
        h4 {
          margin: 0 0 12px 0;
          font-size: 14px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
        
        .control-buttons {
          display: flex;
          flex-direction: column;
          gap: 8px;
          
          .control-btn {
            width: 100%;
            justify-content: flex-start;
          }
        }
        
        .quick-actions {
          display: flex;
          flex-direction: column;
          gap: 8px;
          
          .quick-action-btn {
            width: 100%;
            justify-content: flex-start;
            font-size: 12px;
          }
        }
        
        .session-info {
          .session-details {
            .session-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;
              font-size: 14px;
              
              .session-label {
                color: var(--el-text-color-secondary);
              }
            }
          }
          
          .session-empty {
            color: var(--el-text-color-placeholder);
            font-size: 14px;
            text-align: center;
            padding: 20px 0;
          }
        }
        
        .connection-status {
          .el-tag {
            width: 100%;
            justify-content: center;
          }
        }
      }
    }
  }
  
  .chat-area {
    height: calc(100vh - 120px);
    
    .card-header {
      .header-subtitle {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-left: 8px;
      }
    }
    
    .chat-container {
      height: calc(100% - 60px);
      display: flex;
      flex-direction: column;
      
      .chat-messages {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        background: var(--el-bg-color-page);
        border-radius: 8px;
        margin-bottom: 16px;
      }
      
      .chat-empty {
        text-align: center;
        padding: 60px 20px;
        color: var(--el-text-color-secondary);
        
        .el-icon {
          margin-bottom: 16px;
        }
        
        h3 {
          margin: 16px 0 8px 0;
          color: var(--el-text-color-primary);
        }
        
        p {
          margin: 0;
          font-size: 14px;
        }
      }
      
      .chat-message {
        display: flex;
        margin-bottom: 20px;
        align-items: flex-start;
        gap: 12px;
        
        &--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: 40px;
        height: 40px;
        border-radius: 50%;
        background: var(--el-color-primary);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 18px;
        flex-shrink: 0;
      }
      
      .message-content {
        max-width: 70%;
        padding: 16px 20px;
        position: relative;
        
        .message-text {
          line-height: 1.6;
          word-wrap: break-word;
        }
        
        .message-time {
          font-size: 12px;
          opacity: 0.7;
          margin-top: 8px;
        }
        
        .message-metadata {
          margin-top: 12px;
          
          .knowledge-info,
          .confidence-score,
          .work-order-info {
            font-size: 12px;
            opacity: 0.8;
            margin-top: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
          }
          
          .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: 12px;
        margin-bottom: 20px;
      }
      
      .typing-dots {
        display: flex;
        gap: 6px;
        padding: 16px 20px;
        background: var(--el-bg-color);
        border: 1px solid var(--el-border-color);
        border-radius: 18px 18px 18px 4px;
        
        span {
          width: 8px;
          height: 8px;
          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 {
        .input-group {
          display: flex;
          gap: 12px;
          
          .message-input {
            flex: 1;
          }
          
          .send-btn {
            flex-shrink: 0;
            height: auto;
            padding: 12px 20px;
          }
        }
      }
    }
  }
}
</style>
