<template>
  <a-drawer
    :visible="visible"
    title="存储设备详情"
    placement="right"
    width="600px"
    @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="Agent配置">{{ detailData?.agent_config || '-' }}</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>

        <a-descriptions title="最新指标" :column="2" bordered style="margin-top: 20px" v-if="metricsData?.metrics?.length">
          <a-descriptions-item label="数据时间">{{ formatDateTime(metricsData?.latest_timestamp) }}</a-descriptions-item>
          <a-descriptions-item label="指标数量">{{ metricsData?.count || 0 }}</a-descriptions-item>
          <a-descriptions-item v-for="metric in metricsData?.metrics" :key="metric.metric_name" :label="metric.metric_name">
            {{ metric.metric_value }} {{ metric.metric_unit }}
          </a-descriptions-item>
        </a-descriptions>
        <a-empty v-else-if="!loading && !metricsData?.metrics?.length" description="暂无指标数据" style="margin-top: 20px" />
      </a-spin>
    </div>
  </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'])

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

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)
}
</script>

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