<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>数据仪表盘</h1>
      <p class="dashboard-subtitle">系统数据概览与关键指标监控</p>
    </div>

    <!-- 概览卡片 -->
    <div class="overview-cards">
      <div class="card">
        <div class="card-icon users">
          <i class="fas fa-users"></i>
        </div>
        <div class="card-content">
          <h3>{{ overviewData.totalUsers || 0 }}</h3>
          <p>用户总数</p>
        </div>
      </div>
      
      <div class="card">
        <div class="card-icon paying">
          <i class="fas fa-credit-card"></i>
        </div>
        <div class="card-content">
          <h3>{{ overviewData.payingUsers || 0 }}</h3>
          <p>付费用户数</p>
        </div>
      </div>
      
      <div class="card">
        <div class="card-icon revenue">
          <i class="fas fa-dollar-sign"></i>
        </div>
        <div class="card-content">
          <h3>¥{{ formatNumber(overviewData.todayRevenue || 0) }}</h3>
          <p>今日收入</p>
        </div>
      </div>
      
      <div class="card">
        <div class="card-icon conversion">
          <i class="fas fa-chart-line"></i>
        </div>
        <div class="card-content">
          <h3>{{ overviewData.conversionRate || 0 }}%</h3>
          <p>转化率</p>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-container">
        <h3>日活用户趋势</h3>
        <div class="chart" ref="dailyActiveChart"></div>
      </div>
      
      <div class="chart-container">
        <h3>收入趋势</h3>
        <div class="chart" ref="revenueChart"></div>
      </div>
    </div>

    <!-- 分布图表 -->
    <div class="distribution-section">
      <div class="chart-container">
        <h3>订单状态分布</h3>
        <div class="chart" ref="orderStatusChart"></div>
      </div>
      
      <div class="chart-container">
        <h3>支付方式分布</h3>
        <div class="chart" ref="paymentMethodChart"></div>
      </div>
    </div>

    <!-- 最近订单 -->
    <div class="recent-orders">
      <h3>最近订单</h3>
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>用户</th>
              <th>金额</th>
              <th>状态</th>
              <th>创建时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in recentOrders" :key="order.id">
              <td>{{ order.orderNumber }}</td>
              <td>{{ order.username }}</td>
              <td>¥{{ formatNumber(order.totalAmount) }}</td>
              <td>
                <span class="status-badge" :class="getStatusClass(order.status)">
                  {{ getStatusText(order.status) }}
                </span>
              </td>
              <td>{{ formatDate(order.createdAt) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { dashboardApi } from '@/api/dashboard'

// 动态加载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)
  })
}

export default {
  name: 'Dashboard',
  setup() {
    const overviewData = ref({})
    const dailyActiveData = ref([])
    const revenueData = ref([])
    const orderStatusData = ref([])
    const paymentMethodData = ref([])
    const recentOrders = ref([])
    
    const dailyActiveChart = ref(null)
    const revenueChart = ref(null)
    const orderStatusChart = ref(null)
    const paymentMethodChart = ref(null)

    // 加载仪表盘数据
    const loadDashboardData = async () => {
      try {
        const response = await dashboardApi.getAllData()
        const data = response.data
        
        overviewData.value = data.overview
        dailyActiveData.value = data.dailyActiveUsers.dailyData || []
        revenueData.value = data.revenueTrend.revenueData || []
        orderStatusData.value = data.orderStatusDistribution.statusData || []
        paymentMethodData.value = data.paymentMethodDistribution.methodData || []
        recentOrders.value = data.recentOrders.orders || []
        
        // 等待DOM更新后初始化图表
        await nextTick()
        await initCharts()
      } catch (error) {
        console.error('加载仪表盘数据失败:', error)
      }
    }

    // 初始化图表
    const initCharts = async () => {
      try {
        const echarts = await loadECharts()
        await initDailyActiveChart(echarts)
        await initRevenueChart(echarts)
        await initOrderStatusChart(echarts)
        await initPaymentMethodChart(echarts)
      } catch (error) {
        console.error('加载ECharts失败:', error)
      }
    }

    // 日活用户图表
    const initDailyActiveChart = async (echarts) => {
      if (!dailyActiveChart.value) return
      
      const chart = echarts.init(dailyActiveChart.value)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dailyActiveData.value.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: dailyActiveData.value.map(item => item.activeUsers),
          type: 'line',
          smooth: true,
          areaStyle: {
            opacity: 0.3
          },
          lineStyle: {
            color: '#4CAF50'
          },
          itemStyle: {
            color: '#4CAF50'
          }
        }]
      }
      chart.setOption(option)
    }

    // 收入趋势图表
    const initRevenueChart = async (echarts) => {
      if (!revenueChart.value) return
      
      const chart = echarts.init(revenueChart.value)
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].axisValue}<br/>收入: ¥${params[0].value}`
          }
        },
        xAxis: {
          type: 'category',
          data: revenueData.value.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: revenueData.value.map(item => item.revenue),
          type: 'bar',
          itemStyle: {
            color: '#2196F3'
          }
        }]
      }
      chart.setOption(option)
    }

    // 订单状态分布图表
    const initOrderStatusChart = async (echarts) => {
      if (!orderStatusChart.value) return
      
      const chart = echarts.init(orderStatusChart.value)
      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: orderStatusData.value.map(item => ({
            value: item.count,
            name: item.status
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      chart.setOption(option)
    }

    // 支付方式分布图表
    const initPaymentMethodChart = async (echarts) => {
      if (!paymentMethodChart.value) return
      
      const chart = echarts.init(paymentMethodChart.value)
      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: paymentMethodData.value.map(item => ({
            value: item.count,
            name: item.method
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      chart.setOption(option)
    }

    // 格式化数字
    const formatNumber = (num) => {
      if (typeof num === 'string') {
        num = parseFloat(num)
      }
      return num.toLocaleString()
    }

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 获取状态样式类
    const getStatusClass = (status) => {
      const statusMap = {
        'PENDING': 'status-pending',
        'CONFIRMED': 'status-confirmed',
        'PAID': 'status-paid',
        'PROCESSING': 'status-processing',
        'SHIPPED': 'status-shipped',
        'DELIVERED': 'status-delivered',
        'COMPLETED': 'status-completed',
        'CANCELLED': 'status-cancelled',
        'REFUNDED': 'status-refunded'
      }
      return statusMap[status] || 'status-default'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待支付',
        'CONFIRMED': '已确认',
        'PAID': '已支付',
        'PROCESSING': '处理中',
        'SHIPPED': '已发货',
        'DELIVERED': '已送达',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消',
        'REFUNDED': '已退款'
      }
      return statusMap[status] || status
    }

    onMounted(() => {
      loadDashboardData()
    })

    return {
      overviewData,
      dailyActiveData,
      revenueData,
      orderStatusData,
      paymentMethodData,
      recentOrders,
      dailyActiveChart,
      revenueChart,
      orderStatusChart,
      paymentMethodChart,
      formatNumber,
      formatDate,
      getStatusClass,
      getStatusText
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow-x: hidden;
}

/* 页面特殊效果 */
.dashboard::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: 
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.3) 0%, transparent 50%);
  animation: dashboardGlow 8s ease-in-out infinite alternate;
  pointer-events: none;
  z-index: 1;
}

@keyframes dashboardGlow {
  0% { opacity: 0.3; }
  100% { opacity: 0.7; }
}

/* 内容层级 */
.dashboard > * {
  position: relative;
  z-index: 2;
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
}

.dashboard-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.dashboard-subtitle {
  color: #666;
  font-size: 16px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: transform 0.2s;
}

.card:hover {
  transform: translateY(-2px);
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.card-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.paying {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.revenue {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.conversion {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-content h3 {
  margin: 0 0 5px 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.card-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.distribution-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-container {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chart-container h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
}

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

.recent-orders {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.recent-orders h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.table-container {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-confirmed {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-paid {
  background-color: #d4edda;
  color: #155724;
}

.status-processing {
  background-color: #cce5ff;
  color: #004085;
}

.status-shipped {
  background-color: #e2e3e5;
  color: #383d41;
}

.status-delivered {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.status-refunded {
  background-color: #f8d7da;
  color: #721c24;
}

@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .charts-section,
  .distribution-section {
    grid-template-columns: 1fr;
  }
  
  .chart {
    height: 250px;
  }
}
</style>
