<template>
  <div class="im-monitor">
    <!-- 统计卡片 -->
    <el-row :gutter="14" class="stat-row">
      <el-col v-for="card in statCards" :key="card.key" :xs="12" :sm="12" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" :style="{ background: card.bg, color: card.color }">
              <el-icon :size="22"><component :is="card.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ card.value }}</div>
              <div class="stat-title">{{ card.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区 -->
    <el-row :gutter="14" class="chart-row">
      <el-col :xs="24" :md="16">
        <el-card shadow="never">
          <template #header>
            <div class="card-title">
              <span>近 7 天消息量趋势</span>
              <span class="update-at">更新于 {{ updatedAt }}</span>
            </div>
          </template>
          <div ref="trendRef" class="chart trend-chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="never">
          <template #header>
            <div class="card-title">消息类型分布</div>
          </template>
          <div ref="pieRef" class="chart pie-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Message, ChatDotRound, Bell, User, ChatLineRound, Document } from '@element-plus/icons-vue'
import { imAdminPerformance } from '@/api/im'

const data = ref({ total: 0, today: 0, unread: 0, online: 0, sessions: 0, avgLen: 0, trend: [], typeDist: [], updatedAt: '' })
const updatedAt = computed(() => data.value.updatedAt || '')
const trendRef = ref(null)
const pieRef = ref(null)
let trendChart = null
let pieChart = null
let timer = null

const statCards = computed(() => [
  { key: 'total', title: '消息总量', value: data.value.total, icon: Message, bg: '#ecf5ff', color: '#409eff' },
  { key: 'today', title: '今日消息', value: data.value.today, icon: ChatDotRound, bg: '#f0f9eb', color: '#67c23a' },
  { key: 'unread', title: '未读消息', value: data.value.unread, icon: Bell, bg: '#fdf6ec', color: '#e6a23c' },
  { key: 'online', title: '在线用户', value: data.value.online, icon: User, bg: '#f4f4f5', color: '#909399' },
  { key: 'sessions', title: '会话数', value: data.value.sessions, icon: ChatLineRound, bg: '#f3eefc', color: '#9c27b0' },
  { key: 'avgLen', title: '平均消息长度(B)', value: data.value.avgLen, icon: Document, bg: '#fef0f0', color: '#f56c6c' }
])

function renderCharts() {
  if (!trendRef.value || !pieRef.value) return
  const dates = (data.value.trend || []).map((t) => t.date)
  const counts = (data.value.trend || []).map((t) => t.count)
  trendChart = echarts.init(trendRef.value)
  trendChart.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 30, bottom: 30 },
    xAxis: { type: 'category', data: dates, boundaryGap: false },
    yAxis: { type: 'value', minInterval: 1 },
    series: [
      {
        name: '消息量',
        type: 'line',
        smooth: true,
        areaStyle: { opacity: 0.15 },
        itemStyle: { color: '#409eff' },
        data: counts
      }
    ]
  })

  pieChart = echarts.init(pieRef.value)
  pieChart.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { bottom: 0, icon: 'circle', itemWidth: 10, itemHeight: 10 },
    series: [
      {
        name: '消息类型',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '45%'],
        itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
        label: { formatter: '{b}\n{d}%' },
        data: (data.value.typeDist || []).map((t) => ({ name: t.name, value: t.count }))
      }
    ]
  })
}

function resizeCharts() {
  trendChart?.resize()
  pieChart?.resize()
}

async function load() {
  const res = await imAdminPerformance()
  data.value = res?.data || data.value
  await nextTick()
  renderCharts()
}

function startTimer() {
  timer = setInterval(load, 10000)
}

onMounted(() => {
  load()
  startTimer()
  window.addEventListener('resize', resizeCharts)
})

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

<style scoped>
.im-monitor .stat-row {
  margin-bottom: 14px;
}
.im-monitor .stat-card {
  margin-bottom: 0;
}
.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
}
.stat-icon {
  width: 46px;
  height: 46px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.stat-value {
  font-size: 22px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}
.stat-title {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
.chart-row {
  margin-bottom: 0;
}
.card-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.update-at {
  font-size: 12px;
  color: #909399;
  font-weight: 400;
}
.chart {
  width: 100%;
}
.trend-chart {
  height: 320px;
}
.pie-chart {
  height: 320px;
}
</style>
