<template>
  <div class="polling-monitor-page">
    <!-- 队列状态 -->
    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="card-header">
          <span>队列状态</span>
          <el-button size="small" @click="loadQueueStatus(true)">刷新</el-button>
        </div>
      </template>
      <el-table :data="queueStatusList" border stripe>
        <el-table-column prop="task_type_name" label="任务类型" min-width="120" />
        <el-table-column prop="queue_size" label="队列大小" min-width="100" />
        <el-table-column prop="due_count" label="到期待处理" min-width="110" />
        <el-table-column prop="manual_pending" label="手动待处理" min-width="110" />
        <el-table-column label="平均等待时间" min-width="120">
          <template #default="{ row }">
            {{ row.avg_wait_time_s ? row.avg_wait_time_s.toFixed(1) + 's' : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 任务统计 -->
    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="card-header">
          <span>任务统计（最近1小时）</span>
          <el-button size="small" @click="loadTaskStats(true)">刷新</el-button>
        </div>
      </template>
      <el-table :data="taskStatsList" border stripe>
        <el-table-column prop="task_type_name" label="任务类型" min-width="120" />
        <el-table-column prop="total_count_1h" label="总数" min-width="100" />
        <el-table-column prop="success_count_1h" label="成功数" min-width="100" />
        <el-table-column prop="failure_count_1h" label="失败数" min-width="100" />
        <el-table-column label="成功率" min-width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.success_rate"
              :stroke-width="8"
              :color="getSuccessRateColor(row.success_rate)"
            >
              <span style="font-size: 12px">{{ row.success_rate.toFixed(2) }}%</span>
            </el-progress>
          </template>
        </el-table-column>
        <el-table-column label="平均耗时" min-width="120">
          <template #default="{ row }">
            {{ row.avg_duration_ms ? row.avg_duration_ms.toFixed(1) + 'ms' : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 初始化进度 -->
    <el-card shadow="never" class="section-card" v-if="initProgress && !initProgress.is_complete">
      <template #header>
        <div class="card-header">
          <span>初始化进度</span>
          <el-button size="small" @click="loadInitProgress(true)">刷新</el-button>
        </div>
      </template>
      <div class="init-progress-content">
        <div class="progress-info">
          <div class="info-item">
            <span class="label">总卡数：</span>
            <span class="value">{{ initProgress.total_cards }}</span>
          </div>
          <div class="info-item">
            <span class="label">已初始化：</span>
            <span class="value">{{ initProgress.initialized_cards }}</span>
          </div>
          <div class="info-item">
            <span class="label">开始时间：</span>
            <span class="value">{{ formatDateTime(initProgress.started_at) }}</span>
          </div>
          <div class="info-item">
            <span class="label">预计完成：</span>
            <span class="value">{{ formatDateTime(initProgress.estimated_eta) }}</span>
          </div>
        </div>
        <el-progress
          :percentage="initProgress.progress"
          :stroke-width="20"
          :color="getProgressColor(initProgress.progress)"
        >
          <span style="font-size: 14px; font-weight: bold"
            >{{ initProgress.progress.toFixed(1) }}%</span
          >
        </el-progress>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { PollingMonitorService } from '@/api/modules'
  import type { PollingInitProgress, PollingQueueStatus, PollingTaskStats } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'
  const initProgress = ref<PollingInitProgress>()
  const queueStatusList = ref<PollingQueueStatus[]>([])
  const taskStatsList = ref<PollingTaskStats[]>([])

  let refreshTimer: NodeJS.Timeout | null = null

  // 加载初始化进度
  const loadInitProgress = async (showMessage = false) => {
    try {
      const { data } = await PollingMonitorService.getInitProgress()
      initProgress.value = data
      if (showMessage) {
        ElMessage.success('初始化进度已刷新')
      }
    } catch (error) {
      console.error('加载初始化进度失败', error)
    }
  }

  // 加载队列状态
  const loadQueueStatus = async (showMessage = false) => {
    try {
      const { data } = await PollingMonitorService.getQueueStatus()
      queueStatusList.value = data.items
      if (showMessage) {
        ElMessage.success('队列状态已刷新')
      }
    } catch (error) {
      console.log('加载队列状态失败')
    }
  }

  // 加载任务统计
  const loadTaskStats = async (showMessage = false) => {
    try {
      const { data } = await PollingMonitorService.getTaskStats()
      taskStatsList.value = data.items
      if (showMessage) {
        ElMessage.success('任务统计已刷新')
      }
    } catch (error) {
      console.log('加载任务统计失败')
    }
  }

  // 加载所有数据
  const loadAllData = () => {
    loadInitProgress()
    loadQueueStatus()
    loadTaskStats()
  }

  // 获取成功率颜色
  const getSuccessRateColor = (rate: number) => {
    if (rate >= 95) return '#67c23a'
    if (rate >= 85) return '#e6a23c'
    return '#f56c6c'
  }

  // 获取进度颜色
  const getProgressColor = (progress: number) => {
    if (progress >= 90) return '#67c23a'
    if (progress >= 50) return '#409eff'
    return '#e6a23c'
  }

  onMounted(() => {
    loadAllData()

    // 每30秒自动刷新
    refreshTimer = setInterval(() => {
      loadAllData()
    }, 30000)
  })

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

<style scoped lang="scss">
  .polling-monitor-page {
    padding: 20px;

    .stats-row {
      margin-bottom: 20px;
    }

    .stat-card {
      display: flex;
      gap: 16px;
      align-items: center;

      .stat-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 64px;
        height: 64px;
        color: #fff;
        border-radius: 12px;

        &.total {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.initialized {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.realname {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        &.package {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }

        &.carddata {
          background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
      }

      .stat-content {
        flex: 1;

        .stat-label {
          margin-bottom: 4px;
          font-size: 14px;
          color: var(--el-text-color-secondary);
        }

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: var(--el-text-color-primary);
        }
      }
    }

    .section-card {
      margin-bottom: 20px;

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }
    }

    .init-progress-content {
      .progress-info {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
        margin-bottom: 20px;

        .info-item {
          .label {
            font-size: 14px;
            color: var(--el-text-color-secondary);
          }

          .value {
            margin-left: 8px;
            font-weight: 500;
            color: var(--el-text-color-primary);
          }
        }
      }
    }
  }
</style>
