<script setup lang="ts">
import { ref, onMounted, shallowRef, watch } from 'vue'
import { ShoppingCart, Money, User, Goods, TrendCharts } from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import {
  getDashboardStatsApi,
  getSalesTrendApi,
  getOrderStatusDistributionApi,
  getHotProductsApi
} from '@/api/dashboard'

use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 数据统计
const loading = ref(true)
const stats = ref({
  todayOrders: 0,
  todaySales: 0,
  totalUsers: 0,
  totalProducts: 0
})

const trendDays = ref<'7' | '30'>('7')
const trendOption = shallowRef({})
const pieOption = shallowRef({})
const barOption = shallowRef({})

function buildTrendOption(points: { date: string; amount: number }[]) {
  trendOption.value = {
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: points.map((p) => p.date),
      axisLine: { lineStyle: { color: '#E5E7EB' } },
      axisLabel: { color: '#6B7280' }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { lineStyle: { color: '#F3F4F6' } },
      axisLabel: { color: '#6B7280' }
    },
    series: [
      {
        name: '销售额',
        data: points.map((p) => p.amount),
        type: 'line',
        smooth: true,
        lineStyle: { color: '#3B82F6', width: 3 },
        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)' }
            ]
          }
        }
      }
    ]
  }
}

function buildPieOption(data: { name: string; value: number }[]) {
  const COLOR_MAP: Record<string, string> = {
    待付款: '#F59E0B',
    待发货: '#3B82F6',
    待收货: '#1E40AF',
    已完成: '#10B981',
    已取消: '#9CA3AF',
    已退款: '#EF4444'
  }
  pieOption.value = {
    tooltip: { trigger: 'item' },
    legend: { bottom: 0, icon: 'circle' },
    series: [
      {
        type: 'pie',
        radius: ['50%', '75%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
        label: { show: false },
        data: data.map((d) => ({ ...d, itemStyle: { color: COLOR_MAP[d.name] ?? '#60A5FA' } }))
      }
    ]
  }
}

function buildBarOption(data: { name: string; sales: number }[]) {
  barOption.value = {
    tooltip: { trigger: 'axis' },
    grid: { left: 80, right: 30, top: 20, bottom: 30 },
    xAxis: { type: 'value', axisLine: { show: false }, axisTick: { show: false } },
    yAxis: {
      type: 'category',
      data: data.map((d) => d.name),
      axisLine: { lineStyle: { color: '#E5E7EB' } },
      axisLabel: { color: '#6B7280' }
    },
    series: [
      {
        type: 'bar',
        data: data.map((d) => d.sales),
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#60A5FA' },
              { offset: 1, color: '#1E40AF' }
            ]
          },
          borderRadius: [0, 4, 4, 0]
        }
      }
    ]
  }
}

async function loadStats() {
  try {
    const res = await getDashboardStatsApi()
    stats.value = {
      todayOrders: res.todayOrders ?? 0,
      todaySales: res.todaySales ?? 0,
      totalUsers: res.totalUsers ?? 0,
      totalProducts: res.totalProducts ?? 0
    }
  } catch {
    /* 拦截器已提示 */
  }
}

async function loadTrend(days: '7' | '30') {
  try {
    const res = await getSalesTrendApi(Number(days))
    buildTrendOption(res || [])
  } catch {
    buildTrendOption([])
  }
}

async function loadOrderStatus() {
  try {
    const res = await getOrderStatusDistributionApi()
    buildPieOption(res || [])
  } catch {
    buildPieOption([])
  }
}

async function loadHotProducts() {
  try {
    const res = await getHotProductsApi()
    buildBarOption(res || [])
  } catch {
    buildBarOption([])
  }
}

async function loadAll() {
  loading.value = true
  try {
    await Promise.all([loadStats(), loadTrend(trendDays.value), loadOrderStatus(), loadHotProducts()])
  } finally {
    loading.value = false
  }
}

watch(trendDays, (val) => {
  loadTrend(val)
})

onMounted(loadAll)

const cards = [
  { key: 'todayOrders', title: '今日订单数', icon: ShoppingCart, color: '#3B82F6', suffix: '单' },
  { key: 'todaySales', title: '今日销售额', icon: Money, color: '#10B981', prefix: '¥' },
  { key: 'totalUsers', title: '总用户数', icon: User, color: '#F59E0B', suffix: '人' },
  { key: 'totalProducts', title: '总商品数', icon: Goods, color: '#1E40AF', suffix: '件' }
]
</script>

<template>
  <div class="dashboard">
    <div class="page-header">
      <h2>仪表盘</h2>
      <p>欢迎回来，这是您的运营概览</p>
    </div>

    <!-- 数据卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col v-for="c in cards" :key="c.key" :xs="12" :sm="12" :md="6">
        <el-card v-loading="loading" shadow="never" class="stat-card">
          <div class="stat-icon" :style="{ background: c.color + '15', color: c.color }">
            <el-icon :size="24"><component :is="c.icon" /></el-icon>
          </div>
          <div class="stat-body">
            <div class="stat-title">{{ c.title }}</div>
            <div class="stat-value">
              {{ c.prefix || '' }}{{ stats[c.key as keyof typeof stats] }}{{ c.suffix || '' }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="16">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-radio-group v-model="trendDays" size="small">
                <el-radio-button label="7">近 7 天</el-radio-button>
                <el-radio-button label="30">近 30 天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <v-chart v-loading="loading" :option="trendOption" autoresize style="height: 320px" />
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>订单状态</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <v-chart v-loading="loading" :option="pieOption" autoresize style="height: 320px" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>热销商品 Top 10</span>
              <el-tag size="small" type="info">按销量</el-tag>
            </div>
          </template>
          <v-chart v-loading="loading" :option="barOption" autoresize style="height: 360px" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.page-header {
  h2 {
    margin: 0;
    font-size: 22px;
    color: $color-text-primary;
  }
  p {
    margin: 4px 0 0;
    color: $color-text-secondary;
    font-size: 13px;
  }
}

.stat-cards {
  margin-bottom: 0;
}

.stat-card {
  :deep(.el-card__body) {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 20px;
  }
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-title {
  font-size: 13px;
  color: $color-text-secondary;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: $color-text-primary;
}

.chart-row {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  color: $color-text-primary;
}
</style>
