<template>
  <div class="container">
    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-primary">
              <icon-storage />
            </div>
            <div class="stats-info">
              <div class="stats-title">虚拟机总数</div>
              <div class="stats-value">{{ stats.total }}</div>
              <div class="stats-desc">宿主机 {{ stats.assetGroups }}</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-success">
              <icon-check-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">运行中</div>
              <div class="stats-value">{{ stats.running }}</div>
              <div class="stats-desc text-success">{{ runningRateText }}</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-primary">
              <icon-code-square />
            </div>
            <div class="stats-info">
              <div class="stats-title">CPU使用率</div>
              <div class="stats-value">{{ statsCpuUsageText }}%</div>
              <div class="stats-desc">平均</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-content">
            <div class="stats-icon stats-icon-cyan">
              <icon-drive-file />
            </div>
            <div class="stats-info">
              <div class="stats-title">内存使用率</div>
              <div class="stats-value">{{ statsMemoryUsageText }}%</div>
              <div class="stats-desc">平均</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-alert
      v-if="showVirtualEmptyTip"
      class="empty-tip"
      type="info"
      show-icon
      banner
    >
      当前暂无已关联资产的虚拟服务器。请在服务器管理中将虚拟服务器关联到资产；宿主机趋势还需要配置已关联资产的物理服务器。
    </a-alert>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="chart-row">
      <a-col :xs="24" :lg="8">
        <a-card title="资源使用趋势" :bordered="false">
          <template #extra>
            <a-space>
              <span class="legend-item">
                <span class="legend-dot legend-dot-1"></span>
                <span>CPU</span>
              </span>
              <span class="legend-item">
                <span class="legend-dot legend-dot-3"></span>
                <span>内存</span>
              </span>
            </a-space>
          </template>
          <div class="chart-container">
            <Chart :options="performanceChartOptions" height="240px" />
          </div>
          <div class="chart-legend-placeholder"></div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8">
        <a-card title="CPU资源分配" :bordered="false">
          <template #extra>
            <span class="text-muted">总计 {{ cpuTotalText }} vCPU</span>
          </template>
          <div class="chart-container">
            <Chart :options="cpuChartOptions" height="240px" />
          </div>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-dot legend-dot-1"></span>
              <span>已使用 {{ cpuVirtualText }} vCPU</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot legend-dot-gray"></span>
              <span>总计 {{ cpuPhysicalText }} vCPU</span>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8">
        <a-card title="内存资源分配" :bordered="false">
          <template #extra>
            <span class="text-muted">总计 {{ memoryTotalText }} GB</span>
          </template>
          <div class="chart-container">
            <Chart :options="memoryChartOptions" height="240px" />
          </div>
          <div class="chart-legend">
            <div class="legend-item">
              <span class="legend-dot legend-dot-2"></span>
              <span>已使用 {{ memoryVirtualText }} GB</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot legend-dot-gray"></span>
              <span>总计 {{ memoryPhysicalText }} GB</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 宿主机状态 -->
    <a-row :gutter="16" class="host-row">
      <a-col v-for="host in hostStatus" :key="host.name" :xs="12" :sm="6">
        <a-card class="host-card" :bordered="false">
          <div class="host-header">
            <span class="host-name">{{ host.name }}</span>
            <a-tag :color="host.physicalCount > 0 ? 'green' : 'gray'" size="small">
              {{ host.physicalCount > 0 ? '有物理机' : '仅虚拟机' }}
            </a-tag>
          </div>
          <div class="host-metrics">
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-label">CPU</span>
                <span class="metric-value">{{ host.cpu }}%</span>
              </div>
              <a-progress :percent="host.cpu / 100" :stroke-width="6" :show-text="false" />
            </div>
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-label">内存</span>
                <span class="metric-value">{{ host.memory }}%</span>
              </div>
              <a-progress :percent="host.memory / 100" :stroke-width="6" :show-text="false" />
            </div>
            <div class="metric-item metric-vm">
              <span class="metric-label">虚拟机数</span>
              <span class="metric-value-right">{{ host.vmCount }}</span>
            </div>
            <div class="metric-item metric-vm">
              <span class="metric-label">物理机数</span>
              <span class="metric-value-right">{{ host.physicalCount }}</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 虚拟机列表模块按需求下线（暂不渲染） -->
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconStorage, IconCheckCircleFill, IconCodeSquare, IconDriveFile } from '@arco-design/web-vue/es/icon'
import Chart from '@/components/chart/index.vue'
import {
  fetchAssetMixedSummary,
  fetchLatestResourceSummary,
  fetchPhysicalUsageTrend24h,
  fetchVirtualOverview,
  type AssetMixedSummaryItem,
} from '@/api/ops/server'

// 统计数据
const stats = ref({
  total: 0,
  assetGroups: 0,
  running: 0,
  cpuUsage: 0,
  memoryUsage: 0,
})

const loading = ref(true)

// 宿主机状态
const hostStatus = ref<
  Array<{
    name: string
    cpu: number
    memory: number
    vmCount: number
    physicalCount: number
  }>
>([])

// 资源使用趋势图表配置
const performanceChartOptions = ref({
  tooltip: {
    trigger: 'axis',
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
  },
  yAxis: {
    type: 'value',
    name: '%',
    max: 100,
  },
  series: [
    {
      name: 'CPU',
      type: 'line',
      smooth: true,
      data: [] as number[],
      lineStyle: {
        width: 2,
        color: '#165DFF',
      },
      itemStyle: {
        color: '#165DFF',
      },
    },
    {
      name: '内存',
      type: 'line',
      smooth: true,
      data: [] as number[],
      lineStyle: {
        width: 2,
        color: '#F7BA1E',
      },
      itemStyle: {
        color: '#F7BA1E',
      },
    },
  ],
})

// CPU资源分配图表配置
const cpuChartOptions = ref({
  tooltip: {
    trigger: 'item',
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
      },
      data: [
        { value: 0, name: 'virtual', itemStyle: { color: '#165DFF' } },
        { value: 0, name: 'physical', itemStyle: { color: '#E5E6EB' } },
      ],
    },
  ],
})

// 内存资源分配图表配置
const memoryChartOptions = ref({
  tooltip: {
    trigger: 'item',
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
      },
      data: [
        { value: 0, name: 'virtual', itemStyle: { color: '#14C9C9' } },
        { value: 0, name: 'physical', itemStyle: { color: '#E5E6EB' } },
      ],
    },
  ],
})

const cpuVirtual = ref(0)
const cpuPhysical = ref(0)
const memVirtualGb = ref(0)
const memPhysicalGb = ref(0)

const roundToTwo = (value: number) => Math.round(value * 100) / 100
const formatMaxTwoDecimals = (value: number) => {
  const rounded = roundToTwo(value)
  return Number.isInteger(rounded) ? String(rounded) : String(rounded)
}

const runningRateText = computed(() => {
  if (!stats.value.total) return '0%'
  return `${formatMaxTwoDecimals((stats.value.running / stats.value.total) * 100)}%`
})
const statsCpuUsageText = computed(() => formatMaxTwoDecimals(stats.value.cpuUsage))
const statsMemoryUsageText = computed(() => formatMaxTwoDecimals(stats.value.memoryUsage))
const cpuTotalText = computed(() => formatMaxTwoDecimals(cpuVirtual.value + cpuPhysical.value))
const cpuVirtualText = computed(() => formatMaxTwoDecimals(cpuVirtual.value))
const cpuPhysicalText = computed(() => formatMaxTwoDecimals(cpuPhysical.value))
const memoryTotalText = computed(() => formatMaxTwoDecimals(memVirtualGb.value + memPhysicalGb.value))
const memoryVirtualText = computed(() => formatMaxTwoDecimals(memVirtualGb.value))
const memoryPhysicalText = computed(() => formatMaxTwoDecimals(memPhysicalGb.value))
const showVirtualEmptyTip = computed(() => !loading.value && stats.value.total === 0)
const toGb = (bytes: number) => bytes / 1024 / 1024 / 1024
const safeNum = (v: number | null | undefined) => (typeof v === 'number' ? v : 0)
const hourLabel = (v: string) => {
  const d = new Date(v)
  if (Number.isNaN(d.getTime())) return v
  return `${String(d.getHours()).padStart(2, '0')}:00`
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const [overviewRes, trendRes, resourceRes, mixedRes] = await Promise.all([
      fetchVirtualOverview(),
      fetchPhysicalUsageTrend24h(),
      fetchLatestResourceSummary(),
      fetchAssetMixedSummary(),
    ])

    if (overviewRes.code !== 0 || !overviewRes.details) {
      Message.error(overviewRes.message || '加载虚拟机概览失败')
      return
    }
    const overview = overviewRes.details
    stats.value.total = overview.vm_total || 0
    stats.value.assetGroups = overview.asset_group_total || 0
    stats.value.running = overview.online_total || 0
    stats.value.cpuUsage = roundToTwo(safeNum(overview.latest_cpu_usage_avg))
    stats.value.memoryUsage = roundToTwo(safeNum(overview.latest_mem_usage_avg))

    if (trendRes.code === 0 && trendRes.details?.points) {
      const labels = trendRes.details.points.map((p) => hourLabel(p.hour))
      const cpuSeries = trendRes.details.points.map((p) => roundToTwo(safeNum(p.cpu_used_percent_avg)))
      const memSeries = trendRes.details.points.map((p) => roundToTwo(safeNum(p.mem_used_percent_avg)))
      ;(performanceChartOptions.value.xAxis as { data: string[] }).data = labels
      ;(performanceChartOptions.value.series[0] as { data: number[] }).data = cpuSeries
      ;(performanceChartOptions.value.series[1] as { data: number[] }).data = memSeries
    }

    if (resourceRes.code === 0 && resourceRes.details) {
      cpuVirtual.value = roundToTwo(safeNum(resourceRes.details.virtual?.total_vcpu))
      cpuPhysical.value = roundToTwo(safeNum(resourceRes.details.physical?.total_vcpu))
      memVirtualGb.value = roundToTwo(toGb(safeNum(resourceRes.details.virtual?.total_mem_bytes)))
      memPhysicalGb.value = roundToTwo(toGb(safeNum(resourceRes.details.physical?.total_mem_bytes)))
      ;(cpuChartOptions.value.series[0] as { data: Array<{ value: number; name: string }> }).data = [
        { value: cpuVirtual.value, name: 'virtual' },
        { value: cpuPhysical.value, name: 'physical' },
      ]
      ;(memoryChartOptions.value.series[0] as { data: Array<{ value: number; name: string }> }).data = [
        { value: memVirtualGb.value, name: 'virtual' },
        { value: memPhysicalGb.value, name: 'physical' },
      ]
    }

    if (mixedRes.code === 0 && mixedRes.details?.data) {
      hostStatus.value = (mixedRes.details.data as AssetMixedSummaryItem[]).map((item) => ({
        name: `Asset-${item.asset_id}`,
        cpu: Number(safeNum(item.physical_latest_cpu_usage).toFixed(2)),
        memory: Number(safeNum(item.physical_latest_mem_usage).toFixed(2)),
        vmCount: item.virtual_count || 0,
        physicalCount: item.physical_count || 0,
      }))
    } else {
      hostStatus.value = []
    }
  } catch (e: any) {
    Message.error(e?.message || '加载虚拟化监控数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<script lang="ts">
export default {
  name: 'VirtualizationMonitor',
}
</script>

<style scoped lang="less">
.container {
  padding: 16px;
}

.stats-row {
  margin-bottom: 16px;
}

.empty-tip {
  margin-bottom: 16px;
}

.stats-card {
  height: 100%;

  :deep(.arco-card-body) {
    padding: 16px;
  }

  .stats-content {
    display: flex;
    align-items: flex-start;
    gap: 12px;
  }

  .stats-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;

    &-primary {
      background-color: rgba(22, 93, 255, 0.1);
      color: rgb(var(--primary-6));
    }

    &-success {
      background-color: rgba(0, 180, 42, 0.1);
      color: rgb(var(--success-6));
    }

    &-cyan {
      background-color: rgba(20, 201, 201, 0.1);
      color: #14c9c9;
    }
  }

  .stats-info {
    flex: 1;
  }

  .stats-title {
    font-size: 14px;
    color: var(--color-text-3);
    margin-bottom: 4px;
  }

  .stats-value {
    font-size: 24px;
    font-weight: 600;
    color: var(--color-text-1);
    line-height: 1.2;
    margin-bottom: 4px;
  }

  .stats-desc {
    font-size: 12px;
    color: var(--color-text-3);
  }
}

.chart-row {
  margin-bottom: 16px;
}

.chart-container {
  height: 240px;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 8px;
}

.chart-legend-placeholder {
  height: 24px;
}

.legend-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--color-text-3);
}

.legend-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;

  &-1 {
    background-color: #165dff;
  }

  &-2 {
    background-color: #14c9c9;
  }

  &-3 {
    background-color: #f7ba1e;
  }

  &-gray {
    background-color: #e5e6eb;
  }
}

.text-muted {
  color: var(--color-text-3);
}

.text-success {
  color: rgb(var(--success-6));
}

.host-row {
  margin-bottom: 16px;
}

.host-card {
  height: 100%;

  :deep(.arco-card-body) {
    padding: 16px;
  }

  .host-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
  }

  .host-name {
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text-1);
  }

  .host-metrics {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .metric-item {
    .metric-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
    }

    .metric-label {
      font-size: 12px;
      color: var(--color-text-3);
    }

    .metric-value {
      font-size: 12px;
      color: var(--color-text-1);
    }
  }

  .metric-vm {
    margin-top: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .metric-value-right {
    font-size: 12px;
    color: var(--color-text-1);
  }
}

.progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .progress-text {
    font-size: 12px;
    color: var(--color-text-3);
    min-width: 36px;
  }
}
</style>
