<template>
  <div>
    <h2 style="margin-bottom:12px">服务运营总览</h2>
    <p style="margin:0 0 24px;color:#606266">
      汇总租户、应用与服务开通情况，便于快速判断平台健康状态。
    </p>
    <el-row :gutter="16">
      <el-col :xs="12" :sm="6" v-for="item in stats" :key="item.label">
        <el-card shadow="hover">
          <el-statistic :title="item.label" :value="item.value" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top:16px">
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>近7天注册趋势</template>
          <div ref="trendChartRef" class="chart-box" />
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>服务开通分布</template>
          <div ref="pieChartRef" class="chart-box" />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="16" style="margin-top:16px">
      <el-col :xs="24">
        <el-card>
          <template #header>消息量统计</template>
          <div ref="barChartRef" class="chart-box" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { opsApi } from '@/api/ops'
import * as echarts from 'echarts'

const stats = ref([
  { label: '总租户数', value: 0 },
  { label: '今日新增', value: 0 },
  { label: '活跃应用', value: 0 },
  { label: '在线用户', value: 0 },
])

const trendChartRef = ref<HTMLDivElement>()
const pieChartRef = ref<HTMLDivElement>()
const barChartRef = ref<HTMLDivElement>()

let trendChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null
let barChart: echarts.ECharts | null = null

function initTrendChart(dailyTrend: Array<{ date: string; count: number }>) {
  if (!trendChartRef.value) return
  const dates = dailyTrend.map(d => {
    const parts = d.date.split('-')
    return `${parseInt(parts[1])}/${parseInt(parts[2])}`
  })
  const values = dailyTrend.map(d => d.count)
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dates, boundaryGap: false },
    yAxis: { type: 'value', minInterval: 1 },
    series: [{
      name: '新增注册',
      type: 'line',
      smooth: true,
      data: values,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(64,158,255,0.3)' },
          { offset: 1, color: 'rgba(64,158,255,0.05)' },
        ]),
      },
      itemStyle: { color: '#409eff' },
    }],
  })
}

function initPieChart(serviceDistribution: Record<string, number>) {
  if (!pieChartRef.value) return
  const data = Object.entries(serviceDistribution).map(([name, value]) => ({ name, value }))
  if (data.length === 0) {
    data.push({ name: '暂无数据', value: 0 })
  }
  pieChart = echarts.init(pieChartRef.value)
  pieChart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: '0%' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
      label: { show: false },
      emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
      data,
    }],
  })
}

function initBarChart() {
  if (!barChartRef.value) return
  const dates = Array.from({ length: 7 }, (_, i) => {
    const d = new Date()
    d.setDate(d.getDate() - (6 - i))
    return `${d.getMonth() + 1}/${d.getDate()}`
  })
  barChart = echarts.init(barChartRef.value)
  barChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { data: ['发送消息', '接收消息'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value' },
    series: [
      { name: '发送消息', type: 'bar', data: [0, 0, 0, 0, 0, 0, 0], itemStyle: { color: '#409eff' } },
      { name: '接收消息', type: 'bar', data: [0, 0, 0, 0, 0, 0, 0], itemStyle: { color: '#67c23a' } },
    ],
  })
}

function handleResize() {
  trendChart?.resize()
  pieChart?.resize()
  barChart?.resize()
}

onMounted(async () => {
  try {
    const res = await opsApi.statistics()
    const d = res.data.data
    stats.value[0].value = d.totalTenants ?? 0
    stats.value[1].value = d.todayNew ?? 0
    stats.value[2].value = d.activeApps ?? 0
    stats.value[3].value = d.onlineUsers ?? 0
    initTrendChart(d.dailyTrend ?? [])
    initPieChart(d.serviceDistribution ?? {})
  } catch {
    initTrendChart([])
    initPieChart({})
  }

  initBarChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  pieChart?.dispose()
  barChart?.dispose()
})
</script>

<style scoped>
.chart-box {
  width: 100%;
  height: 320px;
}
</style>
