<template>
  <div class="dashboard-container">
    <h2 class="page-title">数据面板</h2>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#409EFF"><User /></el-icon>
            <div class="stat-info">
              <p class="stat-label">总用户数</p>
              <h3 class="stat-value">{{ stats.totalUsers }}</h3>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#67C23A"><Calendar /></el-icon>
            <div class="stat-info">
              <p class="stat-label">活动数量</p>
              <h3 class="stat-value">{{ stats.totalActivities }}</h3>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#E6A23C"><TrophyBase /></el-icon>
            <div class="stat-info">
              <p class="stat-label">成功案例</p>
              <h3 class="stat-value">{{ stats.totalCases }}</h3>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <el-icon class="stat-icon" color="#F56C6C"><Reading /></el-icon>
            <div class="stat-info">
              <p class="stat-label">课程数量</p>
              <h3 class="stat-value">{{ stats.totalCourses }}</h3>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="hover">
          <template #header>
            <span>用户增长趋势</span>
          </template>
          <div ref="userTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :md="12">
        <el-card shadow="hover">
          <template #header>
            <span>活动报名统计</span>
          </template>
          <div ref="activityStatsChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最近活动 -->
    <el-card shadow="hover" class="recent-activities">
      <template #header>
        <span>最近活动</span>
      </template>
      <el-table :data="recentActivities" stripe style="width: 100%">
        <el-table-column prop="name" label="活动名称" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'success' : 'primary'" size="small">
              {{ row.type === 1 ? '线上' : '线下' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="participants" label="报名人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { User, Calendar, TrophyBase, Reading } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/utils/request'

const stats = ref({
  totalUsers: 0,
  totalActivities: 0,
  totalCases: 0,
  totalCourses: 0
})

const recentActivities = ref([])
const userTrendChart = ref(null)
const activityStatsChart = ref(null)
let userChart = null
let activityChart = null

const loadStats = async () => {
  try {
    const response = await request.get('/admin/dashboard/stats')
    if (response.code === 200) {
      stats.value = {
        totalUsers: response.data.totalUsers || 0,
        totalActivities: response.data.totalActivities || 0,
        totalCases: response.data.totalCases || 0,
        totalCourses: response.data.totalCourses || 0
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 使用默认值
    stats.value = {
      totalUsers: 0,
      totalActivities: 0,
      totalCases: 0,
      totalCourses: 0
    }
  }
}

const loadRecentActivities = async () => {
  try {
    const response = await request.get('/admin/dashboard/recent-activities', {
      params: { limit: 5 }
    })
    if (response.code === 200) {
      // 处理活动数据
      const activities = response.data || []
      recentActivities.value = activities.map(activity => ({
        name: activity.name || '未命名活动',
        type: activity.type || 2,
        participants: activity.actualParticipants || 0,
        status: getActivityStatus(activity),
        startTime: formatDateTime(activity.startTime) || '-'
      }))
      console.log('最近活动数据:', recentActivities.value)
    }
  } catch (error) {
    console.error('加载最近活动失败:', error)
    recentActivities.value = []
  }
}

// 根据时间判断活动状态
const getActivityStatus = (activity) => {
  if (!activity.startTime || !activity.endTime) return 1
  
  const now = new Date()
  const start = new Date(activity.startTime)
  const end = new Date(activity.endTime)
  
  if (now < start) return 1 // 未开始
  if (now >= start && now <= end) return 2 // 进行中
  return 3 // 已结束
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const getStatusType = (status) => {
  const types = { 1: 'info', 2: 'success', 3: 'warning' }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = { 1: '未开始', 2: '进行中', 3: '已结束' }
  return texts[status] || '未知'
}

// 初始化用户增长趋势图表
const initUserTrendChart = async () => {
  if (!userTrendChart.value) {
    console.warn('用户趋势图表 DOM 未准备好')
    return
  }
  
  try {
    const response = await request.get('/admin/dashboard/user-trend', {
      params: { days: 7 }
    })
    
    if (response.code === 200 && response.data) {
      // 确保 DOM 已渲染完成
      await nextTick()
      
      // 如果已经有实例，先销毁
      if (userChart) {
        userChart.dispose()
      }
      
      userChart = echarts.init(userTrendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: response.data.dates || [],
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '用户数'
        },
        series: [{
          name: '新增用户',
          type: 'line',
          smooth: true,
          data: response.data.counts || [],
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(64, 158, 255, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(64, 158, 255, 0.05)'
              }]
            }
          }
        }]
      }
      
      userChart.setOption(option)
    }
  } catch (error) {
    console.error('加载用户趋势图表失败:', error)
  }
}

// 初始化活动报名统计图表
const initActivityStatsChart = async () => {
  if (!activityStatsChart.value) {
    console.warn('活动统计图表 DOM 未准备好')
    return
  }
  
  try {
    const response = await request.get('/admin/dashboard/activity-stats', {
      params: { days: 7 }
    })
    
    if (response.code === 200 && response.data) {
      // 确保 DOM 已渲染完成
      await nextTick()
      
      // 如果已经有实例，先销毁
      if (activityChart) {
        activityChart.dispose()
      }
      
      activityChart = echarts.init(activityStatsChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: response.data.dates || [],
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '报名人数'
        },
        series: [{
          name: '活动报名',
          type: 'bar',
          data: response.data.counts || [],
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: '#E91E63'
              }, {
                offset: 1,
                color: '#F06292'
              }]
            },
            borderRadius: [8, 8, 0, 0]
          }
        }]
      }
      
      activityChart.setOption(option)
    }
  } catch (error) {
    console.error('加载活动统计图表失败:', error)
  }
}

onMounted(async () => {
  // 加载统计数据
  await loadStats()
  await loadRecentActivities()
  
  // 确保 DOM 完全渲染后再初始化图表
  await nextTick()
  
  // 使用 setTimeout 确保 ECharts 能找到 DOM
  setTimeout(async () => {
    await initUserTrendChart()
    await initActivityStatsChart()
  }, 300)
  
  // 监听窗口大小变化，自动调整图表
  const handleResize = () => {
    if (userChart) userChart.resize()
    if (activityChart) activityChart.resize()
  }
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 销毁图表实例
  if (userChart) {
    userChart.dispose()
    userChart = null
  }
  if (activityChart) {
    activityChart.dispose()
    activityChart = null
  }
  
  // 移除事件监听
  window.removeEventListener('resize', () => {})
})
</script>

<style scoped>
/* ==================== 仪表盘容器 ==================== */
.dashboard-container {
  padding: 0;
  animation: fadeIn 0.5s ease-out;
}

/* 页面标题 */
.page-title {
  font-size: var(--font-3xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin: 0 0 var(--spacing-xl) 0;
  position: relative;
  padding-bottom: var(--spacing-md);
}

.page-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, var(--primary-color), var(--primary-light));
  border-radius: 2px;
}

/* ==================== 统计卡片区域 ==================== */
.stats-row {
  margin-bottom: var(--spacing-xl);
}

.stat-card {
  cursor: pointer;
  transition: all var(--transition-base);
  border: 1px solid var(--border-color);
  background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
  height: 100px;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 70%);
  transform: translate(20px, -20px);
  transition: all var(--transition-slow);
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: var(--shadow-lg);
  border-color: var(--primary-light);
}

.stat-card:hover::before {
  transform: translate(10px, -10px) scale(1.2);
}

/* 统计卡片内容 */
.stat-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-xl);
  padding: var(--spacing-md);
  position: relative;
  z-index: 1;
}

.stat-icon {
  font-size: 52px;
  flex-shrink: 0;
  transition: transform var(--transition-base);
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
}

.stat-card:hover .stat-icon {
  transform: scale(1.1) rotate(5deg);
}

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

.stat-label {
  font-size: var(--font-sm);
  color: var(--text-secondary);
  margin: 0 0 var(--spacing-sm) 0;
  font-weight: var(--font-medium);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: var(--font-4xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin: 0;
  line-height: 1.2;
  /* 移除渐变文字效果，确保数字清晰可见 */
}

/* ==================== 图表区域 ==================== */
.charts-row {
  margin-bottom: var(--spacing-xl);
}

.charts-row .el-card {
  height: 100%;
  border: 1px solid var(--border-color);
  transition: all var(--transition-base);
}

.charts-row .el-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.charts-row .el-card :deep(.el-card__header) {
  background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
  font-size: var(--font-md);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  border-bottom: 2px solid var(--border-color);
}

.chart-container {
  width: 100%;
  height: 320px;
  padding: var(--spacing-md);
}

/* ==================== 最近活动表格 ==================== */
.recent-activities {
  margin-top: var(--spacing-xl);
  border: 1px solid var(--border-color);
  transition: all var(--transition-base);
}

.recent-activities:hover {
  box-shadow: var(--shadow-md);
}

.recent-activities :deep(.el-card__header) {
  background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
  font-size: var(--font-md);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
  border-bottom: 2px solid var(--border-color);
}

/* 表格样式增强 */
.recent-activities :deep(.el-table) {
  font-size: var(--font-sm);
}

.recent-activities :deep(.el-table__header-wrapper) {
  border-radius: var(--radius-base) var(--radius-base) 0 0;
}

.recent-activities :deep(.el-table th) {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  font-weight: var(--font-semibold);
}

.recent-activities :deep(.el-table td) {
  color: var(--text-secondary);
}

.recent-activities :deep(.el-table__row:hover) {
  background-color: var(--bg-hover);
}

/* 标签样式 */
.recent-activities :deep(.el-tag) {
  font-weight: var(--font-medium);
  border-radius: var(--radius-sm);
  padding: 4px 12px;
}

/* ==================== 响应式设计 ==================== */

/* 平板设备 */
@media (max-width: 1024px) {
  .page-title {
    font-size: var(--font-2xl);
  }

  .stat-value {
    font-size: var(--font-3xl);
  }

  .stat-icon {
    font-size: 44px;
  }

  .chart-container {
    height: 280px;
  }
}

/* 移动设备 */
@media (max-width: 768px) {
  .page-title {
    font-size: var(--font-xl);
    margin-bottom: var(--spacing-lg);
  }

  .stats-row {
    margin-bottom: var(--spacing-lg);
  }

  .stat-content {
    gap: var(--spacing-md);
    padding: var(--spacing-sm);
  }

  .stat-icon {
    font-size: 36px;
  }

  .stat-value {
    font-size: var(--font-2xl);
  }

  .stat-label {
    font-size: var(--font-xs);
  }

  .chart-container {
    height: 240px;
    padding: var(--spacing-sm);
  }

  .charts-row {
    margin-bottom: var(--spacing-lg);
  }

  .recent-activities :deep(.el-table) {
    font-size: var(--font-xs);
  }
}

/* 超小屏幕 */
@media (max-width: 480px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
  }

  .chart-container {
    height: 200px;
  }
}

/* 超大屏幕 */
@media (min-width: 1920px) {
  .chart-container {
    height: 380px;
  }

  .stat-value {
    font-size: var(--font-5xl);
  }
}
</style>

