<template>
  <MainLayout>
    <div class="monitoring-page">
      <el-card>
      <template #header>
        <div class="card-header">
          <h2>系统监控</h2>
          <el-button @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <!-- 系统概览 -->
      <div class="overview-section">
        <h3>系统概览</h3>
        <el-row :gutter="20">
          <el-col :span="4" v-for="item in overviewItems" :key="item.key">
            <el-card class="stat-card">
              <div class="stat-value">{{ item.value }}</div>
              <div class="stat-label">{{ item.label }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 执行统计 -->
      <div class="statistics-section">
        <h3>执行统计（最近{{ days }}天）</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <h4>执行状态分布</h4>
              <div class="status-stats">
                <div v-for="(count, status) in executionStats.status_counts" :key="status" class="status-item">
                  <span class="status-label">{{ getStatusLabel(status) }}</span>
                  <el-progress 
                    :percentage="(count / executionStats.total) * 100" 
                    :format="() => `${count}`"
                  />
                </div>
              </div>
              <div class="stat-summary">
                <div class="summary-item">
                  <span class="label">总执行数：</span>
                  <span class="value">{{ executionStats.total }}</span>
                </div>
                <div class="summary-item">
                  <span class="label">成功率：</span>
                  <span class="value success">{{ executionStats.success_rate }}%</span>
                </div>
                <div class="summary-item">
                  <span class="label">平均执行时间：</span>
                  <span class="value">{{ formatTime(executionStats.avg_execution_time) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <h4>执行趋势（最近24小时）</h4>
              <div class="trend-chart">
                <div 
                  v-for="(item, index) in executionStats.hourly_trends" 
                  :key="index"
                  class="trend-bar"
                  :style="{ height: `${(item.count / maxTrendCount) * 100}%` }"
                  :title="`${item.hour}: ${item.count}次`"
                >
                  <div class="trend-value">{{ item.count }}</div>
                </div>
              </div>
              <div class="trend-labels">
                <span v-for="(item, index) in hourlyLabels" :key="index" class="trend-label">
                  {{ item }}
                </span>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 节点类型统计 -->
      <div class="node-stats-section">
        <h3>节点类型统计（最近{{ days }}天）</h3>
        <el-card>
          <el-table :data="nodeTypeStats" border stripe>
            <el-table-column prop="node_type" label="节点类型" width="150" />
            <el-table-column prop="execution_count" label="执行次数" width="120" />
            <el-table-column prop="total_duration" label="总耗时(ms)" width="120" />
            <el-table-column prop="avg_duration" label="平均耗时(ms)" width="120" />
            <el-table-column prop="error_count" label="错误次数" width="100" />
            <el-table-column prop="success_rate" label="成功率" width="120">
              <template #default="{ row }">
                <el-progress 
                  :percentage="row.success_rate" 
                  :color="getSuccessRateColor(row.success_rate)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 最近活动 -->
      <div class="activities-section">
        <h3>最近活动</h3>
        <el-card>
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="formatDateTime(activity.created_at)"
              placement="top"
            >
              <el-card>
                <h4>{{ activity.workflow_name }}</h4>
                <p>
                  <el-tag :type="getStatusType(activity.status)" size="small">
                    {{ getStatusLabel(activity.status) }}
                  </el-tag>
                  <span v-if="activity.execution_time" class="execution-time">
                    执行时间: {{ formatTime(activity.execution_time) }}
                  </span>
                </p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>
    </el-card>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import MainLayout from '@/components/MainLayout.vue'
import api from '@/api'

const loading = ref(false)
const days = ref(7)

// 系统概览数据
const overview = ref({
  workflows: 0,
  agents: 0,
  executions: 0,
  data_sources: 0,
  model_configs: 0,
  users: null as number | null
})

// 执行统计数据
const executionStats = ref({
  total: 0,
  status_counts: {} as Record<string, number>,
  success_rate: 0,
  avg_execution_time: 0,
  hourly_trends: [] as Array<{ hour: string; count: number }>
})

// 节点类型统计
const nodeTypeStats = ref([] as Array<{
  node_type: string
  execution_count: number
  total_duration: number
  avg_duration: number
  error_count: number
  success_rate: number
}>)

// 最近活动
const recentActivities = ref([] as Array<{
  id: string
  type: string
  workflow_name: string
  status: string
  created_at: string
  execution_time: number | null
}>)

// 计算概览项
const overviewItems = computed(() => {
  const items = [
    { key: 'workflows', label: '工作流', value: overview.value.workflows },
    { key: 'agents', label: 'Agent', value: overview.value.agents },
    { key: 'executions', label: '执行记录', value: overview.value.executions },
    { key: 'data_sources', label: '数据源', value: overview.value.data_sources },
    { key: 'model_configs', label: '模型配置', value: overview.value.model_configs }
  ]
  if (overview.value.users !== null) {
    items.push({ key: 'users', label: '用户', value: overview.value.users })
  }
  return items
})

// 计算最大趋势值
const maxTrendCount = computed(() => {
  if (executionStats.value.hourly_trends.length === 0) return 1
  return Math.max(...executionStats.value.hourly_trends.map(t => t.count), 1)
})

// 计算小时标签（每4小时显示一个）
const hourlyLabels = computed(() => {
  const labels: string[] = []
  for (let i = 0; i < 24; i += 4) {
    labels.push(`${i.toString().padStart(2, '0')}:00`)
  }
  return labels
})

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    'pending': '等待中',
    'running': '运行中',
    'completed': '已完成',
    'failed': '失败'
  }
  return labels[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return types[status] || 'info'
}

// 格式化时间
const formatTime = (ms: number) => {
  if (!ms) return '0ms'
  if (ms < 1000) return `${ms}ms`
  if (ms < 60000) return `${(ms / 1000).toFixed(2)}s`
  return `${(ms / 60000).toFixed(2)}min`
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

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

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 加载系统概览
    const overviewRes = await api.get('/api/v1/monitoring/overview')
    overview.value = overviewRes.data

    // 加载执行统计
    const statsRes = await api.get(`/api/v1/monitoring/executions?days=${days.value}`)
    executionStats.value = statsRes.data

    // 加载节点类型统计
    const nodeStatsRes = await api.get(`/api/v1/monitoring/node-types?days=${days.value}`)
    nodeTypeStats.value = nodeStatsRes.data

    // 加载最近活动
    const activitiesRes = await api.get('/api/v1/monitoring/activities?limit=10')
    recentActivities.value = activitiesRes.data
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '加载监控数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
  // 每30秒自动刷新
  setInterval(() => {
    loadData()
  }, 30000)
})
</script>

<style scoped>
.monitoring-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.overview-section,
.statistics-section,
.node-stats-section,
.activities-section {
  margin-bottom: 30px;
}

.overview-section h3,
.statistics-section h3,
.node-stats-section h3,
.activities-section h3 {
  margin-bottom: 20px;
  color: #409eff;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

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

.status-item {
  margin-bottom: 15px;
}

.status-label {
  display: inline-block;
  width: 100px;
  font-size: 14px;
}

.stat-summary {
  display: flex;
  justify-content: space-around;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.summary-item {
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-item .value {
  display: block;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.summary-item .value.success {
  color: #67c23a;
}

.trend-chart {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  height: 200px;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.trend-bar {
  flex: 1;
  margin: 0 2px;
  background: linear-gradient(to top, #409eff, #79bbff);
  border-radius: 4px 4px 0 0;
  position: relative;
  min-height: 20px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 5px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.trend-bar:hover {
  opacity: 0.8;
}

.trend-value {
  font-size: 10px;
  color: white;
  font-weight: bold;
}

.trend-labels {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  font-size: 12px;
  color: #909399;
}

.trend-label {
  flex: 1;
  text-align: center;
}

.execution-time {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}
</style>
