<template>
  <a-drawer
    :visible="visible"
    title="存储设备采集详情"
    placement="right"
    width="860px"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
  >
    <div class="detail-container">
      <a-spin :loading="loading" style="width: 100%">
        <a-descriptions title="基础信息" :column="2" bordered>
          <a-descriptions-item label="ID">{{ detailData?.id }}</a-descriptions-item>
          <a-descriptions-item label="服务标识">{{ detailData?.service_identity }}</a-descriptions-item>
          <a-descriptions-item label="名称">{{ detailData?.name }}</a-descriptions-item>
          <a-descriptions-item label="类型">{{ detailData?.type }}</a-descriptions-item>
          <a-descriptions-item label="分类">{{ detailData?.category || '-' }}</a-descriptions-item>
          <a-descriptions-item label="OID">{{ detailData?.oid || '-' }}</a-descriptions-item>
          <a-descriptions-item label="服务器标识">{{ detailData?.server_identity || '-' }}</a-descriptions-item>
          <a-descriptions-item label="标签">{{ detailData?.tags || '-' }}</a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">{{ detailData?.description || '-' }}</a-descriptions-item>
        </a-descriptions>

        <a-descriptions title="采集配置" :column="2" bordered style="margin-top: 20px">
          <a-descriptions-item label="采集方式">
            <a-tag :color="detailData?.collect_method === 'snmp' ? 'purple' : 'arcoblue'">
              {{ detailData?.collect_method === 'snmp' ? 'SNMP' : 'API' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="连接配置">
            <span v-if="detailData?.collect_method === 'snmp'">{{ detailData?.snmp_target || '-' }}</span>
            <span v-else>{{ detailData?.agent_config || '-' }}</span>
          </a-descriptions-item>
          <a-descriptions-item v-if="detailData?.collect_method === 'snmp'" label="SNMP连接">
            {{ (detailData?.snmp_community || '-') + ' @ ' + (detailData?.snmp_port || 161) }}
          </a-descriptions-item>
          <a-descriptions-item v-if="detailData?.collect_method === 'snmp'" label="SNMP超时/重试">
            {{ (detailData?.snmp_timeout_ms || 3000) + 'ms / ' + (detailData?.snmp_retries ?? 1) }}
          </a-descriptions-item>
          <a-descriptions-item label="启用采集">
            <a-tag :color="detailData?.collect_on ? 'green' : 'gray'">
              {{ detailData?.collect_on ? '已启用' : '未启用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="采集间隔">
            {{ detailData?.collect_interval ? `${detailData?.collect_interval}秒` : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="采集参数">{{ detailData?.collect_args || '-' }}</a-descriptions-item>
          <a-descriptions-item label="采集结果" :span="2">{{ detailData?.collect_last_result || '-' }}</a-descriptions-item>
        </a-descriptions>

        <a-descriptions title="运行状态" :column="2" bordered style="margin-top: 20px">
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(detailData?.status)">
              {{ getStatusText(detailData?.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="状态码">{{ detailData?.status_code || '-' }}</a-descriptions-item>
          <a-descriptions-item label="状态消息" :span="2">{{ detailData?.status_message || '-' }}</a-descriptions-item>
          <a-descriptions-item label="响应时间">
            {{ detailData?.response_time ? `${detailData?.response_time}ms` : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="最后检查时间">{{ formatDateTime(detailData?.last_check_time) }}</a-descriptions-item>
          <a-descriptions-item label="最后在线时间">{{ formatDateTime(detailData?.last_online_time) }}</a-descriptions-item>
          <a-descriptions-item label="最后离线时间">{{ formatDateTime(detailData?.last_offline_time) }}</a-descriptions-item>
          <a-descriptions-item label="连续错误次数">{{ detailData?.continuous_errors || 0 }}</a-descriptions-item>
          <a-descriptions-item label="运行时长">{{ detailData?.uptime ? `${detailData?.uptime}秒` : '-' }}</a-descriptions-item>
        </a-descriptions>

        <div class="action-bar">
          <a-space>
            <a-button type="outline" @click="handleViewMetrics">查看最新指标</a-button>
            <a-button type="primary" @click="$emit('edit')">编辑</a-button>
            <a-button type="outline" status="danger" @click="$emit('delete')">删除</a-button>
          </a-space>
        </div>
      </a-spin>
    </div>

    <a-drawer v-model:visible="metricsVisible" :width="860" title="最新指标数据" :footer="false" unmount-on-close>
      <a-spin :loading="loading" style="width: 100%">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="数据时间">{{ formatDateTime(metricsData?.latest_timestamp) }}</a-descriptions-item>
          <a-descriptions-item label="指标数量">{{ metricsData?.count || 0 }}</a-descriptions-item>
        </a-descriptions>
        <div v-if="metricsData?.metrics?.length" class="metrics-grid">
          <div v-for="metric in metricsData?.metrics" :key="metric.metric_name" class="metric-item">
            <div class="metric-name">{{ metric.metric_name }}</div>
            <div class="metric-value">{{ metric.metric_value }} {{ metric.metric_unit }}</div>
          </div>
        </div>
        <a-empty v-else-if="!loading" description="暂无指标数据" style="margin-top: 20px" />
      </a-spin>
    </a-drawer>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchStorageDetail, fetchStorageMetricsLatest } from '@/api/ops/storage'
import type { StorageItem, StorageMetricsLatestResponse } from '@/api/ops/storage'

interface Props {
  visible: boolean
  record?: StorageItem | null
}

const props = withDefaults(defineProps<Props>(), {
  record: null,
})

const emit = defineEmits(['update:visible', 'edit', 'delete'])

const loading = ref(false)
const detailData = ref<StorageItem | null>(null)
const metricsData = ref<StorageMetricsLatestResponse | null>(null)
const metricsVisible = ref(false)

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

const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    error: '异常',
    unknown: '未知',
  }
  return textMap[status || ''] || '-'
}

const formatDateTime = (dateTime: string | null | undefined) => {
  if (!dateTime || dateTime === '0001-01-01T00:00:00Z') {
    return '-'
  }
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      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}`
  } catch {
    return '-'
  }
}

const fetchDetail = async () => {
  if (!props.record?.id) return

  loading.value = true
  try {
    const res: any = await fetchStorageDetail(props.record.id)
    if (res.code === 0) {
      detailData.value = res.details

      if (detailData.value?.service_identity) {
        const metricsRes: any = await fetchStorageMetricsLatest(detailData.value.service_identity)
        if (metricsRes.code === 0) {
          metricsData.value = metricsRes.details
        }
      }
    } else {
      Message.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    Message.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

watch(
  () => props.visible,
  (val) => {
    if (val && props.record) {
      fetchDetail()
    } else {
      detailData.value = null
      metricsData.value = null
    }
  }
)

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleViewMetrics = () => {
  metricsVisible.value = true
}
</script>

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

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

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

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

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

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