<template>
  <div class="page-container">
    <div class="page-head">
      <div>
        <h2 class="page-title">仪表盘</h2>
        <span class="text-muted">实时展示信令服务器运行态，每 5 秒自动刷新</span>
      </div>
      <div class="page-actions">
        <span class="text-muted">最后更新：{{ lastUpdate }}</span>
        <el-button :icon="'Refresh'" :loading="loading" @click="load">刷新</el-button>
      </div>
    </div>

    <el-row :gutter="16">
      <el-col :xs="12" :sm="12" :md="6">
        <StatCard title="在线设备" :value="data?.onlineDevices ?? 0" icon="Monitor" color="#3b82f6" />
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <StatCard title="在线主控端" :value="data?.onlineControllers ?? 0" icon="VideoCamera" color="#67c23a" />
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <StatCard title="在线被控端" :value="data?.onlineControlled ?? 0" icon="Cellphone" color="#e6a23c" />
      </el-col>
      <el-col :xs="12" :sm="12" :md="6">
        <StatCard title="待确认连接" :value="data?.pendingConnections ?? 0" icon="Connection" color="#f56c6c" />
      </el-col>
    </el-row>

    <el-row :gutter="16" class="charts-row">
      <el-col :xs="24" :md="10">
        <el-card shadow="hover" header="设备类型分布">
          <div ref="pieRef" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="14">
        <el-card shadow="hover" header="信令流量统计">
          <div ref="barRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" header="最近在线设备">
      <el-table :data="devices.slice(0, 8)" stripe size="default">
        <el-table-column prop="deviceId" label="设备 ID" min-width="180" />
        <el-table-column label="类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.deviceType === 'CONTROLLER'" type="success">主控端</el-tag>
            <el-tag v-else-if="row.deviceType === 'CONTROLLED'" type="warning">被控端</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.online ? 'success' : 'danger'" effect="dark">
              {{ row.online ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上线时间" min-width="180">
          <template #default="{ row }">{{ fmtTime(row.connectedAt) }}</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { getDashboard, getDevices } from '@/api/admin';
import type { DashboardData, DeviceInfo } from '@/api/admin';
import StatCard from '@/components/StatCard.vue';

const data = ref<DashboardData | null>(null);
const devices = ref<DeviceInfo[]>([]);
const loading = ref(false);
const lastUpdate = ref('—');
const pieRef = ref<HTMLDivElement>();
const barRef = ref<HTMLDivElement>();
let pieChart: echarts.ECharts | null = null;
let barChart: echarts.ECharts | null = null;
let timer: number | undefined;

async function load() {
  loading.value = true;
  try {
    const [d, devs] = await Promise.all([getDashboard(), getDevices()]);
    data.value = d;
    devices.value = devs;
    lastUpdate.value = new Date().toLocaleTimeString('zh-CN');
    renderCharts();
  } finally {
    loading.value = false;
  }
}

function renderCharts() {
  if (!data.value) return;
  const d = data.value;
  pieChart?.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '设备分布',
        type: 'pie',
        radius: ['42%', '70%'],
        avoidLabelOverlap: true,
        label: { show: true, formatter: '{b}: {c}' },
        data: [
          { value: d.onlineControllers, name: '在线主控端', itemStyle: { color: '#67c23a' } },
          { value: d.onlineControlled, name: '在线被控端', itemStyle: { color: '#e6a23c' } },
          { value: d.offlineDevices, name: '离线设备', itemStyle: { color: '#c0c4cc' } },
        ],
      },
    ],
  });
  const m = d.metrics;
  barChart?.setOption({
    tooltip: { trigger: 'axis' },
    grid: { left: 40, right: 20, top: 30, bottom: 30 },
    xAxis: { type: 'category', data: ['注册', 'OFFER', 'ANSWER', '拒绝', '消息总量'] },
    yAxis: { type: 'value' },
    series: [
      {
        type: 'bar',
        barWidth: '48%',
        data: [m.totalRegistered, m.totalOffers, m.totalAnswers, m.totalRejected, m.totalMessages],
        itemStyle: { borderRadius: [4, 4, 0, 0], color: '#3b82f6' },
      },
    ],
  });
}

function initCharts() {
  if (pieRef.value) pieChart = echarts.init(pieRef.value);
  if (barRef.value) barChart = echarts.init(barRef.value);
}

function onResize() {
  pieChart?.resize();
  barChart?.resize();
}

function fmtTime(ts: number | null) {
  return ts ? new Date(ts).toLocaleString('zh-CN') : '—';
}

onMounted(() => {
  initCharts();
  load();
  timer = window.setInterval(load, 5000);
  window.addEventListener('resize', onResize);
});

onBeforeUnmount(() => {
  if (timer) clearInterval(timer);
  window.removeEventListener('resize', onResize);
  pieChart?.dispose();
  barChart?.dispose();
});
</script>

<style scoped>
.page-head {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 8px;
}
.page-title {
  margin: 0 0 4px;
  font-size: 20px;
}
.page-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.charts-row {
  margin-top: 16px;
}
.chart {
  height: 300px;
}
</style>
