<template>
  <div class="history-list">
    <!-- 加载状态 -->
    <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="restorePlan(plan)"
      >
        <div class="plan-info">
          <div class="plan-goal">
            <SvgIcon icon-class="XiaoXi" size="20px" />
            {{ plan.general_goal || '未知任务' }}
          </div>
        </div>
        <div class="plan-actions">
          <el-popover
            placement="bottom-end"
            :show-arrow="false"
            trigger="click"
            popper-class="action-popover"
          >
            <template #reference>
              <button class="more-btn" @click.stop>
                <SvgIcon icon-class="more" class="more-icon" size="16px" />
              </button>
            </template>
            <div class="action-menu">
              <div class="action-item" @click="pinPlan(plan)">
                <SvgIcon icon-class="ZhiDing" size="14px" />
                <span>{{ plan.is_pinned ? '取消置顶' : '置顶' }}</span>
              </div>
              <div class="action-item">
                <SvgIcon icon-class="FenXiang" size="14px" />
                <span>分享</span>
              </div>
              <div class="action-item" @click="deletePlan(plan)">
                <SvgIcon icon-class="ShanChu" size="14px" />
                <span>删除</span>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model="dialogVisible"
      title="确认删除该任务 ?"
      content="删除后，该任务无法恢复 !"
      @confirm="confirmDelete"
    />
  </div>
</template>

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

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

// 数据类型
interface PlanInfo {
  id: string
  general_goal: string
  is_pinned?: boolean
  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 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[]
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 恢复任务
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 pinPlan = async (plan: PlanInfo) => {
  const newPinnedState = !plan.is_pinned
  const reqId = generateRequestId()

  try {
    await websocket.send('pin_plan', {
      id: reqId,
      data: { plan_id: plan.id, is_pinned: newPinnedState }
    })

    ElMessage.success(newPinnedState ? '置顶成功' : '取消置顶成功')
    // 成功后会自动通过 history_updated 事件刷新列表
  } catch (error) {
    console.error('置顶任务失败:', error)
    ElMessage.error('置顶失败')
  }
}

// 删除任务
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
  }
}

// 生命周期
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;
}

.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: var(--color-bg-three);
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: var(--color-bg-hover);

    .plan-goal {
      color: var(--color-text-plan-item-hover);
    }
  }

  &.active {
    background: var(--color-bg-hover);
    border-left: 3px solid var(--color-primary);
  }
}

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

.plan-goal {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--color-text-plan-item);
  transition: color 0.2s;
}

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

// 更多按钮
.more-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;

  .more-icon {
    color: var(--color-text-plan-item);
    transition: color 0.2s;
  }

  &:hover {
    background-color: var(--color-card-border-three);
    border-radius: 50%;

    .more-icon {
      color: var(--color-text-plan-item-hover);
    }
  }
}

// 操作菜单
.action-menu {
  display: flex;
  flex-direction: column;

  :deep(.el-popover__content) {
    padding: 0;
  }
}

.action-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 13px;
  color: var(--color-text-plan-item);
  transition: background-color 0.2s, color 0.2s;

  .svg-icon {
    color: var(--color-text-plan-item);
    transition: color 0.2s;
  }

  &:first-child {
    border-radius: 8px 8px 0 0;
  }

  &:last-child {
    border-radius: 0 0 8px 8px;
  }

  &:hover {
    background-color: var(--color-card-border-three);
    color: var(--color-text-plan-item-hover);

    .svg-icon {
      color: var(--color-text-plan-item-hover);
    }
  }
}
</style>

<style lang="scss">
.action-popover {
  padding: 0 !important;
  border-radius: 8px !important;
  width: 120px !important;
  min-width: 120px !important;
}
</style>
