/* 服务器监控视图 */
const ServersView = {
  template: `
  <div class="space-y-4">
    <div v-if="!m.asset" class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-8 text-center text-slate-400 text-sm">
      请在「资产」页点击 VPS 的「监控」查看服务器资源与安全状态
    </div>
    <template v-else>
      <div class="flex items-center gap-2">
        <button @click="goBack" class="text-sm text-slate-500 hover:text-slate-700">← 返回</button>
        <h2 class="font-semibold">{{ m.asset.name }}</h2>
      </div>
      <div v-if="m.info" class="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
          <div class="text-xs text-slate-500">CPU</div>
          <div class="text-xl font-bold mt-1">{{ latest ? latest.cpu_pct : '—' }}%</div>
          <div class="text-xs text-slate-400 mt-1">{{ m.info.cpu_cores }} 核</div>
        </div>
        <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
          <div class="text-xs text-slate-500">内存</div>
          <div class="text-xl font-bold mt-1">{{ latest ? latest.mem_pct : '—' }}%</div>
          <div class="text-xs text-slate-400 mt-1">{{ m.info.mem_total_gb }} GB</div>
        </div>
        <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
          <div class="text-xs text-slate-500">磁盘</div>
          <div class="text-xl font-bold mt-1">{{ latest ? latest.disk_pct : '—' }}%</div>
          <div class="text-xs text-slate-400 mt-1">{{ m.info.disk_total_gb }} GB</div>
        </div>
        <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
          <div class="text-xs text-slate-500">负载/在线</div>
          <div class="text-xl font-bold mt-1">{{ latest && latest.load_1m !== null ? latest.load_1m : '—' }}</div>
          <div class="text-xs text-slate-400 mt-1">{{ m.info.hostname }}</div>
        </div>
      </div>
      <div v-if="m.info" class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4 text-sm">
        <h3 class="font-semibold mb-2">服务器信息</h3>
        <div class="grid grid-cols-2 gap-y-1 text-xs text-slate-500">
          <div>系统：{{ m.info.os }}</div><div>内核：{{ m.info.kernel }}</div>
          <div>公网 IP：{{ m.info.public_ip || '—' }}</div><div>状态：{{ m.info.status }}</div>
        </div>
      </div>
      <div v-if="m.metrics && m.metrics.length > 1" class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
        <h3 class="font-semibold mb-2 text-sm">资源趋势（最近 {{ m.metrics.length }} 次采样）</h3>
        <canvas id="metricsChart" height="90"></canvas>
      </div>
      <div class="bg-white dark:bg-slate-900 rounded-xl border border-slate-200 dark:border-slate-800 p-4">
        <div class="flex justify-between items-center mb-2">
          <h3 class="font-semibold text-sm">安全检查</h3>
          <div v-if="m.security && m.security.score !== null && m.security.score !== undefined" class="flex items-center gap-2">
            <span class="text-xs text-slate-500">安全评分</span>
            <span class="text-lg font-bold" :class="scoreClass(m.security.level)">{{ m.security.score }}</span>
          </div>
        </div>
        <div class="space-y-2">
          <div v-for="c in m.checks" :key="c.id" class="flex items-start gap-2 text-sm">
            <span class="text-xs px-2 py-0.5 rounded-full shrink-0" :class="Fmt.checkBadge(c.status)">{{ c.status }}</span>
            <div class="min-w-0">
              <div class="font-medium text-xs">{{ c.check_item }}</div>
              <div class="text-xs text-slate-500">{{ c.detail }}</div>
              <div v-if="c.suggestion" class="text-xs text-amber-600 dark:text-amber-400">建议：{{ c.suggestion }}</div>
            </div>
          </div>
          <div v-if="!m.checks.length" class="text-xs text-slate-400">暂无安全检查数据（需 Agent 上报）</div>
        </div>
      </div>
    </template>
  </div>`,
  setup() {
    const m = Vue.computed(() => store.serverMetrics);
    const latest = Vue.computed(() => (m.value.metrics && m.value.metrics.length) ? m.value.metrics[0] : null);
    let chartInstance = null;
    function renderChart() {
      const canvas = document.getElementById('metricsChart');
      if (!canvas || !window.Chart) return;
      if (!m.value.metrics || m.value.metrics.length < 2) return;
      if (chartInstance) { chartInstance.destroy(); chartInstance = null; }
      const data = [...m.value.metrics].reverse();
      const labels = data.map(p => new Date(p.ts).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }));
      chartInstance = new Chart(canvas, {
        type: 'line',
        data: {
          labels,
          datasets: [
            { label: 'CPU %', data: data.map(p => p.cpu_pct), borderColor: '#3b82f6', backgroundColor: 'rgba(59,130,246,0.1)', tension: 0.3, pointRadius: 0 },
            { label: '内存 %', data: data.map(p => p.mem_pct), borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,0.1)', tension: 0.3, pointRadius: 0 },
            { label: '磁盘 %', data: data.map(p => p.disk_pct), borderColor: '#f59e0b', backgroundColor: 'rgba(245,158,11,0.1)', tension: 0.3, pointRadius: 0 },
          ],
        },
        options: {
          responsive: true,
          interaction: { mode: 'index', intersect: false },
          scales: { y: { min: 0, max: 100, ticks: { callback: v => v + '%' } } },
          plugins: { legend: { position: 'top' } },
        },
      });
    }
    Vue.watch(m, () => { Vue.nextTick(renderChart); }, { deep: true });
    Vue.onMounted(() => { Vue.nextTick(renderChart); });
    Vue.onUnmounted(() => { if (chartInstance) { chartInstance.destroy(); chartInstance = null; } });
    function scoreClass(level) {
      return { good: 'text-emerald-600 dark:text-emerald-400', warning: 'text-amber-600 dark:text-amber-400', risk: 'text-red-600 dark:text-red-400', unknown: 'text-slate-400' }[level] || 'text-slate-400';
    }
    function goBack() { window.location.hash = '#assets'; }
    return { store, Fmt, m, latest, scoreClass, goBack };
  },
};
