<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-title">受管设备</div>
          <div class="stats-value">{{ overview.total_devices ?? 0 }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-title">在线设备</div>
          <div class="stats-value text-success">{{ overview.online_devices ?? 0 }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-title">离线/异常</div>
          <div class="stats-value text-danger">{{ overview.abnormal_devices ?? 0 }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card class="stats-card" :bordered="false">
          <div class="stats-title">平均响应时延</div>
          <div class="stats-value">{{ Number(overview.avg_response_time_ms || 0).toFixed(1) }} ms</div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" class="section-row">
      <a-col :xs="24" :lg="8" class="panel-col">
        <a-card title="设备健康矩阵" :bordered="false" class="panel-card">
          <div class="matrix-list">
            <div v-for="item in healthMatrix" :key="`${item.error_bucket}-${item.latency_bucket}`" class="matrix-item">
              <span>{{ item.error_bucket }} / {{ item.latency_bucket }}</span>
              <a-tag>{{ item.count }}</a-tag>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8" class="panel-col">
        <a-card title="采集新鲜度分布" :bordered="false" class="panel-card">
          <div class="simple-list">
            <div v-for="item in freshness" :key="item.bucket_label" class="simple-item">
              <span>{{ item.bucket_label }}</span>
              <b>{{ item.count }}</b>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="8" class="panel-col">
        <a-card title="协议/版本分布" :bordered="false" class="panel-card">
          <div class="simple-list">
            <div v-for="item in protocols" :key="`${item.protocol}-${item.snmp_version}`" class="simple-item">
              <span>{{ item.protocol || '-' }} / {{ item.snmp_version || '-' }}</span>
              <b>{{ item.count }}</b>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" class="section-row">
      <a-col :xs="24" :lg="12">
        <a-card title="资源概览" :bordered="false">
          <a-descriptions :column="2" size="small" bordered>
            <a-descriptions-item label="接口总量">{{ resource.interface_summary?.total || 0 }}</a-descriptions-item>
            <a-descriptions-item label="接口Up/Down">
              {{ resource.interface_summary?.up || 0 }} / {{ resource.interface_summary?.down || 0 }}
            </a-descriptions-item>
            <a-descriptions-item label="ARP总量">{{ resource.arp_summary?.total || 0 }}</a-descriptions-item>
            <a-descriptions-item label="ARP去重IP">{{ resource.arp_summary?.unique_ip_count || 0 }}</a-descriptions-item>
            <a-descriptions-item label="路由总量">{{ resource.route_summary?.total || 0 }}</a-descriptions-item>
            <a-descriptions-item label="FIB总量">{{ resource.fib_summary?.total || 0 }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="12">
        <a-card title="异常事件带" :bordered="false">
          <div class="simple-list">
            <div v-for="item in alerts.top_continuous_errors || []" :key="item.id" class="simple-item">
              <span>{{ item.name }} ({{ item.host }})</span>
              <a-tag color="red">连续错误 {{ item.continuous_errors }}</a-tag>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-card title="设备明细" :bordered="false">
      <template #extra>
        <a-space>
          <a-input-search v-model="filters.keyword" placeholder="设备名/IP/型号" style="width: 220px" @search="fetchDevices" />
          <a-select v-model="filters.status" placeholder="状态" allow-clear style="width: 120px" @change="fetchDevices">
            <a-option value="online">online</a-option>
            <a-option value="offline">offline</a-option>
            <a-option value="error">error</a-option>
            <a-option value="unknown">unknown</a-option>
          </a-select>
          <a-button type="primary" @click="fetchAll">刷新</a-button>
        </a-space>
      </template>
      <a-table :data="devices" :columns="columns" :loading="loading" row-key="id" :pagination="pagination">
        <template #status="{ record }">
          <a-tag :color="statusColor(record.status)">{{ record.status }}</a-tag>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, reactive, ref } from 'vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { Message } from '@arco-design/web-vue'
import {
  fetchNetworkScreenAlertsStream,
  fetchNetworkScreenDevices,
  fetchNetworkScreenFreshnessDistribution,
  fetchNetworkScreenHealthMatrix,
  fetchNetworkScreenOverview,
  fetchNetworkScreenProtocolDistribution,
  fetchNetworkScreenResourceOverview,
} from '@/api/ops/network-screen'

const loading = ref(false)
const overview = reactive<Record<string, any>>({})
const healthMatrix = ref<any[]>([])
const freshness = ref<any[]>([])
const protocols = ref<any[]>([])
const resource = reactive<Record<string, any>>({})
const alerts = reactive<Record<string, any>>({})
const devices = ref<any[]>([])
const pollTimer = ref<number | null>(null)

const filters = reactive({
  keyword: '',
  status: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  onChange: (page: number) => {
    pagination.current = page
    fetchDevices()
  },
})

const columns: TableColumnData[] = [
  { title: '设备', dataIndex: 'name' },
  { title: '管理IP', dataIndex: 'host' },
  { title: '协议', dataIndex: 'protocol' },
  { title: '厂商', dataIndex: 'vendor' },
  { title: '状态', dataIndex: 'status', slotName: 'status' },
  { title: '响应时延(ms)', dataIndex: 'response_time' },
  { title: '最后检查时间', dataIndex: 'last_check_time' },
  { title: '连续错误', dataIndex: 'continuous_errors' },
]

const statusColor = (status: string) => {
  if (status === 'online') return 'green'
  if (status === 'offline') return 'red'
  if (status === 'error') return 'orangered'
  return 'orange'
}

const fetchDevices = async () => {
  loading.value = true
  try {
    const res: any = await fetchNetworkScreenDevices({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: filters.keyword || undefined,
      status: filters.status || undefined,
    })
    devices.value = res?.details?.data || []
    pagination.total = res?.details?.total || 0
  } finally {
    loading.value = false
  }
}

const fetchAll = async () => {
  try {
    const [a, b, c, d, e, f] = await Promise.all([
      fetchNetworkScreenOverview(),
      fetchNetworkScreenHealthMatrix({ window: '15m' }),
      fetchNetworkScreenFreshnessDistribution(),
      fetchNetworkScreenProtocolDistribution(),
      fetchNetworkScreenResourceOverview({ window: '1h' }),
      fetchNetworkScreenAlertsStream({ limit: 10 }),
    ])
    Object.assign(overview, a?.details || {})
    healthMatrix.value = b?.details?.data || []
    freshness.value = c?.details?.data || []
    protocols.value = d?.details?.data || []
    Object.assign(resource, e?.details || {})
    Object.assign(alerts, f?.details || {})
    await fetchDevices()
  } catch (e) {
    Message.error('网络设备大屏数据加载失败')
  }
}

onMounted(async () => {
  await fetchAll()
  pollTimer.value = window.setInterval(fetchAll, 30000)
})

onBeforeUnmount(() => {
  if (pollTimer.value) window.clearInterval(pollTimer.value)
})
</script>

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

<style scoped lang="less">
.container {
  padding: 16px;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  overflow: auto;
}

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

.stats-card {
  .stats-title {
    color: var(--color-text-2);
    margin-bottom: 8px;
  }
  .stats-value {
    font-size: 28px;
    font-weight: 700;
  }
}

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

.panel-col {
  display: flex;
}

.panel-card {
  width: 100%;
  min-height: 320px;
  display: flex;
  flex-direction: column;
}

:deep(.panel-card .arco-card-body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.matrix-list,
.simple-list {
  flex: 1;
  min-height: 0;
  max-height: 260px;
  overflow: auto;
}
.matrix-item,
.simple-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid var(--color-border-2);
}

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

.text-success {
  color: rgb(var(--success-6));
}
</style>
