<template>
  <div class="history-list">
    <div class="header">
      <h3>📋 历史任务</h3>
      <el-button type="primary" link @click="fetchPlans">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="plans.length === 0" description="暂无历史任务" />

    <!-- 任务列表 -->
    <div v-else class="plan-list">
      <div
        v-for="plan in plans"
        :key="plan.id"
        class="plan-item"
        :class="{ active: selectedPlanId === plan.id }"
        @click="selectPlan(plan)"
      >
        <div class="plan-info">
          <div class="plan-goal">{{ plan.general_goal || '未知任务' }}</div>
          <div class="plan-meta">
            <el-tag size="small" :type="getStatusType(plan.status)">
              {{ getStatusText(plan.status) }}
            </el-tag>
            <span class="plan-time">{{ formatTime(plan.created_at) }}</span>
          </div>
          <div class="plan-stats">
            <span>执行次数: {{ plan.execution_count }}</span>
          </div>
        </div>
        <div class="plan-actions">
          <el-button
            type="primary"
            size="small"
            @click.stop="restorePlan(plan)"
            :disabled="restoring"
          >
            恢复
          </el-button>
          <el-button
            type="danger"
            size="small"
            link
            @click.stop="deletePlan(plan)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="plans.length > 0" class="pagination">
      <span>共 {{ total }} 个任务</span>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="删除确认"
      width="400px"
      :close-on-click-modal="false"
    >
      <span>确定要删除任务 "{{ planToDelete?.general_goal }}" 吗？此操作不可恢复。</span>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleting">确定删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Loading, Delete } from '@element-plus/icons-vue'
import websocket from '@/utils/websocket'

// 事件定义
const emit = defineEmits<{
  (e: 'restore', plan: PlanInfo): void
  (e: 'close'): void
}>()

// 数据类型
interface PlanInfo {
  id: string              // 对应数据库 task_id
  general_goal: string    // 对应数据库 query
  status: string
  execution_count: number
  created_at: string
  // 完整恢复数据
  task_outline?: any
  assigned_agents?: any
  agent_scores?: any
  agents_info?: any[]
}

// 响应式数据
const plans = ref<PlanInfo[]>([])
const loading = ref(false)
const restoring = ref(false)
const selectedPlanId = ref<string | null>(null)
const total = ref(0)
const isConnected = ref(false)

// 删除对话框相关
const dialogVisible = ref(false)
const planToDelete = ref<PlanInfo | null>(null)
const deleting = ref(false)

// 生成唯一请求ID
let requestIdCounter = 0
const generateRequestId = () => `ws_req_${Date.now()}_${++requestIdCounter}`

// WebSocket 监听器引用（用于清理）
const historyUpdatedHandler = () => {
  console.log('📡 收到历史列表更新通知，自动刷新')
  fetchPlans()
}

// 获取任务列表
const fetchPlans = async () => {
  loading.value = true
  const reqId = generateRequestId()

  try {
    const result = await websocket.send('get_plans', { id: reqId })
    plans.value = (result.data || []) as PlanInfo[]
    total.value = plans.value.length
    isConnected.value = true
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
    isConnected.value = false
  } finally {
    loading.value = false
  }
}

// 选择任务
const selectPlan = (plan: PlanInfo) => {
  selectedPlanId.value = plan.id
}

// 恢复任务
const restorePlan = async (plan: PlanInfo) => {
  if (restoring.value) return

  console.log('🔍 [HistoryList] 恢复计划:', plan)
  console.log('🔍 [HistoryList] plan.id:', plan.id)

  if (!plan.id) {
    ElMessage.error('任务 ID 为空，无法恢复')
    return
  }

  restoring.value = true
  selectedPlanId.value = plan.id

  const reqId = generateRequestId()

  try {
    const result = await websocket.send('restore_plan', {
      id: reqId,
      data: { plan_id: plan.id }
    })
    const planData = (result.data || result) as any

    // 发送恢复事件
    emit('restore', {
      ...plan,
      ...planData
    })

    ElMessage.success('任务已恢复')
  } catch (error) {
    console.error('恢复任务失败:', error)
    ElMessage.error('恢复任务失败')
  } finally {
    restoring.value = false
  }
}

// 删除任务
const deletePlan = (plan: PlanInfo) => {
  planToDelete.value = plan
  dialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!planToDelete.value) return

  deleting.value = true
  const reqId = generateRequestId()

  try {
    await websocket.send('delete_plan', {
      id: reqId,
      data: { plan_id: planToDelete.value.id }
    })

    dialogVisible.value = false
    ElMessage.success('删除成功')
    // 删除成功后会自动通过 history_updated 事件刷新列表
  } catch (error) {
    console.error('删除任务失败:', error)
    ElMessage.error('删除任务失败')
  } finally {
    deleting.value = false
  }
}

// 格式化时间
const formatTime = (timeStr: string | undefined) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return timeStr
  }
}

// 获取状态类型
const getStatusType = (status: string): string => {
  const statusMap: Record<string, string> = {
    'generating': 'warning',
    'executing': 'warning',
    'completed': 'success',
    'stopped': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'generating': '生成中',
    'executing': '执行中',
    'completed': '已完成',
    'stopped': '已停止'
  }
  return statusMap[status] || status
}

// 生命周期
onMounted(() => {
  fetchPlans()
  // 监听历史列表更新事件（多标签页实时同步）
  websocket.on('history_updated', historyUpdatedHandler)
})

onUnmounted(() => {
  // 移除事件监听
  websocket.off('history_updated', historyUpdatedHandler)
})
</script>

<style scoped lang="scss">
.history-list {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
  gap: 8px;
}

.plan-list {
  flex: 1;
  overflow-y: auto;
}

.plan-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  background: #f5f7fa;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: #ecf5ff;
  }

  &.active {
    background: #ecf5ff;
    border-left: 3px solid #409eff;
  }
}

.plan-info {
  flex: 1;
  min-width: 0;
}

.plan-goal {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.plan-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.plan-time {
  font-size: 12px;
  color: #909399;
}

.plan-stats {
  font-size: 12px;
  color: #606266;
}

.plan-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  color: #909399;
  font-size: 13px;
}
</style>
