<template>
  <div class="admin-dashboard admin-theme">
    <AdminSidebar active="dashboard" />

    <!-- 主内容区域 -->
    <main class="main-content">
      <AdminHeader :title="$t('nav.dashboard')" />

      <!-- 统计卡片 -->
      <div class="stats-cards" :spinning="loading">
        <div class="stat-card">
          <div class="stat-icon users">
            <UserOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('dashboard.totalUsers') }}</div>
            <div class="stat-number">{{ formatNumber(stats.totalUsers) }}</div>
            <div class="stat-change" :class="stats.totalUsersChange >= 0 ? 'positive' : 'negative'">
              {{ stats.totalUsersChange >= 0 ? '+' : '' }}{{ stats.totalUsersChange }}% {{ $t('dashboard.comparedToLastMonth') }}
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon paid-users">
            <UserOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('dashboard.paidUsers') }}</div>
            <div class="stat-number">{{ formatNumber(stats.paidUsers) }}</div>
            <div class="stat-change" :class="stats.paidUsersChange >= 0 ? 'positive' : 'negative'">
              {{ stats.paidUsersChange >= 0 ? '+' : '' }}{{ stats.paidUsersChange }}% {{ $t('dashboard.comparedToLastMonth') }}
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon revenue">
            <DollarOutlined />
          </div>
          <div class="stat-content">
            <div class="stat-title">{{ $t('dashboard.todayRevenue') }}</div>
            <div class="stat-number">{{ formatCurrency(stats.todayRevenue) }}</div>
            <div class="stat-change" :class="stats.todayRevenueChange >= 0 ? 'positive' : 'negative'">
              {{ stats.todayRevenueChange >= 0 ? '+' : '' }}{{ stats.todayRevenueChange }}% {{ $t('dashboard.comparedToYesterday') }}
            </div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <!-- 日活用户趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>{{ $t('dashboard.dailyActive') }}</h3>
            <div class="year-picker">
              <a-button size="small" @click="changeYear(-1)" :disabled="selectedYear <= 2025"><template #icon><LeftOutlined /></template></a-button>
              <span class="year-display">{{ selectedYear }}{{ $t('dashboard.yearSuffix') }}</span>
              <a-button size="small" @click="changeYear(1)" :disabled="selectedYear >= 2099"><template #icon><RightOutlined /></template></a-button>
            </div>
          </div>
          <div class="chart-content">
            <div ref="dailyActiveChart" style="width: 100%; height: 100%;"></div>
          </div>
        </div>

        <!-- 用户转化率 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>{{ $t('dashboard.conversionRate') }}</h3>
            <div class="year-picker">
              <a-button size="small" @click="changeYear2(-1)" :disabled="selectedYear2 <= 2025"><template #icon><LeftOutlined /></template></a-button>
              <span class="year-display">{{ selectedYear2 }}{{ $t('dashboard.yearSuffix') }}</span>
              <a-button size="small" @click="changeYear2(1)" :disabled="selectedYear2 >= 2099"><template #icon><RightOutlined /></template></a-button>
            </div>
          </div>
          <div class="chart-content">
            <div ref="conversionChart" style="width: 100%; height: 100%;"></div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import {
  UserOutlined,
  LeftOutlined,
  RightOutlined,
  DollarOutlined
} from '@ant-design/icons-vue'
import { getDashboardOverview, getConversionRate, getDailyActiveUsersTrend } from '@/api/dashboard'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'

const { t } = useI18n()

// 年份选择
const currentYear = new Date().getFullYear()
const selectedYear = ref(currentYear)
const selectedYear2 = ref(currentYear)

// 切换年份
const changeYear = (delta) => {
  const newYear = selectedYear.value + delta
  if (newYear >= 2025 && newYear <= 2099) {
    selectedYear.value = newYear
    loadDailyActiveChart()
  }
}

const changeYear2 = (delta) => {
  const newYear = selectedYear2.value + delta
  if (newYear >= 2025 && newYear <= 2099) {
    selectedYear2.value = newYear
    loadConversionChart()
  }
}

// 统计数据
const stats = ref({
  totalUsers: 0,
  paidUsers: 0,
  todayRevenue: 0,
  totalUsersChange: 0,
  paidUsersChange: 0,
  todayRevenueChange: 0
})

const loading = ref(false)

// 图表相关
const dailyActiveChart = ref(null)
const conversionChart = ref(null)
let dailyActiveChartInstance = null
let conversionChartInstance = null

// 动态加载ECharts
const loadECharts = () => {
  return new Promise((resolve, reject) => {
    if (window.echarts) {
      resolve(window.echarts)
      return
    }
    
    const script = document.createElement('script')
    script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js'
    script.onload = () => resolve(window.echarts)
    script.onerror = reject
    document.head.appendChild(script)
  })
}

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toLocaleString('zh-CN')
}

// 格式化货币
const formatCurrency = (amount) => {
  if (amount >= 10000) {
    return '¥' + (amount / 10000).toFixed(1) + '万'
  }
  return '¥' + amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  loading.value = true
  try {
    // 获取概览数据
    const overviewRes = await getDashboardOverview()
    console.log('仪表盘概览数据响应:', overviewRes)
    
    // 后端直接返回Map，没有success/data包装
    const data = overviewRes?.data || overviewRes || {}
    console.log('解析后的数据:', data)
    
    if (data && !data.error) {
      stats.value = {
        totalUsers: data.totalUsers || 0,
        paidUsers: data.paidUsers || 0,
        todayRevenue: data.todayRevenue || 0,
        totalUsersChange: data.totalUsersChange ?? 0,
        paidUsersChange: data.paidUsersChange ?? 0,
        todayRevenueChange: data.todayRevenueChange ?? 0
      }
      console.log('设置后的统计数据:', stats.value)
    } else {
      console.error('Get dashboard data failed:', data.error || data.message)
      message.error(t('dashboard.loadDataFailed') + ': ' + (data.message || t('dashboard.unknownError')))
    }
    
  } catch (error) {
    console.error('Load dashboard data failed:', error)
    message.error(t('dashboard.loadDataFailed') + ': ' + (error.message || t('dashboard.unknownError')))
  } finally {
    loading.value = false
  }
}

// 加载日活用户趋势图
const loadDailyActiveChart = async () => {
  try {
    const response = await getDailyActiveUsersTrend(selectedYear.value, 'monthly')
    const data = response.data || {}
    
    if (!dailyActiveChart.value) return
    
    const echarts = await loadECharts()
    await nextTick()
    
    if (dailyActiveChartInstance) {
      dailyActiveChartInstance.dispose()
    }
    
    dailyActiveChartInstance = echarts.init(dailyActiveChart.value)
    
    // 始终显示12个月
    const allMonths = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const monthlyData = data.monthlyData || []
    
    // 创建月份到数据的映射
    const monthDataMap = {}
    monthlyData.forEach(item => {
      monthDataMap[item.month] = item
    })
    
    // 填充12个月的数据，没有数据的月份为0
    const values = []
    for (let i = 1; i <= 12; i++) {
      const monthData = monthDataMap[i] || { avgDailyActive: 0, dailyActiveUsers: 0 }
      values.push(monthData.avgDailyActive || monthData.dailyActiveUsers || 0)
    }
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: allMonths,
        axisLabel: {
          color: '#6b7280'
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#6b7280',
          formatter: '{value}'
        }
      },
      series: [{
        name: '日活用户',
        type: 'line',
        smooth: true,
        data: values,
        itemStyle: {
          color: '#3b82f6'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(59, 130, 246, 0.3)'
            }, {
              offset: 1,
              color: 'rgba(59, 130, 246, 0.1)'
            }]
          }
        }
      }]
    }
    
    dailyActiveChartInstance.setOption(option)
    
    // 响应式调整
    window.addEventListener('resize', () => {
      if (dailyActiveChartInstance) {
        dailyActiveChartInstance.resize()
      }
    })
  } catch (error) {
    console.error('加载日活用户趋势图失败:', error)
  }
}

// 加载用户转化率图
const loadConversionChart = async () => {
  try {
    const response = await getConversionRate(selectedYear2.value)
    const data = response.data || {}
    
    if (!conversionChart.value) return
    
    const echarts = await loadECharts()
    await nextTick()
    
    if (conversionChartInstance) {
      conversionChartInstance.dispose()
    }
    
    conversionChartInstance = echarts.init(conversionChart.value)
    
    // 始终显示12个月
    const allMonths = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const monthlyData = data.monthlyData || []
    
    // 创建月份到数据的映射
    const monthDataMap = {}
    monthlyData.forEach(item => {
      monthDataMap[item.month] = item
    })
    
    // 填充12个月的数据，没有数据的月份为0
    const conversionRates = []
    const fullMonthlyData = []
    for (let i = 1; i <= 12; i++) {
      const monthData = monthDataMap[i] || { month: i, conversionRate: 0, totalUsers: 0, paidUsers: 0 }
      conversionRates.push(monthData.conversionRate || 0)
      fullMonthlyData.push(monthData)
    }
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params) => {
          const item = params[0]
          const monthData = fullMonthlyData[item.dataIndex]
          return `${item.name}<br/>转化率: ${item.value}%<br/>总用户: ${monthData?.totalUsers || 0}<br/>付费用户: ${monthData?.paidUsers || 0}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: allMonths,
        axisLabel: {
          color: '#6b7280'
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#6b7280',
          formatter: '{value}%'
        }
      },
      series: [{
        name: '转化率',
        type: 'bar',
        data: conversionRates,
        barWidth: '40%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: '#8b5cf6'
            }, {
              offset: 1,
              color: '#3b82f6'
            }]
          },
          borderRadius: [4, 4, 0, 0]
        }
      }]
    }
    
    conversionChartInstance.setOption(option)
    
    // 响应式调整
    window.addEventListener('resize', () => {
      if (conversionChartInstance) {
        conversionChartInstance.resize()
      }
    })
  } catch (error) {
    console.error('加载用户转化率图失败:', error)
  }
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('后台管理页面加载完成')
  await loadDashboardData()
  await nextTick()
  await loadDailyActiveChart()
  await loadConversionChart()
})

// 组件卸载时清理图表
onUnmounted(() => {
  if (dailyActiveChartInstance) {
    dailyActiveChartInstance.dispose()
    dailyActiveChartInstance = null
  }
  if (conversionChartInstance) {
    conversionChartInstance.dispose()
    conversionChartInstance = null
  }
})
</script>

<style scoped>
.admin-dashboard {
  display: flex;
  height: 100vh;
  background: var(--bg-base);
  font-family: var(--font-sans);
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-base);
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--space-6);
  padding: var(--space-6);
}

.stat-card {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  padding: var(--space-6);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-subtle);
  display: flex;
  align-items: center;
  gap: var(--space-4);
  transition: var(--transition-all);
}

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

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--text-xl);
}

.stat-icon.users {
  background: var(--warning-glow);
  color: var(--warning-400);
}

.stat-icon.paid-users {
  background: var(--primary-glow-light);
  color: var(--primary-400);
}

.stat-icon.revenue {
  background: rgba(236, 72, 153, 0.10);
  color: #db2777;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  margin-bottom: var(--space-2);
  font-weight: var(--font-medium);
}

.stat-number {
  font-size: var(--text-3xl);
  font-weight: var(--font-bold);
  color: var(--text-primary);
  margin-bottom: var(--space-1);
}

.stat-change {
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
}

.stat-change.positive {
  color: var(--success-400);
}

.stat-change.negative {
  color: var(--error-400);
}

/* 图表区域 */
.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-6);
  padding: 0 var(--space-6) var(--space-6);
}

.chart-card {
  background: var(--bg-surface);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-subtle);
  overflow: hidden;
}

.chart-header {
  padding: var(--space-5) var(--space-6) var(--space-4);
  border-bottom: 1px solid var(--border-subtle);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-header h3 {
  margin: 0;
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  color: var(--text-primary);
}

.year-picker {
  display: flex;
  align-items: center;
  gap: var(--space-2);
}

.year-display {
  font-size: var(--text-sm);
  font-weight: var(--font-medium);
  color: var(--text-primary);
  min-width: 60px;
  text-align: center;
}

.year-picker .ant-btn {
  --el-button-bg-color: transparent;
  --el-button-border-color: var(--border-default);
  --el-button-hover-bg-color: var(--bg-hover);
  --el-button-hover-border-color: var(--primary-500);
}

.year-select {
  width: 100px;
}

.chart-content {
  padding: var(--space-6);
  height: 300px;
}

.chart-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: var(--bg-elevated);
  border-radius: var(--radius-md);
  border: 2px dashed var(--border-default);
}

.chart-title {
  font-size: var(--text-base);
  font-weight: var(--font-semibold);
  color: var(--text-secondary);
  margin-bottom: var(--space-2);
}

.chart-description {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .admin-dashboard {
    flex-direction: column;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
    padding: var(--space-4);
  }
  
  .charts-section {
    padding: 0 var(--space-4) var(--space-4);
  }
}

@media (max-width: 480px) {
  .stat-card {
    padding: var(--space-4);
  }
  
  .stat-number {
    font-size: var(--text-2xl);
  }
  
  .chart-content {
    padding: var(--space-4);
    height: 250px;
  }
}
</style>
