<template>
  <a-modal
    :visible="visible"
    title="数据库服务详情"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :footer="false"
    width="700px"
  >
    <a-spin :loading="loading" style="width: 100%">
      <a-descriptions
        :column="2"
        bordered
        size="medium"
        :label-style="{ width: '140px' }"
      >
        <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="数据库类型">
          <a-tag :color="getTypeColor(detailData?.type)">
            {{ detailData?.type || '-' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="主机地址">
          {{ detailData?.host || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="端口">
          {{ detailData?.port || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="用户名">
          {{ detailData?.username || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="数据库名">
          {{ detailData?.database || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="服务器标识">
          {{ detailData?.server_identity || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="分类">
          {{ detailData?.category || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="启用监控">
          <a-tag :color="detailData?.enabled ? 'green' : 'red'">
            {{ detailData?.enabled ? '已启用' : '已禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="采集间隔">
          {{ detailData?.interval ? `${detailData.interval}秒` : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="进程内采集">
          <a-tag :color="detailData?.collect_on ? 'green' : 'red'">
            {{ 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="运行状态" :span="2">
          <a-tag :color="getStatusColor(detailData?.status)">
            {{ getStatusText(detailData?.status) }}
          </a-tag>
          <span v-if="detailData?.status_message" style="margin-left: 8px; color: rgb(var(--text-3))">
            {{ detailData.status_message }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="状态码">
          {{ detailData?.status_code || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="响应时间">
          {{ detailData?.response_time ? `${detailData.response_time.toFixed(2)}ms` : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="连续错误次数">
          <span :style="{ color: (detailData?.continuous_errors ?? 0) > 0 ? 'rgb(var(--danger-6))' : '' }">
            {{ detailData?.continuous_errors ?? 0 }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="运行时长">
          {{ formatUptime(detailData?.uptime) }}
        </a-descriptions-item>
        <a-descriptions-item label="最后检查时间">
          {{ formatTime(detailData?.last_check_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="最后在线时间">
          {{ formatTime(detailData?.last_online_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="最后离线时间">
          {{ formatTime(detailData?.last_offline_time) }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ formatTime(detailData?.created_at) }}
        </a-descriptions-item>
        <a-descriptions-item label="更新时间">
          {{ formatTime(detailData?.updated_at) }}
        </a-descriptions-item>
        <a-descriptions-item label="标签" :span="2">
          <a-tag v-for="(tag, index) in parseTags(detailData?.tags)" :key="index" style="margin-right: 4px">
            {{ tag }}
          </a-tag>
          <span v-if="!parseTags(detailData?.tags).length">-</span>
        </a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">
          {{ detailData?.description || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="采集参数" :span="2">
          {{ detailData?.collect_args || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="最近采集结果" :span="2">
          <div v-if="detailData?.collect_last_result" class="collect-result">
            {{ detailData.collect_last_result }}
          </div>
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="额外配置" :span="2">
          <div v-if="detailData?.extra" class="extra-config">
            <a-button size="small" @click="showExtraConfig = !showExtraConfig">
              {{ showExtraConfig ? '隐藏' : '展开' }} JSON
            </a-button>
            <pre v-if="showExtraConfig" class="json-display">{{ formatJson(detailData?.extra) }}</pre>
          </div>
          <span v-else>-</span>
        </a-descriptions-item>
      </a-descriptions>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchDatabaseDetail, type DatabaseService } from '@/api/ops/database'

interface Props {
  visible: boolean
  recordId?: number
}

const props = withDefaults(defineProps<Props>(), {
  recordId: 0,
})

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

const loading = ref(false)
const detailData = ref<DatabaseService | null>(null)
const showExtraConfig = ref(false)

watch(
  () => props.visible,
  (val) => {
    if (val && props.recordId) {
      fetchDetail()
      showExtraConfig.value = false
    }
  }
)

const fetchDetail = async () => {
  loading.value = true
  try {
    const res = await fetchDatabaseDetail(props.recordId)
    detailData.value = res
  } catch (error) {
    console.error('获取详情失败:', error)
    Message.error('获取详情失败')
    detailData.value = null
  } finally {
    loading.value = false
  }
}

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

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

// 获取数据库类型颜色
const getTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    MySQL: 'blue',
    PostgreSQL: 'purple',
    Redis: 'red',
    MongoDB: 'green',
    DM: 'orange',
    KingBase: 'cyan',
  }
  return colorMap[type || ''] || 'gray'
}

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

// 获取状态文本
const getStatusText = (status?: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    error: '错误',
  }
  return textMap[status || ''] || '-'
}

// 格式化运行时长
const formatUptime = (uptime?: number) => {
  if (!uptime) 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}小时 ${minutes}分钟`
  }
  if (hours > 0) {
    return `${hours}小时 ${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 格式化时间
const formatTime = (time?: string | null) => {
  if (!time) return '-'
  const date = new Date(time)
  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 parseTags = (tags?: string) => {
  if (!tags) return []
  return tags.split(',').filter((t) => t.trim())
}

// 格式化JSON
const formatJson = (json?: string) => {
  if (!json) return ''
  try {
    return JSON.stringify(JSON.parse(json), null, 2)
  } catch {
    return json
  }
}
</script>

<style scoped lang="less">
.collect-result {
  max-height: 100px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.extra-config {
  .json-display {
    margin-top: 8px;
    padding: 8px;
    background: rgb(var(--gray-2));
    border-radius: 4px;
    max-height: 200px;
    overflow-y: auto;
    font-size: 12px;
    white-space: pre-wrap;
    word-break: break-all;
  }
}
</style>