<template>
  <div class="detail-container">
    <a-divider orientation="left">基础信息</a-divider>
    <a-descriptions :column="2" bordered>
      <a-descriptions-item label="ID">{{ record.id }}</a-descriptions-item>
      <a-descriptions-item label="服务标识">{{ record.service_identity }}</a-descriptions-item>
      <a-descriptions-item label="服务名称">{{ record.name }}</a-descriptions-item>
      <a-descriptions-item label="设备类型">
        {{ SECURITY_TYPE_MAP[record.type] || record.type }}
      </a-descriptions-item>
      <a-descriptions-item label="OID">{{ record.oid || '-' }}</a-descriptions-item>
      <a-descriptions-item label="服务器标识">{{ record.server_identity || '-' }}</a-descriptions-item>
      <a-descriptions-item label="描述信息" :span="2">{{ record.description || '-' }}</a-descriptions-item>
      <a-descriptions-item label="创建时间">{{ formatTime(record.created_at) }}</a-descriptions-item>
      <a-descriptions-item label="更新时间">{{ formatTime(record.updated_at) }}</a-descriptions-item>
    </a-descriptions>

    <a-divider orientation="left">采集配置</a-divider>
    <a-descriptions :column="2" bordered>
      <a-descriptions-item label="采集方式">
        <a-tag :color="record.collect_method === 'snmp' ? 'purple' : 'arcoblue'">
          {{ record.collect_method === 'snmp' ? 'SNMP' : 'API' }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="采集间隔">{{ record.collect_interval }}秒</a-descriptions-item>
      <a-descriptions-item label="采集地址" :span="2">
        <a-link v-if="record.collect_method !== 'snmp' && record.agent_config" :href="record.agent_config" target="_blank">
          {{ record.agent_config }}
        </a-link>
        <span v-else-if="record.collect_method === 'snmp'">{{ record.snmp_target || '-' }}</span>
        <span v-else>-</span>
      </a-descriptions-item>
      <a-descriptions-item v-if="record.collect_method === 'snmp'" label="SNMP连接">
        {{ (record.snmp_community || '-') + ' @ ' + (record.snmp_port || 161) }}
      </a-descriptions-item>
      <a-descriptions-item v-if="record.collect_method === 'snmp'" label="SNMP超时/重试">
        {{ (record.snmp_timeout_ms || 3000) + 'ms / ' + (record.snmp_retries ?? 1) }}
      </a-descriptions-item>
      <a-descriptions-item label="启用周期采集">
        <a-tag :color="record.collect_on ? 'green' : 'gray'">
          {{ record.collect_on ? '已启用' : '未启用' }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="采集参数" :span="2">{{ record.collect_args || '-' }}</a-descriptions-item>
      <a-descriptions-item label="采集结果" :span="2">{{ record.collect_last_result || '-' }}</a-descriptions-item>
    </a-descriptions>

    <a-divider orientation="left">运行状态</a-divider>
    <a-descriptions :column="2" bordered>
      <a-descriptions-item label="运行状态">
        <a-tag :color="getStatusColor(record.status)">
          {{ STATUS_MAP[record.status] || record.status }}
        </a-tag>
      </a-descriptions-item>
      <a-descriptions-item label="状态码">{{ record.status_code || '-' }}</a-descriptions-item>
      <a-descriptions-item label="状态信息" :span="2">{{ record.status_message || '-' }}</a-descriptions-item>
      <a-descriptions-item label="响应时间">
        {{ record.response_time ? `${record.response_time.toFixed(2)} ms` : '-' }}
      </a-descriptions-item>
      <a-descriptions-item label="连续错误">
        <a-tag v-if="record.continuous_errors > 0" color="red">{{ record.continuous_errors }}</a-tag>
        <span v-else>0</span>
      </a-descriptions-item>
      <a-descriptions-item label="最近检查">{{ formatTime(record.last_check_time) }}</a-descriptions-item>
      <a-descriptions-item label="运行时长">{{ formatUptime(record.uptime) }}</a-descriptions-item>
      <a-descriptions-item label="最近在线">{{ formatTime(record.last_online_time) }}</a-descriptions-item>
      <a-descriptions-item label="最近离线">{{ formatTime(record.last_offline_time) }}</a-descriptions-item>
    </a-descriptions>

    <div class="action-bar">
      <a-space>
        <a-button type="primary" @click="$emit('edit')">
          <template #icon><icon-edit /></template>
          编辑
        </a-button>
        <a-button type="outline" @click="$emit('quick-config')">
          <template #icon><icon-settings /></template>
          采集配置
        </a-button>
        <a-button type="outline" @click="handleViewMetrics">
          <template #icon><icon-dashboard /></template>
          查看最新指标
        </a-button>
        <a-button type="outline" status="danger" @click="$emit('delete')">
          <template #icon><icon-delete /></template>
          删除
        </a-button>
      </a-space>
    </div>

    <a-drawer v-model:visible="metricsVisible" :width="800" title="最新指标数据" :footer="false" unmount-on-close>
      <a-spin :loading="metricsLoading" style="width: 100%">
        <div v-if="metricsData && metricsData.metrics && metricsData.metrics.length > 0">
          <a-alert type="info" style="margin-bottom: 16px">
            <template #message>
              <div>最新采集时间: {{ formatTime(metricsData.latest_timestamp) || '-' }}</div>
              <div>指标数量: {{ metricsData.count }}</div>
            </template>
          </a-alert>
          <a-row :gutter="16">
            <a-col v-for="(item, index) in metricsData.metrics" :key="index" :span="8">
              <a-card class="metric-card" :bordered="false">
                <div class="metric-name">{{ item.metric_name }}</div>
                <div class="metric-value">{{ item.metric_value }} {{ item.metric_unit || '' }}</div>
              </a-card>
            </a-col>
          </a-row>
        </div>
        <a-empty v-else description="暂无指标数据" />
      </a-spin>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconEdit, IconDelete, IconSettings, IconDashboard } from '@arco-design/web-vue/es/icon'
import {
  SECURITY_TYPE_MAP,
  STATUS_MAP,
  fetchSecurityMetricsLatest,
  type SecurityServiceItem,
  type SecurityMetricsLatestData,
} from '@/api/ops/security'

interface Props {
  record: SecurityServiceItem
}

const props = defineProps<Props>()
defineEmits(['edit', 'quick-config', 'delete'])

const metricsVisible = ref(false)
const metricsLoading = ref(false)
const metricsData = ref<SecurityMetricsLatestData | null>(null)

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    online: 'green',
    offline: 'gray',
    error: 'red',
    unknown: 'gray',
  }
  return colorMap[status] || 'gray'
}

const handleViewMetrics = async () => {
  metricsVisible.value = true
  metricsLoading.value = true
  try {
    const response: any = await fetchSecurityMetricsLatest(props.record.service_identity)
    metricsData.value = response?.details || null
  } catch (error) {
    console.error('获取最新指标失败:', error)
    Message.error('获取最新指标失败')
    metricsData.value = null
  } finally {
    metricsLoading.value = false
  }
}

const formatTime = (time?: string | null) => {
  if (!time) return '-'
  if (time.startsWith('0001-01-01')) return '-'
  const date = new Date(time)
  if (Number.isNaN(date.getTime())) return '-'
  if (date.getFullYear() <= 1970) return '-'
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

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}分钟`
}
</script>

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

.action-bar {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
}

.metric-card {
  margin-bottom: 16px;

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

  .metric-name {
    font-size: 14px;
    color: var(--color-text-3);
    margin-bottom: 8px;
  }

  .metric-value {
    font-size: 24px;
    font-weight: 600;
    color: var(--color-text-1);
  }
}
</style>
