<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { getDashboardStats } from '../../api/admin/dashboard'
import {
  Setting,
  Fold,
  Expand,
  ArrowDown,
  DataBoard,
  User,
  Headset,
  Files,
  Avatar,
  Picture,
  ChatDotRound,
  Collection,
  VideoPlay
} from '@element-plus/icons-vue'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
])

// 统计数据
const stats = ref({
  userCount: 0,
  musicCount: 0,
  playlistCount: 0,
  singerCount: 0,
  playCount: 0
})

// 最新用户和音乐
const latestUsers = ref([])
const latestMusics = ref([])

// 图表数据
const userGrowthData = ref([])
const musicTypeData = ref([])
const playCountData = ref([])

// 加载状态
const loading = ref(false)

// 图表实例
let userChart = null
let musicChart = null
let playlistChart = null

// 获取统计数据
const fetchStats = async () => {
  const loadingInstance = ElLoading.service({
    target: '.dashboard-container',
    text: '正在加载数据...',
    background: 'rgba(255, 255, 255, 0.7)'
  })

  try {
    loading.value = true
    console.log('开始获取控制台统计数据')
    const res = await getDashboardStats()
    console.log('获取控制台统计数据成功:', res)

    if (res.code === 200) {
      const data = res.data || {}

      // 设置基础统计数据
      stats.value = {
        userCount: data.userCount || 0,
        musicCount: data.musicCount || 0,
        playlistCount: data.playlistCount || 0,
        singerCount: data.singerCount || 0,
        playCount: data.playCount || 0
      }

      // 设置图表数据
      userGrowthData.value = data.userGrowth || []
      musicTypeData.value = data.musicTypeDistribution || []
      playCountData.value = data.playCountData || []

      // 设置最新用户和音乐
      latestUsers.value = data.latestUsers || []
      latestMusics.value = data.latestMusics || []

      // 初始化图表
      setTimeout(() => {
        try {
          initUserChart()
          initMusicChart()
          initPlaylistChart()
        } catch (error) {
          console.error('初始化图表失败:', error)
        }
      }, 100)
    } else {
      console.error('获取统计数据失败, 响应码非200:', res.code, res.message)
      ElMessage.error(res.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败，请稍后再试')
  } finally {
    loading.value = false
    loadingInstance.close()
  }
}

// 初始化用户增长图表
const initUserChart = () => {
  const chartDom = document.getElementById('userChart')
  if (!chartDom) return

  userChart = echarts.init(chartDom)

  // 准备数据
  const xAxisData = userGrowthData.value.map(item => item.name)
  const seriesData = userGrowthData.value.map(item => item.value)

  const option = {
    title: {
      text: '用户增长趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: xAxisData.length > 0 ? xAxisData : ['无数据']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: seriesData.length > 0 ? seriesData : [0],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64, 158, 255, 0.5)'
              },
              {
                offset: 1,
                color: 'rgba(64, 158, 255, 0.1)'
              }
            ]
          }
        }
      }
    ]
  }

  userChart.setOption(option)
}

// 初始化音乐类型分布图表
const initMusicChart = () => {
  const chartDom = document.getElementById('musicChart')
  if (!chartDom) return

  musicChart = echarts.init(chartDom)

  // 准备数据
  const typeData = musicTypeData.value || []

  // 如果没有数据，显示空图表
  if (typeData.length === 0) {
    const option = {
      title: {
        text: '类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: ['50%', '70%'],
          data: [{ value: 100, name: '无数据' }]
        }
      ]
    }
    musicChart.setOption(option)
    return
  }

  // 准备图表数据
  const series = typeData.map((category, index) => {
    const children = category.children || []
    return {
      name: category.name,
      type: 'pie',
      radius: [index === 0 ? '20%' : '50%', (index + 1) * 20 + '%'],
      center: ['50%', '50%'],
      roseType: index === 1 ? 'radius' : undefined,
      itemStyle: {
        borderRadius: 5,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: index === 2
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      data: children.map(item => ({
        value: item.value,
        name: item.name
      }))
    }
  })

  const option = {
    title: {
      text: '类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      type: 'scroll'
    },
    series: series
  }

  musicChart.setOption(option)
}

// 初始化播放量统计图表
const initPlaylistChart = () => {
  const chartDom = document.getElementById('playlistChart')
  if (!chartDom) return

  playlistChart = echarts.init(chartDom)

  // 准备数据
  const xAxisData = playCountData.value.map(item => item.name)
  const seriesData = playCountData.value.map(item => ({
    value: item.value,
    // 根据数值动态设置颜色
    itemStyle: {
      color: function() {
        // 找出最大值
        const maxValue = Math.max(...playCountData.value.map(item => item.value))
        // 如果是最大值的 80% 以上，使用黄色
        if (item.value > maxValue * 0.8) {
          return '#fac858'
        }
        // 如果是最大值的 50% 以上，使用淡绿色
        else if (item.value > maxValue * 0.5) {
          return '#91cc75'
        }
        // 否则使用淡蓝色
        return '#5470c6'
      }()
    }
  }))

  const option = {
    title: {
      text: '近7天播放量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xAxisData.length > 0 ? xAxisData : ['无数据'],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '播放次数'
      }
    ],
    series: [
      {
        name: '播放量',
        type: 'bar',
        barWidth: '60%',
        data: seriesData.length > 0 ? seriesData : [{ value: 0, itemStyle: { color: '#91cc75' } }],
        // 添加标签显示数值
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  }

  playlistChart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  userChart && userChart.resize()
  musicChart && musicChart.resize()
  playlistChart && playlistChart.resize()
}

onMounted(() => {
  fetchStats()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  userChart && userChart.dispose()
  musicChart && musicChart.dispose()
  playlistChart && playlistChart.dispose()
})
</script>

<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon user-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.userCount }}</div>
            <div class="stat-label">用户数量</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon music-icon">
            <el-icon><Headset /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.musicCount }}</div>
            <div class="stat-label">音乐数量</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon playlist-icon">
            <el-icon><Files /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.playlistCount }}</div>
            <div class="stat-label">歌单数量</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon singer-icon">
            <el-icon><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.singerCount }}</div>
            <div class="stat-label">歌手数量</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon play-icon">
            <el-icon><VideoPlay /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.playCount }}</div>
            <div class="stat-label">总播放量</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
            </div>
          </template>
          <div id="userChart" class="chart"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>音乐/歌单/歌手类型分布</span>
            </div>
          </template>
          <div id="musicChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>近7天播放量统计</span>
            </div>
          </template>
          <div id="playlistChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-row :gutter="20" class="activity-row">
      <el-col :span="12">
        <el-card shadow="hover" class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最新用户</span>
              <el-button text>查看更多</el-button>
            </div>
          </template>

          <el-table :data="latestUsers" style="width: 100%">
            <el-table-column prop="username" label="用户名" width="120"></el-table-column>
            <el-table-column prop="nickname" label="昵称"></el-table-column>
            <el-table-column prop="createTime" label="注册时间" width="180"></el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="activity-card">
          <template #header>
            <div class="card-header">
              <span>最新音乐</span>
              <el-button text>查看更多</el-button>
            </div>
          </template>

          <el-table :data="latestMusics" style="width: 100%">
            <el-table-column prop="name" label="音乐名称" width="120"></el-table-column>
            <el-table-column prop="singerName" label="歌手"></el-table-column>
            <el-table-column prop="createTime" label="上传时间" width="180"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: calc(100vh - 60px);
  overflow-y: auto;
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%);
}

/* 自定义滚动条样式 */
.dashboard-container::-webkit-scrollbar {
  width: 8px;
}

.dashboard-container::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.dashboard-container::-webkit-scrollbar-thumb {
  background: rgba(0, 131, 143, 0.5);
  border-radius: 4px;
}

.dashboard-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 131, 143, 0.7);
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  display: flex;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9) !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15) !important;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s;
}

.stat-icon:hover {
  transform: scale(1.1);
}

.stat-icon .el-icon {
  font-size: 30px;
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, #4dd0e1 0%, #26c6da 100%);
}

.music-icon {
  background: linear-gradient(135deg, #80deea 0%, #4dd0e1 100%);
}

.playlist-icon {
  background: linear-gradient(135deg, #b2ebf2 0%, #80deea 100%);
}

.singer-icon {
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  color: #4dd0e1 !important;
}

.play-icon {
  background: linear-gradient(135deg, #26c6da 0%, #00838f 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #0d47a1;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 14px;
  color: #4a4a4a;
  font-weight: 500;
}

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

.chart-card {
  height: 400px;
  background: rgba(255, 255, 255, 0.9) !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.chart {
  width: 100%;
  height: 350px;
}

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

.activity-card {
  height: 400px;
  background: rgba(255, 255, 255, 0.9) !important;
  border-radius: 12px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%) !important;
  border-radius: 12px 12px 0 0 !important;
}

.card-header span {
  font-weight: bold;
  color: #0d47a1;
  font-size: 16px;
}

.el-table {
  --el-table-border-color: #b3e5fc;
  --el-table-header-bg-color: #e1f5fe;
  --el-table-row-hover-bg-color: #b3e5fc;
  border-radius: 8px;
  overflow: hidden;
}

.el-table th.el-table__cell {
  background-color: #e1f5fe !important;
  color: #0d47a1 !important;
  font-weight: bold !important;
}

.el-table .el-table__row {
  background-color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s;
}

.el-table .el-table__row:hover {
  background-color: #b3e5fc !important;
  transform: scale(1.01);
}

.el-button {
  border-radius: 8px !important;
  font-weight: bold !important;
  transition: all 0.3s !important;
}

.el-button--primary {
  background: linear-gradient(135deg, #4dd0e1 0%, #26c6da 100%) !important;
  border: none !important;
}

.el-button--primary:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 4px 8px rgba(38, 198, 218, 0.3) !important;
}
</style>
