<template>
  <div class="system-tab">
    <div v-if="loading" class="system-tab__loading">
      <a-spin size="small" />
      <span>加载系统资源...</span>
    </div>

    <div v-else-if="error" class="system-tab__error">
      <WarningOutlined />
      <span>{{ error }}</span>
    </div>

    <div v-else class="system-tab__body">
      <div class="system-tab__card">
        <div class="system-tab__card-title">CPU</div>
        <div class="system-tab__metric-row">
          <span class="system-tab__metric-value">{{ resources.cpu.count }} 核</span>
          <span class="system-tab__metric-label">负载</span>
        </div>
        <div class="system-tab__bar">
          <div
            class="system-tab__bar-fill"
            :style="{ width: cpuLoadPercent + '%' }"
          />
        </div>
        <div class="system-tab__metric-detail">
          {{ cpuLoadAverage }}
        </div>
      </div>

      <div class="system-tab__card">
        <div class="system-tab__card-title">内存</div>
        <div class="system-tab__metric-row">
          <span class="system-tab__metric-value">{{ memoryPercent }}%</span>
          <span class="system-tab__metric-label">已用</span>
        </div>
        <div class="system-tab__bar">
          <div
            class="system-tab__bar-fill"
            :class="{ 'system-tab__bar-fill--warning': memoryPercent > 80 }"
            :style="{ width: memoryPercent + '%' }"
          />
        </div>
        <div class="system-tab__metric-detail">
          {{ formatBytes(resources.memory.used_bytes) }} / {{ formatBytes(resources.memory.total_bytes) }}
        </div>
      </div>

      <div class="system-tab__card">
        <div class="system-tab__card-title">磁盘</div>
        <div class="system-tab__metric-row">
          <span class="system-tab__metric-value">{{ diskPercent }}%</span>
          <span class="system-tab__metric-label">已用</span>
        </div>
        <div class="system-tab__bar">
          <div
            class="system-tab__bar-fill"
            :class="{ 'system-tab__bar-fill--warning': diskPercent > 85 }"
            :style="{ width: diskPercent + '%' }"
          />
        </div>
        <div class="system-tab__metric-detail">
          {{ formatBytes(resources.disk.used_bytes) }} / {{ formatBytes(resources.disk.total_bytes) }}
        </div>
      </div>

      <div class="system-tab__updated">
        更新时间：{{ updatedAt }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { WarningOutlined } from '@ant-design/icons-vue'
import { getResources, type ISystemResources } from '@/api/system'

const loading = ref(false)
const error = ref('')
const resources = ref<ISystemResources>({
  cpu: { count: 1, load_average: null },
  memory: { total_bytes: 0, used_bytes: 0, free_bytes: 0, percent: null },
  disk: { total_bytes: 0, used_bytes: 0, free_bytes: 0, percent: null },
  timestamp: 0,
})

const cpuLoadPercent = computed(() => {
  const load = resources.value.cpu.load_average?.[0]
  if (!load || resources.value.cpu.count <= 0) return 0
  return Math.min((load / resources.value.cpu.count) * 100, 100)
})

const cpuLoadAverage = computed(() => {
  const load = resources.value.cpu.load_average
  if (!load || load.length === 0) return '—'
  return `1m: ${load[0].toFixed(2)}${load[1] !== undefined ? ` / 5m: ${load[1].toFixed(2)}` : ''}`
})

const memoryPercent = computed(() => resources.value.memory.percent ?? 0)
const diskPercent = computed(() => resources.value.disk.percent ?? 0)

const updatedAt = computed(() => {
  if (!resources.value.timestamp) return '—'
  return new Date(resources.value.timestamp * 1000).toLocaleString()
})

function formatBytes(bytes: number): string {
  if (bytes === 0) return '—'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let idx = 0
  let value = bytes
  while (value >= 1024 && idx < units.length - 1) {
    value /= 1024
    idx++
  }
  return `${value.toFixed(1)} ${units[idx]}`
}

async function refresh(): Promise<void> {
  loading.value = true
  error.value = ''
  try {
    resources.value = await getResources()
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : '加载失败'
  } finally {
    loading.value = false
  }
}

let refreshTimer: number | null = null

onMounted(() => {
  refresh()
  refreshTimer = window.setInterval(refresh, 10000)
})

onUnmounted(() => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.system-tab {
  height: 100%;
  overflow-y: auto;
  padding: var(--space-3) var(--space-4);
}

.system-tab__loading,
.system-tab__error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--space-2);
  padding: var(--space-8) 0;
  color: var(--text-tertiary);
  font-size: var(--font-sm);
}

.system-tab__error {
  color: var(--color-error);
}

.system-tab__body {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.system-tab__card {
  padding: var(--space-3);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  background: var(--bg-primary);
}

.system-tab__card-title {
  font-size: var(--font-sm);
  font-weight: var(--font-weight-medium);
  color: var(--text-primary);
  margin-bottom: var(--space-2);
}

.system-tab__metric-row {
  display: flex;
  align-items: baseline;
  gap: var(--space-1);
  margin-bottom: var(--space-2);
}

.system-tab__metric-value {
  font-size: 20px;
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.system-tab__metric-label {
  font-size: var(--font-sm);
  color: var(--text-tertiary);
}

.system-tab__bar {
  height: 6px;
  background: var(--bg-tertiary);
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: var(--space-2);
}

.system-tab__bar-fill {
  height: 100%;
  background: var(--accent-team);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.system-tab__bar-fill--warning {
  background: var(--color-warning);
}

.system-tab__metric-detail {
  font-size: var(--font-xs);
  color: var(--text-tertiary);
}

.system-tab__updated {
  font-size: var(--font-xs);
  color: var(--text-placeholder);
  text-align: right;
}
</style>
