<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-safe />
            </div>
            <div class="stats-info">
              <div class="stats-title">安全设备</div>
              <div class="stats-value">{{ stats.totalDevices }}</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-success">
              <icon-check-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">威胁拦截</div>
              <div class="stats-value">{{ stats.threatsBlocked }}</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-danger">
              <icon-exclamation-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">高危威胁</div>
              <div class="stats-value">{{ stats.highRiskThreats }}</div>
              <div class="stats-desc text-danger">需立即处理</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-muted">
              <icon-close-circle-fill />
            </div>
            <div class="stats-info">
              <div class="stats-title">离线设备</div>
              <div class="stats-value">{{ stats.offlineDevices }}</div>
              <div class="stats-desc text-danger">VPN网关异常</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 图表区域 -->
    <a-row :gutter="16" class="chart-row">
      <a-col :xs="24" :lg="12">
        <a-card title="威胁趋势" :bordered="false">
          <template #extra>
            <a-space>
              <span class="legend-item">
                <span class="legend-dot legend-dot-1"></span>
                <span>检测</span>
              </span>
              <span class="legend-item">
                <span class="legend-dot legend-dot-2"></span>
                <span>拦截</span>
              </span>
            </a-space>
          </template>
          <div class="chart-container">
            <Chart :options="threatChartOptions" height="280px" />
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :lg="12">
        <a-card title="威胁分类统计" :bordered="false">
          <template #extra>
            <span class="text-muted">今日威胁类型分布</span>
          </template>
          <div class="threat-category-list">
            <div v-for="item in threatCategories" :key="item.name" class="threat-category-item">
              <div class="threat-category-header">
                <div class="threat-category-icon" :style="{ backgroundColor: item.bgColor }">
                  <component :is="item.icon" :style="{ color: item.color }" />
                </div>
                <div class="threat-category-info">
                  <div class="threat-category-name">{{ item.name }}</div>
                  <a-progress :percent="item.percent" :stroke-width="8" :show-text="false" :status="item.progressStatus" />
                </div>
                <span class="threat-category-value" :style="{ color: item.color }">{{ item.value }}</span>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 设备列表 -->
    <a-card title="设备列表" :bordered="false">
      <template #extra>
        <a-select v-model="filterType" placeholder="全部类型" style="width: 150px">
          <a-option value="">全部类型</a-option>
          <a-option value="firewall">防火墙</a-option>
          <a-option value="ids">IDS</a-option>
          <a-option value="ips">IPS</a-option>
          <a-option value="waf">WAF</a-option>
          <a-option value="vpn">VPN</a-option>
        </a-select>
      </template>
      <a-table :data="filteredDevices" :columns="columns" :loading="loading" :pagination="false" row-key="id">
        <!-- 状态列 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)" bordered>
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <!-- 响应时间列 -->
        <template #responseTime="{ record }">
          <span v-if="record.response_time">{{ record.response_time.toFixed(2) }} ms</span>
          <span v-else>-</span>
        </template>

        <!-- 运行时长列 -->
        <template #uptime="{ record }">
          <span>{{ formatUptime(record.uptime) }}</span>
        </template>

        <!-- 最近检查时间列 -->
        <template #lastCheckTime="{ record }">
          <span>{{ formatTime(record.last_check_time) }}</span>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import {
  IconSafe,
  IconCheckCircleFill,
  IconExclamationCircleFill,
  IconCloseCircleFill,
  IconThunderbolt,
  IconLock,
  IconCode,
} from '@arco-design/web-vue/es/icon'
import Chart from '@/components/chart/index.vue'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { fetchSecurityServiceList, type SecurityServiceItem } from '@/api/ops/security'

const loading = ref(false)
const filterType = ref('')
const deviceData = ref<SecurityServiceItem[]>([])

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '设备名称',
    dataIndex: 'name',
    width: 150,
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 120,
  },
  {
    title: '服务标识',
    dataIndex: 'service_identity',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
    align: 'center',
  },
  {
    title: '响应时间',
    dataIndex: 'response_time',
    slotName: 'responseTime',
    width: 120,
    align: 'center',
  },
  {
    title: '运行时长',
    dataIndex: 'uptime',
    slotName: 'uptime',
    width: 120,
    align: 'center',
  },
  {
    title: '连续错误',
    dataIndex: 'continuous_errors',
    width: 100,
    align: 'center',
  },
  {
    title: '最近检查',
    dataIndex: 'last_check_time',
    slotName: 'lastCheckTime',
    width: 180,
  },
]

// 统计数据
const stats = computed(() => {
  const total = deviceData.value.length
  const online = deviceData.value.filter((d) => d.status === 'online').length
  const offline = deviceData.value.filter((d) => d.status === 'offline').length
  const error = deviceData.value.filter((d) => d.status === 'error').length
  return {
    totalDevices: online,
    threatsBlocked: '-',
    highRiskThreats: error,
    offlineDevices: offline,
  }
})

// 过滤后的设备列表
const filteredDevices = computed(() => {
  if (!filterType.value) return deviceData.value
  return deviceData.value.filter((device) => device.type === filterType.value)
})

// 威胁分类数据
const threatCategories = ref([
  {
    name: 'DDoS攻击',
    value: 456,
    percent: 45,
    icon: IconThunderbolt,
    color: '#F53F3F',
    bgColor: 'rgba(245, 63, 63, 0.1)',
    progressStatus: 'danger' as const,
  },
  {
    name: '暴力破解',
    value: 234,
    percent: 30,
    icon: IconLock,
    color: '#FF7D00',
    bgColor: 'rgba(255, 125, 0, 0.1)',
    progressStatus: 'warning' as const,
  },
  {
    name: 'SQL注入',
    value: 189,
    percent: 25,
    icon: IconCode,
    color: '#165DFF',
    bgColor: 'rgba(22, 93, 255, 0.1)',
    progressStatus: 'normal' as const,
  },
  {
    name: 'XSS攻击',
    value: 156,
    percent: 20,
    icon: IconCode,
    color: '#14C9C9',
    bgColor: 'rgba(20, 201, 201, 0.1)',
    progressStatus: 'normal' as const,
  },
])

// 威胁趋势图表配置
const threatChartOptions = ref({
  tooltip: {
    trigger: 'axis',
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
  },
  yAxis: {
    type: 'value',
    name: '数量',
  },
  series: [
    {
      name: '检测',
      type: 'line',
      smooth: true,
      data: [45, 32, 89, 156, 123, 78, 56],
      areaStyle: {
        opacity: 0.1,
      },
      lineStyle: {
        width: 2,
        color: '#165DFF',
      },
      itemStyle: {
        color: '#165DFF',
      },
    },
    {
      name: '拦截',
      type: 'line',
      smooth: true,
      data: [12, 8, 25, 45, 38, 22, 15],
      areaStyle: {
        opacity: 0.1,
      },
      lineStyle: {
        width: 2,
        color: '#14C9C9',
      },
      itemStyle: {
        color: '#14C9C9',
      },
    },
  ],
})

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'gray',
    warning: 'orange',
    error: 'red',
    unknown: 'gray',
  }
  return colorMap[status] || 'gray'
}

/** 获取状态文本 */
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    warning: '警告',
    error: '异常',
    unknown: '未知',
  }
  return textMap[status] || '未知'
}

/** 格式化运行时长 */
const formatUptime = (uptime: number) => {
  if (!uptime || uptime === 0) return '-'
  const days = Math.floor(uptime / 86400)
  const hours = Math.floor((uptime % 86400) / 3600)
  const minutes = Math.floor((uptime % 3600) / 60)
  if (days > 0) return `${days}天 ${hours}小时`
  if (hours > 0) return `${hours}小时 ${minutes}分钟`
  return `${minutes}分钟`
}

/** 格式化时间 */
const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

/** 获取数据 */
const fetchData = async () => {
  loading.value = true
  try {
    const response = await fetchSecurityServiceList()
    if (response && response.code === 0 && response.details) {
      deviceData.value = response.details.data || []
    }
  } catch (error) {
    console.error('获取安全设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

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

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

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

.stats-row {
  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));
    }

    &-danger {
      background-color: rgba(245, 63, 63, 0.1);
      color: rgb(var(--danger-6));
    }

    &-muted {
      background-color: rgba(134, 144, 156, 0.1);
      color: rgb(var(--gray-6));
    }
  }

  .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: 280px;
}

.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;
  }
}

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

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

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

.threat-category-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 280px;
}

.threat-category-item {
  .threat-category-header {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .threat-category-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
  }

  .threat-category-info {
    flex: 1;
  }

  .threat-category-name {
    font-size: 14px;
    color: var(--color-text-1);
    margin-bottom: 4px;
  }

  .threat-category-value {
    font-size: 14px;
    font-weight: 500;
    min-width: 40px;
    text-align: right;
  }
}

.threats-value {
  font-weight: 500;

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

  &.warning {
    color: rgb(var(--warning-6));
  }

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

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

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