<template>
  <a-drawer
    :visible="visible"
    title="数据库采集详情"
    placement="right"
    :width="860"
    :footer="false"
    unmount-on-close
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
  >
    <a-spin :loading="loading" style="width: 100%">
      <div v-if="detailData" class="database-detail">
        <div class="detail-header-card">
          <div class="header-left">
            <div class="service-icon">{{ getTypeAbbr(detailData.type) }}</div>
            <div class="service-info">
              <div class="service-title">
                <h2>{{ detailData.name || '数据库服务' }}</h2>
                <div class="status-tags">
                  <a-tag :color="getStatusColor(detailData.status)" size="large">{{ getStatusText(detailData.status) }}</a-tag>
                  <a-tag :color="detailData.enabled ? 'green' : 'gray'" size="large">{{ detailData.enabled ? '已启用' : '已禁用' }}</a-tag>
                </div>
              </div>
              <div class="service-meta">
                <span class="meta-item">标识: {{ detailData.service_identity || '-' }}</span>
                <span class="meta-item">
                  类型:
                  <a-tag :color="getTypeColor(detailData.type)" size="small">{{ detailData.type || '-' }}</a-tag>
                </span>
                <span class="meta-item">地址: {{ detailData.host || '-' }}:{{ detailData.port || '-' }}</span>
              </div>
            </div>
          </div>
          <div class="header-actions">
            <a-button size="small" @click="emit('edit', detailData)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-button size="small" @click="emit('collect', detailData)">
              <template #icon><icon-sync /></template>
              触发采集
            </a-button>
            <a-button size="small" status="danger" @click="emit('delete', detailData)">
              <template #icon><icon-delete /></template>
              删除
            </a-button>
          </div>
        </div>

        <div class="metrics-grid">
          <div class="metric-card">
            <div class="metric-title">响应时间</div>
            <div class="metric-value">
              {{ detailData.response_time ? detailData.response_time.toFixed(2) : '-' }}
              <span class="unit">ms</span>
            </div>
            <div class="metric-footer">最后检查: {{ formatTime(detailData.last_check_time) }}</div>
          </div>
          <div class="metric-card">
            <div class="metric-title">状态码</div>
            <div class="metric-value">{{ formatStatusCode(detailData.status_code) }}</div>
            <div class="metric-footer">{{ detailData.status_message || '-' }}</div>
          </div>
          <div class="metric-card">
            <div class="metric-title">连续错误</div>
            <div class="metric-value">
              {{ detailData.continuous_errors ?? 0 }}
              <span class="unit">次</span>
            </div>
            <div class="metric-footer">运行时长: {{ formatUptime(detailData.uptime) }}</div>
          </div>
          <div class="metric-card">
            <div class="metric-title">采集状态</div>
            <div class="metric-value">{{ detailData.collect_on ? '运行中' : '已停用' }}</div>
            <div class="metric-footer">间隔: {{ detailData.collect_interval || detailData.interval || 60 }} 秒</div>
          </div>
        </div>

        <a-tabs v-model:active-tab="activeTab" class="detail-tabs">
          <a-tab-pane key="basic" title="基本信息">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="服务ID">{{ detailData.id }}</a-descriptions-item>
              <a-descriptions-item label="服务名称">{{ detailData.name || '-' }}</a-descriptions-item>
              <a-descriptions-item label="数据库">{{ detailData.database || '-' }}</a-descriptions-item>
              <a-descriptions-item label="用户名">{{ detailData.username || '-' }}</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="标签" :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>
          </a-tab-pane>

          <a-tab-pane key="collect" title="采集配置">
            <a-descriptions :column="2" bordered>
              <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">{{ detailData.collect_args || '-' }}</a-descriptions-item>
              <a-descriptions-item label="最近采集结果" :span="2">{{ detailData.collect_last_result || '-' }}</a-descriptions-item>
              <a-descriptions-item label="额外配置" :span="2">
                <pre class="json-display">{{ formatJson(detailData.extra) || '-' }}</pre>
              </a-descriptions-item>
            </a-descriptions>
          </a-tab-pane>

          <a-tab-pane key="status" title="运行状态">
            <a-descriptions :column="2" bordered>
              <a-descriptions-item label="运行状态">
                <a-tag :color="getStatusColor(detailData.status)">{{ getStatusText(detailData.status) }}</a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="状态码">{{ formatStatusCode(detailData.status_code) }}</a-descriptions-item>
              <a-descriptions-item label="状态消息" :span="2">{{ detailData.status_message || '-' }}</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>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-spin>
  </a-drawer>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconEdit, IconDelete, IconSync } from '@arco-design/web-vue/es/icon'
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', 'edit', 'delete', 'collect'])

const loading = ref(false)
const detailData = ref<DatabaseService | null>(null)
const activeTab = ref('basic')

watch(
  () => props.visible,
  (val) => {
    if (val && props.recordId) {
      fetchDetail()
      activeTab.value = 'basic'
    }
  }
)

const fetchDetail = async () => {
  loading.value = true
  try {
    const res: any = await fetchDatabaseDetail(props.recordId)
    detailData.value = res?.details || null
  } 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 getTypeAbbr = (type?: string) => {
  const abbrMap: Record<string, string> = {
    MySQL: 'MY',
    PostgreSQL: 'PG',
    Redis: 'RD',
    MongoDB: 'MG',
    DM: 'DM',
    KingBase: 'KB',
  }
  return abbrMap[type || ''] || 'DB'
}

// 获取状态颜色
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 formatStatusCode = (code?: number | null) => {
  if (code === null || code === undefined) return '-'
  return code
}

// 格式化运行时长
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 '-'
  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 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">
.database-detail {
  padding: 16px;
  background: #f7f8fa;
}

.detail-header-card {
  background: #fff;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-icon {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  background: linear-gradient(135deg, #165dff, #4080ff);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
}

.service-title {
  display: flex;
  align-items: center;
  gap: 12px;

  h2 {
    margin: 0;
    font-size: 16px;
  }
}

.status-tags {
  display: flex;
  gap: 8px;
}

.service-meta {
  margin-top: 8px;
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  color: #86909c;
  font-size: 13px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

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

.metric-card {
  background: #fff;
  border-radius: 6px;
  padding: 12px;
}

.metric-title {
  font-size: 12px;
  color: #86909c;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 22px;
  font-weight: 600;
  color: #1d2129;
}

.unit {
  font-size: 12px;
  color: #86909c;
  margin-left: 4px;
}

.metric-footer {
  margin-top: 8px;
  color: #86909c;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-tabs {
  background: #fff;
  border-radius: 6px;
  padding: 16px;
}

.json-display {
  margin: 0;
  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>
