<template>
  <div class="detail-container">
    <a-descriptions title="基础信息" :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="设备分类">
        {{ DEVICE_CATEGORY_MAP[record.device_category] || record.device_category }}
      </a-descriptions-item>
      <a-descriptions-item label="机房ID">{{ record.room_id }}</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-descriptions title="采集配置" :column="2" bordered class="section-block">
      <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="采集地址/目标" :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.enabled ? 'green' : 'gray'">
          {{ record.enabled ? '已启用' : '已禁用' }}
        </a-tag>
      </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="采集间隔">{{ record.collect_interval }}秒</a-descriptions-item>
    </a-descriptions>

    <a-descriptions title="运行状态" :column="2" bordered class="section-block">
      <a-descriptions-item label="采集结果摘要" :span="2">{{ record.collect_last_result || '-' }}</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-eye /></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="860" title="最新指标数据" :footer="false" unmount-on-close>
      <a-spin :loading="metricsLoading" style="width: 100%">
        <a-descriptions :column="2" bordered style="margin-bottom: 12px">
          <a-descriptions-item label="数据时间">{{ formatTime(metricsLatestTimestamp) }}</a-descriptions-item>
          <a-descriptions-item label="指标数量">{{ metricsCount }}</a-descriptions-item>
        </a-descriptions>
        <div v-if="metricsData.length > 0">
          <div class="metrics-grid">
            <div v-for="(item, index) in metricsData" :key="index" class="metric-item">
              <div class="metric-name">{{ item.metric_name }}</div>
              <div class="metric-value">{{ item.metric_value }} {{ item.metric_unit || '' }}</div>
              <div class="metric-meta">
                <span>类型: {{ item.type || '-' }}</span>
                <span>时间: {{ formatTime(item.timestamp) }}</span>
              </div>
            </div>
          </div>
        </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, IconEye } from '@arco-design/web-vue/es/icon'
import { DEVICE_CATEGORY_MAP, fetchLatestMetrics, type RoomDeviceItem, type MetricItem } from '@/api/ops/room-device'

interface Props {
  record: RoomDeviceItem
}

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

const metricsVisible = ref(false)
const metricsLoading = ref(false)
const metricsData = ref<MetricItem[]>([])
const metricsLatestTimestamp = ref<string | undefined>('')
const metricsCount = ref(0)

const handleViewMetrics = async () => {
  metricsVisible.value = true
  metricsLoading.value = true
  try {
    const response = await fetchLatestMetrics(props.record.service_identity)
    metricsLatestTimestamp.value = response?.details?.latest_timestamp || ''
    metricsCount.value = response?.details?.count || 0
    const metrics =
      response?.code === 0 && response.details?.metrics && Array.isArray(response.details.metrics) ? response.details.metrics : []
    metricsData.value = metrics
  } catch (error) {
    console.error('获取最新指标失败:', error)
    Message.error('获取最新指标失败')
    metricsData.value = []
    metricsLatestTimestamp.value = ''
    metricsCount.value = 0
  } finally {
    metricsLoading.value = false
  }
}

const formatTime = (time?: string) => {
  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}`
}
</script>

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

.section-block {
  margin-top: 16px;
}

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

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.metric-item {
  border: 1px solid var(--color-neutral-3);
  border-radius: 4px;
  background: var(--color-fill-1);
  padding: 10px 12px;
}

.metric-name {
  color: var(--color-text-2);
  font-size: 12px;
  margin-bottom: 6px;
  word-break: break-all;
}

.metric-value {
  color: var(--color-text-1);
  font-size: 14px;
  line-height: 20px;
  word-break: break-all;
}

.metric-meta {
  margin-top: 6px;
  color: var(--color-text-3);
  font-size: 12px;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

@media (max-width: 1024px) {
  .metrics-grid {
    grid-template-columns: 1fr;
  }
}
</style>
