<template>
  <div class="stats-page">
    <!-- 时间筛选 -->
    <el-card shadow="never" class="filter-card">
      <el-form inline>
        <el-form-item label="统计周期">
          <el-radio-group v-model="dateRange" @change="fetchAll" size="small">
            <el-radio-button value="7d">近7天</el-radio-button>
            <el-radio-button value="30d">近30天</el-radio-button>
            <el-radio-button value="3m">近3个月</el-radio-button>
            <el-radio-button value="1y">近1年</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 概览卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-value">{{ summary.totalOrders }}</div>
          <div class="summary-label">总订单数</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card" style="border-top: 3px solid #e6a23c">
          <div class="summary-value">¥{{ formatMoney(summary.totalRevenue) }}</div>
          <div class="summary-label">总收入</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card" style="border-top: 3px solid #67c23a">
          <div class="summary-value">¥{{ formatMoney(summary.avgOrderAmount) }}</div>
          <div class="summary-label">平均客单价</div>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <el-card shadow="hover" class="summary-card" style="border-top: 3px solid #f56c6c">
          <div class="summary-value">{{ summary.newUsers }}</div>
          <div class="summary-label">新增用户</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :md="16">
        <el-card shadow="never">
          <template #header><div class="card-header">销售趋势</div></template>
          <div ref="salesTrendRef" class="chart-lg"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="never">
          <template #header><div class="card-header">订单占比</div></template>
          <div ref="orderDistRef" class="chart-sm"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :md="12">
        <el-card shadow="never">
          <template #header><div class="card-header">热销商品 TOP10</div></template>
          <div ref="topProductsRef" class="chart-sm"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card shadow="never">
          <template #header><div class="card-header">用户增长趋势</div></template>
          <div ref="userGrowthRef" class="chart-sm"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
const API = axios.create({baseURL:'/api/admin'})
API.interceptors.request.use(c=>{c.headers.Authorization='Bearer '+localStorage.getItem('admin_token');return c})

const dateRange = ref('7d')

// DOM refs
const salesTrendRef = ref(null)
const orderDistRef = ref(null)
const topProductsRef = ref(null)
const userGrowthRef = ref(null)

// Chart instances
let salesTrendChart = null
let orderDistChart = null
let topProductsChart = null
let userGrowthChart = null

const summary = reactive({
  totalOrders: 0,
  totalRevenue: 0,
  avgOrderAmount: 0,
  newUsers: 0
})

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

// 销售趋势图
const initSalesTrend = (data) => {
  if (!salesTrendRef.value) return
  if (salesTrendChart) salesTrendChart.dispose()
  salesTrendChart = echarts.init(salesTrendRef.value)

  const trend = window.__statsTrend || []
  const dates = trend.length ? trend.map(d => d.d) : getDateLabels(7)
  const revenues = trend.length ? trend.map(d => d.revenue) : [3200,4500,3800,5200,4800,6100,5500]
  const orders = trend.length ? trend.map(d => d.orders) : [28,35,30,42,38,48,43]

  salesTrendChart.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: '18%', top: '5%', containLabel: true },
    xAxis: {
      type: 'category',
      data: dates,
      axisLine: { lineStyle: { color: '#e8e8e8' } },
      axisLabel: { rotate: 30 }
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额(元)',
        splitLine: { lineStyle: { color: '#f5f5f5' } }
      },
      {
        type: 'value',
        name: '订单数',
        splitLine: { show: false }
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'bar',
        yAxisIndex: 0,
        barWidth: '35%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#79bbff' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        data: revenues
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 2, color: '#e6a23c' },
        itemStyle: { color: '#e6a23c' },
        data: orders
      }
    ]
  })
}

// 订单分布
const initOrderDist = (data) => {
  if (!orderDistRef.value) return
  if (orderDistChart) orderDistChart.dispose()
  orderDistChart = echarts.init(orderDistRef.value)

  const dist = window.__orderDist || []
  const statusMap = {pending_pay:'待付款',pending_ship:'待发货',shipped:'已发货',received:'已完成',closed:'已关闭',cancelled:'已取消',refunding:'退款中'}
  const chartData = data || (dist.length ? dist.map(d => ({value:d.cnt, name:statusMap[d.status]||d.status})) : [
    {value:45,name:'待付款'},{value:32,name:'待发货'},{value:18,name:'已发货'},{value:28,name:'已完成'},{value:7,name:'已取消'}
  ])

  orderDistChart.setOption({
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 0,
      boxShadow: '0 2px 12px rgba(0,0,0,0.1)',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: ['40%', '65%'],
      center: ['50%', '55%'],
      avoidLabelOverlap: false,
      label: {
        show: true,
        formatter: '{b}: {d}%',
        fontSize: 11
      },
      emphasis: {
        label: { show: true, fontSize: 14, fontWeight: 'bold' }
      },
      data: chartData
    }]
  })
}

// 热销商品Top10
const initTopProducts = (data) => {
  if (!topProductsRef.value) return
  if (topProductsChart) topProductsChart.dispose()
  topProductsChart = echarts.init(topProductsRef.value)

  const top = window.__topProducts || []
  const names = data?.map(d => d.name) || (top.length ? top.map(d => d.name) : ['LED灯带','智能筒灯','射灯','吸顶灯','壁灯','台灯','轨道灯','灯管','灯泡','感应灯'])
  const sales = data?.map(d => d.sales) || (top.length ? top.map(d => d.total_sales) : [320,280,245,210,180,155,130,98,75,52])

  topProductsChart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 0,
      boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
    },
    grid: { left: '3%', right: '5%', bottom: '5%', top: '3%', containLabel: true },
    xAxis: {
      type: 'value',
      splitLine: { lineStyle: { color: '#f5f5f5' } }
    },
    yAxis: {
      type: 'category',
      data: names.reverse(),
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { fontSize: 11 }
    },
    series: [{
      type: 'bar',
      barWidth: '55%',
      data: sales.reverse().map((v, i) => ({
        value: v,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: i > 4 ? '#79bbff' : '#409eff' },
            { offset: 1, color: i > 4 ? '#a0cfff' : '#79bbff' }
          ]),
          borderRadius: [0, 4, 4, 0]
        }
      }))
    }]
  })
}

// 用户增长趋势
const initUserGrowth = (data) => {
  if (!userGrowthRef.value) return
  if (userGrowthChart) userGrowthChart.dispose()
  userGrowthChart = echarts.init(userGrowthRef.value)

  const growth = window.__userGrowth || []
  const dates = data?.map(d => d.date) || (growth.length ? growth.map(d => d.d) : getDateLabels(7))
  const newUsers = data?.map(d => d.count) || (growth.length ? growth.map(d => d.cnt) : [12,18,25,16,30,22,28])
  const totalUsers = data?.map(d => d.total) || []

  userGrowthChart.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: '18%', top: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: { rotate: 30 },
      axisLine: { lineStyle: { color: '#e8e8e8' } }
    },
    yAxis: {
      type: 'value',
      splitLine: { lineStyle: { color: '#f5f5f5' } }
    },
    series: [
      {
        name: '新增用户',
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67c23a' },
            { offset: 1, color: '#a8e6a3' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        data: newUsers
      },
      {
        name: '总用户',
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: { width: 2, color: '#409eff' },
        itemStyle: { color: '#409eff' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.2)' },
            { offset: 1, color: 'rgba(64,158,255,0.02)' }
          ])
        },
        data: totalUsers
      }
    ]
  })
}

const getDateLabels = (days) => {
  const labels = []
  const now = new Date()
  for (let i = days - 1; i >= 0; i--) {
    const d = new Date(now)
    d.setDate(d.getDate() - i)
    labels.push(`${d.getMonth() + 1}/${d.getDate()}`)
  }
  return labels
}

const fetchAll = async () => {
  const range = dateRange.value
  try {
    // 概览+销售趋势
    const r = await API.get('/stats/dashboard', {params:{range}})
    const d = r.data.data || {}
    summary.totalOrders = d.totalOrders || 0
    summary.totalRevenue = d.totalRevenue || 0
    summary.avgOrderAmount = d.avgOrderAmount || 0
    summary.newUsers = d.newUsers || 0
    window.__statsTrend = d.trend || []
  } catch {}

  try {
    const r = await API.get('/stats/top-products')
    window.__topProducts = r.data.data || []
  } catch {}
  try {
    const r = await API.get('/stats/user-growth')
    window.__userGrowth = r.data.data || []
  } catch {}
  try {
    const r = await API.get('/stats/order-distribution')
    window.__orderDist = r.data.data || []
  } catch {}

  nextTick(() => {
    initSalesTrend()
    initOrderDist()
    initTopProducts()
    initUserGrowth()
  })
}

onMounted(() => {
  fetchAll()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  salesTrendChart?.dispose()
  orderDistChart?.dispose()
  topProductsChart?.dispose()
  userGrowthChart?.dispose()
})

const handleResize = () => {
  salesTrendChart?.resize()
  orderDistChart?.resize()
  topProductsChart?.resize()
  userGrowthChart?.resize()
}
</script>

<style scoped>
.stats-page {
  max-width: 1400px;
}
.filter-card {
  margin-bottom: 16px;
}
.stats-row {
  margin-bottom: 16px;
}
.summary-card {
  text-align: center;
  padding: 8px 0;
  border-top: 3px solid #409eff;
  margin-bottom: 16px;
}
.summary-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}
.summary-label {
  font-size: 14px;
  color: #909399;
}
.card-header {
  font-weight: 600;
  font-size: 15px;
}
.chart-lg {
  width: 100%;
  height: 360px;
}
.chart-sm {
  width: 100%;
  height: 320px;
}
</style>
