<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card" @click="$router.push('/orders')">
          <div class="stat-card-inner">
            <div class="stat-info">
              <div class="stat-label">今日订单</div>
              <div class="stat-value">{{ stats.todayOrders }}</div>
              <div class="stat-desc">较昨日 <span :class="stats.orderChange >= 0 ? 'up' : 'down'">{{ stats.orderChange >= 0 ? '+' : '' }}{{ stats.orderChange }}%</span></div>
            </div>
            <div class="stat-icon" style="background:#e6f7ff;color:#1890ff">
              <el-icon :size="32"><List /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-inner">
            <div class="stat-info">
              <div class="stat-label">今日销售额</div>
              <div class="stat-value">¥{{ formatMoney(stats.todaySales) }}</div>
              <div class="stat-desc">较昨日 <span :class="stats.salesChange >= 0 ? 'up' : 'down'">{{ stats.salesChange >= 0 ? '+' : '' }}{{ stats.salesChange }}%</span></div>
            </div>
            <div class="stat-icon" style="background:#fdf6ec;color:#e6a23c">
              <el-icon :size="32"><Coin /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card" @click="$router.push('/users')">
          <div class="stat-card-inner">
            <div class="stat-info">
              <div class="stat-label">总用户数</div>
              <div class="stat-value">{{ stats.totalUsers }}</div>
              <div class="stat-desc">较昨日 <span :class="stats.userChange >= 0 ? 'up' : 'down'">{{ stats.userChange >= 0 ? '+' : '' }}{{ stats.userChange }}%</span></div>
            </div>
            <div class="stat-icon" style="background:#f0f5ff;color:#409eff">
              <el-icon :size="32"><User /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-inner">
            <div class="stat-info">
              <div class="stat-label">总销售额</div>
              <div class="stat-value">¥{{ formatMoney(stats.totalSales) }}</div>
              <div class="stat-desc">累计至今</div>
            </div>
            <div class="stat-icon" style="background:#f0fff0;color:#67c23a">
              <el-icon :size="32"><Money /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :md="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>近7天订单趋势</span>
            </div>
          </template>
          <div ref="chartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速操作 -->
    <el-card shadow="hover" class="quick-actions">
      <template #header>
        <div class="card-header">
          <span>快速操作</span>
        </div>
      </template>
      <div class="action-buttons">
        <el-button type="primary" @click="$router.push('/products')">
          <el-icon><Plus /></el-icon>新增商品
        </el-button>
        <el-button type="success" @click="$router.push('/orders')">
          <el-icon><View /></el-icon>查看订单
        </el-button>
        <el-button type="warning" @click="$router.push('/marketing')">
          <el-icon><Present /></el-icon>创建活动
        </el-button>
        <el-button type="info" @click="$router.push('/stats')">
          <el-icon><DataAnalysis /></el-icon>数据报表
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { dashboardApi } from '../api'

const chartRef = ref(null)
const pieChartRef = ref(null)
let chartInstance = null
let pieChartInstance = null

const stats = reactive({
  todayOrders: 0,
  todaySales: 0,
  totalUsers: 0,
  totalSales: 0,
  orderChange: 0,
  salesChange: 0,
  userChange: 0
})

const formatMoney = (val) => {
  if (!val && val !== 0) return '0.00'
  return Number(val).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const initChart = (data) => {
  if (!chartRef.value) return
  if (chartInstance) chartInstance.dispose()
  chartInstance = echarts.init(chartRef.value)

  const days = data?.map(d => d.d || d.date) || ['周一','周二','周三','周四','周五','周六','周日']
  const orderData = data?.map(d => d.orders || d.order_count || 0) || [120,200,150,80,70,110,130]
  const salesData = data?.map(d => d.revenue || d.sales || d.revenue || 0) || [2000,3500,2800,1500,1200,1900,2300]

  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 0,
      boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
    },
    legend: {
      data: ['订单数', '销售额'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: days,
      axisLine: { lineStyle: { color: '#e8e8e8' } }
    },
    yAxis: {
      type: 'value',
      splitLine: { lineStyle: { color: '#f5f5f5' } }
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 3 },
        itemStyle: { color: '#409eff' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.35)' },
            { offset: 1, color: 'rgba(64,158,255,0.05)' }
          ])
        },
        data: orderData
      },
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 3 },
        itemStyle: { color: '#67c23a' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103,194,58,0.35)' },
            { offset: 1, color: 'rgba(103,194,58,0.05)' }
          ])
        },
        data: salesData
      }
    ]
  })
}

const initPieChart = () => {
  if (!pieChartRef.value) return
  if (pieChartInstance) pieChartInstance.dispose()
  pieChartInstance = echarts.init(pieChartRef.value)

  pieChartInstance.setOption({
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 0,
      boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: { show: true, fontSize: 14, fontWeight: 'bold' }
        },
        data: [
          { value: 45, name: '待付款', itemStyle: { color: '#409eff' } },
          { value: 32, name: '待发货', itemStyle: { color: '#e6a23c' } },
          { value: 18, name: '已发货', itemStyle: { color: '#67c23a' } },
          { value: 5, name: '已完成', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  })
}

const fetchData = async () => {
  try {
    const res = await dashboardApi.getStats()
    if (res.data) {
      const d = res.data
      stats.todayOrders = d.todayOrders || d.today_orders || 0
      stats.todaySales = d.todaySales || d.today_sales || 0
      stats.totalUsers = d.totalUsers || d.total_users || 0
      stats.totalSales = d.totalSales || d.total_sales || 0
      stats.orderChange = d.orderChange || 0
      stats.salesChange = d.salesChange || 0
      stats.userChange = d.userChange || 0
    }
  } catch (e) {
    stats.todayOrders = 42
    stats.todaySales = 8650
    stats.totalUsers = 1286
    stats.totalSales = 368500
    stats.orderChange = 12.5
    stats.salesChange = 8.3
    stats.userChange = 3.2
  }

  try {
    const res = await dashboardApi.getOrderTrend(7)
    if (res.data) {
      nextTick(() => initChart(res.data))
    }
  } catch (e) {
    nextTick(() => initChart())
  }
}

onMounted(() => {
  fetchData()
  nextTick(() => {
    initPieChart()
  })
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
  pieChartInstance?.dispose()
})

const handleResize = () => {
  chartInstance?.resize()
  pieChartInstance?.resize()
}
</script>

<style scoped>
.dashboard {
  max-width: 1400px;
}
.stat-cards {
  margin-bottom: 20px;
}
.stat-card {
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  margin-bottom: 20px;
}
.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.1);
}
.stat-card-inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.stat-info {
  flex: 1;
}
.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
}
.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}
.stat-desc {
  font-size: 12px;
  color: #909399;
}
.stat-desc .up {
  color: #67c23a;
  font-weight: 600;
}
.stat-desc .down {
  color: #f56c6c;
  font-weight: 600;
}
.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 15px;
}
.chart-container {
  width: 100%;
  height: 320px;
}
.quick-actions {
  margin-bottom: 20px;
}
.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
</style>
