<template>
  <div class="panel-status">
    <a-row :gutter="[24, 24]">
      <!-- 顶部概览 -->
      <a-col :span="24">
        <a-card>
          <div class="overview-bar">
            <div class="overview-item">
              <span class="overview-label">面板总数</span>
              <a-tag color="blue">{{ panels.length }} 个</a-tag>
            </div>
            <div class="overview-item">
              <span class="overview-label">在线面板</span>
              <a-tag color="green">{{ onlineCount }} 个</a-tag>
            </div>
            <div class="overview-item">
              <span class="overview-label">离线面板</span>
              <a-tag color="default">{{ offlineCount }} 个</a-tag>
            </div>
            <div class="overview-item">
              <span class="overview-label">告警面板</span>
              <a-tag color="red">{{ alarmPanelCount }} 个</a-tag>
            </div>
            <div class="overview-item">
              <span class="overview-label">最近更新</span>
              <span class="overview-value">{{ lastUpdate }}</span>
            </div>
            <div class="overview-item">
              <a-button type="primary" size="small" @click="refreshData" :loading="loading">
                刷新
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 面板状态卡片 -->
      <a-col :span="24">
        <a-card title="面板状态">
          <a-empty v-if="panels.length === 0" description="暂无面板数据" />
          <div v-else class="panel-grid">
            <div
              v-for="panel in sortedPanels"
              :key="panel.panel_id"
              class="panel-card"
              :class="getPanelClass(panel)"
            >
              <div class="panel-header">
                <span class="panel-id">面板 {{ panel.panel_id }}</span>
                <a-tag :color="getStatusColor(panel.status)" size="small">
                  {{ panel.status === 'online' ? '在线' : '离线' }}
                </a-tag>
              </div>
              <div class="panel-info">
                <div class="info-row">
                  <span class="info-label">地址:</span>
                  <span class="info-value">{{ panel.address ?? '--' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">位置:</span>
                  <span class="info-value">{{ panel.position ?? '--' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">UID:</span>
                  <span class="info-value uid-text">{{ formatUid(panel.panel_uid) }}</span>
                </div>
              </div>
              <a-divider style="margin: 12px 0" />
              <div class="panel-stats">
                <div class="stat-item">
                  <span class="stat-label">端口数</span>
                  <span class="stat-value">{{ panel.port_count }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">已连接</span>
                  <span class="stat-value success">{{ panel.connected_count }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">告警数</span>
                  <span class="stat-value" :class="{ error: panel.alarm_count > 0 }">
                    {{ panel.alarm_count }}
                  </span>
                </div>
              </div>
              <div class="panel-progress">
                <a-progress
                  :percent="getConnectPercent(panel)"
                  :show-info="false"
                  :stroke-color="getProgressColor(panel)"
                  :trail-color="'#f0f0f0'"
                  size="small"
                />
                <span class="progress-text">{{ getConnectPercent(panel) }}%</span>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import apiService from '../api/apiService'

const loading = ref(false)
const lastUpdate = ref('')
const panels = ref([])
const pollTimer = ref(null)

const onlineCount = computed(() => panels.value.filter(p => p.status === 'online').length)

const offlineCount = computed(() => panels.value.filter(p => p.status === 'offline').length)

const alarmPanelCount = computed(() => panels.value.filter(p => p.alarm_count > 0).length)

const sortedPanels = computed(() => {
  return [...panels.value].sort((a, b) => {
    const idA = Number(a.panel_id) || 0
    const idB = Number(b.panel_id) || 0
    return idA - idB
  })
})

function getPanelClass(panel) {
  if (panel.status === 'offline') return 'panel-offline'
  if (panel.alarm_count > 0) return 'panel-alarm'
  return 'panel-online'
}

function getStatusColor(status) {
  return status === 'online' ? 'green' : 'default'
}

function getConnectPercent(panel) {
  if (!panel.port_count) return 0
  return Math.round((panel.connected_count / panel.port_count) * 100)
}

function getProgressColor(panel) {
  if (panel.alarm_count > 0) return '#ff4d4f'
  if (panel.status === 'offline') return '#d9d9d9'
  return '#52c41a'
}

function formatUid(uid) {
  if (!uid) return '--'
  if (typeof uid === 'string' && uid.length === 8) {
    return uid.match(/.{1,2}/g)?.join(':') || uid
  }
  return String(uid).substring(0, 8)
}

async function loadPanelStatus() {
  try {
    const res = await apiService.panel.getStatus()
    if (res.data.success) {
      panels.value = Object.values(res.data.panels || {})
    }
  } catch (e) {
    console.error('load panel status error:', e)
  }
}

async function refreshData() {
  loading.value = true
  try {
    await loadPanelStatus()
    lastUpdate.value = new Date().toLocaleTimeString()
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await refreshData()
  pollTimer.value = setInterval(refreshData, 5000)
})

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

<style scoped>
.overview-bar {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}
.overview-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
.overview-label {
  font-size: 14px;
  color: #666;
}
.overview-value {
  font-size: 14px;
  color: #333;
}
.panel-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}
.panel-card {
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  padding: 16px;
  transition: all 0.3s;
}
.panel-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}
.panel-online {
  border-color: #b7eb8f;
  background-color: #f6ffed;
}
.panel-offline {
  border-color: #d9d9d9;
  background-color: #fafafa;
}
.panel-alarm {
  border-color: #ffccc7;
  background-color: #fff2f0;
  animation: pulse 1.5s infinite;
}
@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.85; }
}
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}
.panel-id {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.panel-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}
.info-label {
  color: #666;
  min-width: 40px;
}
.info-value {
  color: #333;
}
.uid-text {
  font-family: monospace;
  font-size: 12px;
}
.panel-stats {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
}
.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.stat-label {
  font-size: 12px;
  color: #999;
}
.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.stat-value.success {
  color: #52c41a;
}
.stat-value.error {
  color: #ff4d4f;
}
.panel-progress {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}
.panel-progress :deep(.ant-progress) {
  flex: 1;
}
.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 36px;
  text-align: right;
}
</style>