<template>
  <div class="monitor-dashboard">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">实时监控仪表盘</span>
          <div>
            <el-tag :type="autoRefresh ? 'success' : 'info'" size="small" style="margin-right: 10px;">
              {{ autoRefresh ? '自动刷新中' : '已暂停' }}
            </el-tag>
            <el-switch v-model="autoRefresh" active-text="自动" inactive-text="手动" style="margin-right: 10px;" />
            <el-button size="small" @click="loadStats" :loading="loading">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 顶部统计卡片 -->
      <el-row :gutter="16" class="stat-cards">
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #909399;">{{ stats.queued_count || 0 }}</div>
            <div class="stat-label">排队中</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #409eff;">{{ stats.running_count || 0 }}</div>
            <div class="stat-label">运行中</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #67c23a;">{{ stats.successful_count || 0 }}</div>
            <div class="stat-label">已成功</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #f56c6c;">{{ stats.failed_count || 0 }}</div>
            <div class="stat-label">失败</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #e6a23c;">{{ stats.max_parallel || 2 }}</div>
            <div class="stat-label">最大并行</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-value" style="color: #409eff;">{{ stats.overall_progress || 0 }}%</div>
            <div class="stat-label">总进度</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 总进度条 -->
      <el-progress :percentage="stats.overall_progress || 0" :stroke-width="16" style="margin: 20px 0;" />

      <el-row :gutter="16">
        <!-- 运行中任务 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <span style="font-weight: 600;">运行中任务 ({{ stats.running_count || 0 }})</span>
            </template>
            <div v-if="!stats.running_tasks?.length" class="empty-state">
              <el-empty description="暂无运行中任务" :image-size="60" />
            </div>
            <div v-for="task in stats.running_tasks" :key="task.task_id" class="task-item">
              <div class="task-header">
                <span class="task-name">{{ task.task_name }}</span>
                <el-tag size="small" type="primary">运行中</el-tag>
              </div>
              <el-progress :percentage="task.progress" :stroke-width="8" style="margin: 8px 0;" />
              <div class="task-meta">
                <span>点: {{ task.current_point }}/{{ task.total_points }}</span>
                <span>优先级: {{ task.priority }}</span>
                <span>开始: {{ formatTime(task.started_at) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 排队任务 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <span style="font-weight: 600;">排队任务 ({{ stats.queued_count || 0 }})</span>
            </template>
            <div v-if="!stats.queued_tasks?.length" class="empty-state">
              <el-empty description="暂无排队任务" :image-size="60" />
            </div>
            <div v-for="task in stats.queued_tasks" :key="task.task_id" class="task-item">
              <div class="task-header">
                <span class="task-name">{{ task.task_name }}</span>
                <el-tag size="small" :type="task.priority >= 8 ? 'danger' : task.priority >= 5 ? 'warning' : 'info'">
                  P{{ task.priority }}
                </el-tag>
              </div>
              <div class="task-meta">
                <span>总点数: {{ task.total_points }}</span>
                <span>入队: {{ formatTime(task.enqueued_at) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近完成 -->
      <el-card shadow="never" style="margin-top: 16px;">
        <template #header>
          <span style="font-weight: 600;">最近完成任务</span>
        </template>
        <el-table :data="stats.recent_completed || []" size="small" border>
          <el-table-column prop="task_name" label="任务名称" min-width="150" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'completed' ? 'success' : row.status === 'failed' ? 'danger' : 'info'" size="small">
                {{ row.status === 'completed' ? '成功' : row.status === 'failed' ? '失败' : row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total_points" label="总点数" width="80" />
          <el-table-column prop="priority" label="优先级" width="80" />
          <el-table-column label="完成时间" width="170">
            <template #default="{ row }">{{ formatTime(row.completed_at) }}</template>
          </el-table-column>
          <el-table-column prop="error" label="错误信息" min-width="200" show-overflow-tooltip />
        </el-table>
      </el-card>

      <div class="last-update">最后更新: {{ lastUpdate || '-' }}</div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import api from '@/api'

const stats = reactive<any>({})
const loading = ref(false)
const autoRefresh = ref(true)
const lastUpdate = ref('')
let timer: any = null

const formatTime = (t: string) => t ? new Date(t).toLocaleString('zh-CN') : '-'

const loadStats = async () => {
  loading.value = true
  try {
    const res: any = await api.get('/monitor/stats')
    Object.assign(stats, res)
    lastUpdate.value = new Date().toLocaleTimeString('zh-CN')
  } catch (e) {
    console.error('Failed to load stats:', e)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadStats()
  timer = setInterval(() => {
    if (autoRefresh.value) loadStats()
  }, 5000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<style scoped>
.monitor-dashboard { padding: 20px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.title { font-weight: 600; font-size: 16px; }
.stat-cards { margin-bottom: 10px; }
.stat-card { text-align: center; }
.stat-value { font-size: 28px; font-weight: 700; margin-bottom: 4px; }
.stat-label { font-size: 13px; color: #909399; }
.task-item { padding: 12px; border-bottom: 1px solid #ebeef5; }
.task-item:last-child { border-bottom: none; }
.task-header { display: flex; justify-content: space-between; align-items: center; }
.task-name { font-weight: 500; }
.task-meta { display: flex; gap: 16px; font-size: 12px; color: #909399; margin-top: 4px; }
.empty-state { padding: 20px 0; }
.last-update { text-align: right; font-size: 12px; color: #909399; margin-top: 10px; }
</style>
