<template>
  <div class="dashboard-screen" :class="{ 'fullscreen': isFullscreen }">
    <!-- 头部 -->
    <header class="dashboard-header">
      <h1 class="title">企业培训数据大屏</h1>
      <div class="header-right">
        <span class="current-time">{{ currentTime }}</span>
        <el-button text @click="toggleFullscreen">
          <el-icon><FullScreen /></el-icon>
        </el-button>
        <el-button text @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </header>
    
    <!-- 主内容区 -->
    <main class="dashboard-main" v-loading="loading">
      <!-- 顶部数据卡片 -->
      <section class="top-cards">
        <div class="stat-card" v-for="stat in topStats" :key="stat.key">
          <div class="stat-icon" :style="{ background: stat.color }">
            <el-icon><component :is="stat.icon" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
        </div>
      </section>
      
      <!-- 中间图表区 -->
      <section class="middle-charts">
        <!-- 左侧：部门排行 -->
        <div class="chart-card department-ranking">
          <div class="card-header">
            <h3>部门学习排行</h3>
          </div>
          <div class="chart-content" ref="departmentChartRef"></div>
        </div>
        
        <!-- 中间：学习趋势 -->
        <div class="chart-card trend-chart">
          <div class="card-header">
            <h3>学习趋势（近7天）</h3>
          </div>
          <div class="chart-content" ref="trendChartRef"></div>
        </div>
        
        <!-- 右侧：考试通过率 -->
        <div class="chart-card exam-stats">
          <div class="card-header">
            <h3>考试通过率</h3>
          </div>
          <div class="chart-content" ref="examChartRef"></div>
        </div>
      </section>
      
      <!-- 底部区域 -->
      <section class="bottom-section">
        <!-- 左侧：等级分布 -->
        <div class="chart-card level-distribution">
          <div class="card-header">
            <h3>等级分布</h3>
          </div>
          <div class="chart-content" ref="levelChartRef"></div>
        </div>
        
        <!-- 右侧：实时动态 -->
        <div class="chart-card realtime-activities">
          <div class="card-header">
            <h3>实时动态</h3>
          </div>
          <div class="activities-list">
            <div 
              v-for="activity in activities" 
              :key="activity.id" 
              class="activity-item"
            >
              <span class="activity-type" :class="getActivityClass(activity.type)">
                {{ activity.type }}
              </span>
              <span class="activity-user">{{ activity.user_name }}</span>
              <span class="activity-desc">{{ activity.description }}</span>
              <span class="activity-exp" v-if="activity.exp_amount > 0">
                +{{ activity.exp_amount }}
              </span>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { FullScreen, Refresh, User, TrendCharts, Trophy, Clock, Reading, Medal } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getFullDashboardData, 
  type FullDashboardData, 
  type ActivityItem,
  type DepartmentData 
} from '@/api/dashboard'

// 状态
const loading = ref(false)
const isFullscreen = ref(false)
const currentTime = ref('')
const dashboardData = ref<FullDashboardData | null>(null)
const activities = ref<ActivityItem[]>([])

// 图表引用
const departmentChartRef = ref<HTMLElement | null>(null)
const trendChartRef = ref<HTMLElement | null>(null)
const examChartRef = ref<HTMLElement | null>(null)
const levelChartRef = ref<HTMLElement | null>(null)

// 图表实例
let departmentChart: echarts.ECharts | null = null
let trendChart: echarts.ECharts | null = null
let examChart: echarts.ECharts | null = null
let levelChart: echarts.ECharts | null = null

// 定时器
let timeTimer: number | null = null
let refreshTimer: number | null = null

// 顶部统计数据
const topStats = computed(() => {
  const overview = dashboardData.value?.overview?.overview
  const exam = dashboardData.value?.overview?.exam
  
  return [
    {
      key: 'total_users',
      label: '总学员数',
      value: overview?.total_users || 0,
      icon: 'User',
      color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    },
    {
      key: 'today_active',
      label: '今日活跃',
      value: overview?.today_active || 0,
      icon: 'TrendCharts',
      color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
    },
    {
      key: 'total_hours',
      label: '总学习时长',
      value: `${overview?.total_hours || 0}h`,
      icon: 'Clock',
      color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
    },
    {
      key: 'pass_rate',
      label: '考试通过率',
      value: `${exam?.pass_rate || 0}%`,
      icon: 'Trophy',
      color: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
    },
    {
      key: 'checkin_rate',
      label: '今日签到率',
      value: `${overview?.checkin_rate || 0}%`,
      icon: 'Medal',
      color: 'linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%)'
    }
  ]
})

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 切换全屏
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

// 获取活动样式类
const getActivityClass = (type: string) => {
  const classMap: Record<string, string> = {
    '签到': 'checkin',
    '考试': 'exam',
    '陪练': 'practice',
    '奖章': 'badge',
    '学习': 'study'
  }
  return classMap[type] || 'default'
}

// 初始化部门排行图表
const initDepartmentChart = (departments: DepartmentData[]) => {
  if (!departmentChartRef.value) return
  
  if (departmentChart) {
    departmentChart.dispose()
  }
  
  departmentChart = echarts.init(departmentChartRef.value)
  
  const top10 = departments.slice(0, 10)
  
  departmentChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: { color: '#a0a0a0' },
      axisLine: { lineStyle: { color: '#333' } },
      splitLine: { lineStyle: { color: '#333' } }
    },
    yAxis: {
      type: 'category',
      data: top10.map(d => d.name).reverse(),
      axisLabel: { color: '#fff' },
      axisLine: { lineStyle: { color: '#333' } }
    },
    series: [{
      name: '考试通过率',
      type: 'bar',
      data: top10.map(d => d.pass_rate).reverse(),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#667eea' },
          { offset: 1, color: '#764ba2' }
        ])
      },
      label: {
        show: true,
        position: 'right',
        formatter: '{c}%',
        color: '#fff'
      }
    }]
  })
}

// 初始化趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value || !dashboardData.value?.trend) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  trendChart = echarts.init(trendChartRef.value)
  
  const trend = dashboardData.value.trend
  
  trendChart.setOption({
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['活跃用户', '学习时长', '考试次数'],
      textStyle: { color: '#a0a0a0' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trend.dates.map(d => d.slice(5)),
      axisLabel: { color: '#a0a0a0' },
      axisLine: { lineStyle: { color: '#333' } }
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#a0a0a0' },
      axisLine: { lineStyle: { color: '#333' } },
      splitLine: { lineStyle: { color: '#333' } }
    },
    series: [
      {
        name: '活跃用户',
        type: 'line',
        smooth: true,
        data: trend.trend.map(t => t.active_users),
        itemStyle: { color: '#667eea' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(102, 126, 234, 0.3)' },
            { offset: 1, color: 'rgba(102, 126, 234, 0.05)' }
          ])
        }
      },
      {
        name: '学习时长',
        type: 'line',
        smooth: true,
        data: trend.trend.map(t => t.learning_hours),
        itemStyle: { color: '#43e97b' }
      },
      {
        name: '考试次数',
        type: 'line',
        smooth: true,
        data: trend.trend.map(t => t.exam_count),
        itemStyle: { color: '#fa709a' }
      }
    ]
  })
}

// 初始化考试通过率图表
const initExamChart = () => {
  if (!examChartRef.value || !dashboardData.value) return
  
  if (examChart) {
    examChart.dispose()
  }
  
  examChart = echarts.init(examChartRef.value)
  
  const exam = dashboardData.value.overview.exam
  
  examChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    series: [{
      name: '考试统计',
      type: 'gauge',
      radius: '85%',
      startAngle: 180,
      endAngle: 0,
      min: 0,
      max: 100,
      splitNumber: 10,
      axisLine: {
        lineStyle: {
          width: 20,
          color: [
            [0.6, '#f56c6c'],
            [0.8, '#e6a23c'],
            [1, '#67c23a']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: { show: false },
      splitLine: { show: false },
      axisLabel: {
        color: '#a0a0a0',
        fontSize: 10,
        distance: -30
      },
      title: {
        offsetCenter: [0, '30%'],
        color: '#fff',
        fontSize: 14
      },
      detail: {
        fontSize: 24,
        offsetCenter: [0, '-10%'],
        valueAnimation: true,
        formatter: '{value}%',
        color: '#fff'
      },
      data: [{
        value: exam.pass_rate,
        name: '通过率'
      }]
    }]
  })
}

// 初始化等级分布图表
const initLevelChart = () => {
  if (!levelChartRef.value || !dashboardData.value) return
  
  if (levelChart) {
    levelChart.dispose()
  }
  
  levelChart = echarts.init(levelChartRef.value)
  
  const dist = dashboardData.value.level_distribution
  
  levelChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    series: [{
      name: '等级分布',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 4,
        borderColor: '#1a1a2e',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: 'Lv.{b}\n{c}人',
        color: '#fff'
      },
      data: dist.levels.map((level, i) => ({
        value: dist.counts[i],
        name: level.toString(),
        itemStyle: {
          color: `hsl(${(level - 1) * 36}, 70%, 50%)`
        }
      })).filter(d => d.value > 0)
    }]
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  
  try {
    const res = await getFullDashboardData()
    
    if (res.code === 200 && res.data) {
      dashboardData.value = res.data
      activities.value = res.data.activities || []
      
      await nextTick()
      
      // 初始化图表
      initDepartmentChart(res.data.departments)
      initTrendChart()
      initExamChart()
      initLevelChart()
    }
  } catch (error) {
    console.error('获取大屏数据失败:', error)
  } finally {
    loading.value = false
  }
}

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

// 处理窗口大小变化
const handleResize = () => {
  departmentChart?.resize()
  trendChart?.resize()
  examChart?.resize()
  levelChart?.resize()
}

// 初始化
onMounted(() => {
  updateTime()
  timeTimer = window.setInterval(updateTime, 1000)
  
  fetchData()
  
  // 每5分钟自动刷新
  refreshTimer = window.setInterval(refreshData, 5 * 60 * 1000)
  
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  if (timeTimer) clearInterval(timeTimer)
  if (refreshTimer) clearInterval(refreshTimer)
  
  departmentChart?.dispose()
  trendChart?.dispose()
  examChart?.dispose()
  levelChart?.dispose()
  
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.dashboard-screen {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #fff;
  padding: 20px;
  
  &.fullscreen {
    padding: 24px;
  }
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .title {
    font-size: 28px;
    font-weight: 600;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .current-time {
      font-size: 14px;
      color: #a0a0a0;
    }
    
    .el-button {
      color: #a0a0a0;
      
      &:hover {
        color: #667eea;
      }
    }
  }
}

.dashboard-main {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.top-cards {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
  
  .stat-card {
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    
    .stat-icon {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .el-icon {
        font-size: 28px;
        color: #fff;
      }
    }
    
    .stat-info {
      .stat-value {
        font-size: 28px;
        font-weight: 600;
      }
      
      .stat-label {
        font-size: 13px;
        color: #a0a0a0;
        margin-top: 4px;
      }
    }
  }
}

.middle-charts {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 20px;
}

.bottom-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
  
  .card-header {
    padding: 16px 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    
    h3 {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
    }
  }
  
  .chart-content {
    height: 280px;
    padding: 16px;
  }
}

.realtime-activities {
  .activities-list {
    height: 280px;
    overflow-y: auto;
    padding: 8px 16px;
    
    &::-webkit-scrollbar {
      width: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 2px;
    }
    
    .activity-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 10px 0;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      font-size: 13px;
      
      &:last-child {
        border-bottom: none;
      }
      
      .activity-type {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 500;
        
        &.checkin { background: #67c23a; }
        &.exam { background: #e6a23c; }
        &.practice { background: #409eff; }
        &.badge { background: #f56c6c; }
        &.study { background: #909399; }
        &.default { background: #606266; }
      }
      
      .activity-user {
        color: #fff;
        font-weight: 500;
        min-width: 80px;
      }
      
      .activity-desc {
        color: #a0a0a0;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .activity-exp {
        color: #67c23a;
        font-weight: 600;
      }
    }
  }
}

// 响应式
@media (max-width: 1400px) {
  .top-cards {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .middle-charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1024px) {
  .top-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .bottom-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard-screen {
    padding: 12px;
  }
  
  .dashboard-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
    
    .title {
      font-size: 22px;
    }
  }
  
  .top-cards {
    grid-template-columns: 1fr;
    
    .stat-card {
      padding: 16px;
      
      .stat-icon {
        width: 48px;
        height: 48px;
        
        .el-icon {
          font-size: 24px;
        }
      }
      
      .stat-info .stat-value {
        font-size: 24px;
      }
    }
  }
  
  .chart-card .chart-content {
    height: 220px;
  }
}
</style>
