<template>
  <a-card :bordered="false" class="overview-card">
    <div class="stats-row">
      <a-card class="stat-card" :bordered="false">
        <div class="stat-icon orders">
          <icon-file :size="32" />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ overview.orderCount || 0 }}</div>
          <div class="stat-label">订单总量</div>
        </div>
      </a-card>
      <a-card class="stat-card" :bordered="false">
        <div class="stat-icon sales">
          <icon-gift :size="32" />
        </div>
        <div class="stat-info">
          <div class="stat-value">¥{{ (overview.salesAmount || 0).toLocaleString() }}</div>
          <div class="stat-label">平台销售额</div>
        </div>
      </a-card>
      <a-card class="stat-card" :bordered="false">
        <div class="stat-icon users">
          <icon-user-group :size="32" />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ userCount }}</div>
          <div class="stat-label">注册用户</div>
        </div>
      </a-card>
      <a-card class="stat-card" :bordered="false">
        <div class="stat-icon risks">
          <icon-exclamation :size="32" />
        </div>
        <div class="stat-info">
          <div class="stat-value">{{ riskCount }}</div>
          <div class="stat-label">待处理风控</div>
        </div>
      </a-card>
    </div>

    <a-row :gutter="16" style="margin-top: 20px">
      <a-col :xs="24" :md="12">
        <a-card title="品类占比" size="small">
          <div ref="categoryChartRef" style="height: 280px;"></div>
        </a-card>
      </a-col>
      <a-col :xs="24" :md="12">
        <a-card title="热销排行 Top10" size="small">
          <div ref="hotChartRef" style="height: 280px;"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-divider />
    <a-card title="通知公告" size="small">
      <a-timeline v-if="overview.notifications && overview.notifications.length">
        <a-timeline-item v-for="(note, idx) in overview.notifications" :key="idx" :color="idx === 0 ? 'red' : 'purple'">
          {{ note }}
        </a-timeline-item>
      </a-timeline>
      <a-empty v-else description="暂无公告" />
    </a-card>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { IconFile, IconGift, IconUserGroup, IconExclamation } from '@arco-design/web-vue/es/icon'
import { api } from '../../api'

const overview = reactive({})
const userCount = ref(0)
const riskCount = ref(0)
const categoryChartRef = ref(null)
const hotChartRef = ref(null)
let categoryChart = null
let hotChart = null

const initCharts = () => {
  if (!overview.categoryRatio) overview.categoryRatio = {}
  if (!overview.hotProducts) overview.hotProducts = {}

  const categoryData = Object.entries(overview.categoryRatio).map(([name, value]) => ({ name, value }))
  if (categoryChart) {
    categoryChart.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{ type: 'pie', radius: ['40%', '70%'], data: categoryData, itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 } }]
    })
  } else if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
    categoryChart.setOption({
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { orient: 'vertical', left: 'left' },
      series: [{ type: 'pie', radius: ['40%', '70%'], data: categoryData, itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 } }]
    })
  }

  const hotEntries = Object.entries(overview.hotProducts).sort((a, b) => b[1] - a[1]).slice(0, 10)
  const hotData = hotEntries.map(([name, value]) => ({ name: name.length > 8 ? name.substring(0, 8) + '...' : name, value }))
  if (hotChart) {
    hotChart.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'value' },
      yAxis: { type: 'category', data: hotData.map(d => d.name).reverse() },
      series: [{ type: 'bar', data: hotData.map(d => d.value).reverse(), itemStyle: { borderRadius: [0, 4, 4, 0] } }]
    })
  } else if (hotChartRef.value) {
    hotChart = echarts.init(hotChartRef.value)
    hotChart.setOption({
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'value' },
      yAxis: { type: 'category', data: hotData.map(d => d.name).reverse() },
      series: [{ type: 'bar', data: hotData.map(d => d.value).reverse(), itemStyle: { borderRadius: [0, 4, 4, 0] } }]
    })
  }
}

const handleResize = () => { categoryChart?.resize(); hotChart?.resize() }

onMounted(async () => {
  Object.assign(overview, await api.adminOverview())
  const users = await api.adminUsers()
  userCount.value = users.length
  const risks = await api.adminOrderRisks()
  riskCount.value = risks.length
  await nextTick()
  initCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  categoryChart?.dispose()
  hotChart?.dispose()
})
</script>

<style scoped>
.stats-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }
.stat-card { 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; }
.stat-icon.orders { background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%); color: white; }
.stat-icon.sales { background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%); color: white; }
.stat-icon.users { background: linear-gradient(135deg, #722ed1 0%, #b37feb 100%); color: white; }
.stat-icon.risks { background: linear-gradient(135deg, #f5222d 0%, #cf1322 100%); color: white; }
.stat-value { font-size: 28px; font-weight: 700; color: #1f2937; }
.stat-label { font-size: 14px; color: #6b7280; margin-top: 4px; }
.overview-card { border-radius: 12px; }
@media (max-width: 768px) { .stats-row { grid-template-columns: repeat(2, 1fr); } }
</style>