<template>
  <a-modal :visible="visible" title="告警详情" :footer="false" width="1000px" @cancel="handleCancel" @update:visible="handleCancel">
    <a-spin :loading="loading">
      <div v-if="record" class="alert-detail">
        <!-- 基础信息 -->
        <a-descriptions title="基础信息" :column="2" bordered>
          <a-descriptions-item label="告警ID">{{ record.id }}</a-descriptions-item>
          <a-descriptions-item label="告警名称">{{ record.alert_name }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="告警级别">
            <a-tag v-if="record.severity" :color="record.severity.color">
              {{ record.severity.name || record.severity.code }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="策略ID">{{ record.policy_id }}</a-descriptions-item>
          <a-descriptions-item label="规则ID">{{ record.rule_id }}</a-descriptions-item>
        </a-descriptions>

        <!-- 告警内容 -->
        <a-descriptions title="告警内容" :column="1" bordered class="mt-4">
          <a-descriptions-item label="摘要">
            {{ record.summary || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="描述">
            {{ record.description || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="当前值">
            {{ record.value || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="阈值">
            {{ record.threshold || '-' }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 时间信息 -->
        <a-descriptions title="时间信息" :column="2" bordered class="mt-4">
          <a-descriptions-item label="开始时间">
            {{ formatDateTime(record.starts_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="结束时间">
            {{ record.ends_at ? formatDateTime(record.ends_at) : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="持续时长">
            {{ formatDuration(record.duration) }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(record.created_at) }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 处理信息 -->
        <a-descriptions title="处理信息" :column="2" bordered class="mt-4">
          <a-descriptions-item label="处理人">
            {{ record.processed_by || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="处理时间">
            {{ record.processed_at ? formatDateTime(record.processed_at) : '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="关联工单">
            {{ record.feedback_ticket_id || '-' }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 通知信息 -->
        <a-descriptions title="通知信息" :column="2" bordered class="mt-4">
          <a-descriptions-item label="通知次数">
            {{ record.notify_count || 0 }}
          </a-descriptions-item>
          <a-descriptions-item label="通知状态">
            <a-tag :color="getNotifyStatusColor(record.notify_status)">
              {{ getNotifyStatusText(record.notify_status) }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 标签 -->
        <a-descriptions title="标签" :column="1" bordered class="mt-4">
          <a-descriptions-item label="Labels">
            <div v-if="labels">
              <a-tag v-for="(value, key) in labels" :key="key" class="mb-1">{{ key }}: {{ value }}</a-tag>
            </div>
            <span v-else>-</span>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 注解 -->
        <a-descriptions title="注解" :column="1" bordered class="mt-4">
          <a-descriptions-item label="Annotations">
            <div v-if="annotations">
              <a-tag v-for="(value, key) in annotations" :key="key" class="mb-1">{{ key }}: {{ value }}</a-tag>
            </div>
            <span v-else>-</span>
          </a-descriptions-item>
        </a-descriptions>

        <!-- 处理记录 -->
        <div class="mt-6">
          <div class="mb-2 font-bold">处理记录</div>
          <a-table :data="processRecords" :columns="processColumns" :pagination="false" size="medium">
            <template #action="{ record }">
              <a-tag :color="getActionColor(record.action)">
                {{ getActionText(record.action) }}
              </a-tag>
            </template>
          </a-table>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchAlertRecordDetail, fetchAlertProcessList } from '@/api/ops/alertRecord'

interface Props {
  visible: boolean
  alertRecordId: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
}>()

const loading = ref(false)
const record = ref<any>(null)
const processRecords = ref<any[]>([])

const labels = computed(() => {
  if (!record.value?.labels) return null
  try {
    return JSON.parse(record.value.labels)
  } catch {
    return null
  }
})

const annotations = computed(() => {
  if (!record.value?.annotations) return null
  try {
    return JSON.parse(record.value.annotations)
  } catch {
    return null
  }
})

const processColumns = [
  { title: '时间', dataIndex: 'created_at', slotName: 'created_at', width: 180 },
  { title: '操作', dataIndex: 'action', slotName: 'action', width: 100 },
  { title: '操作人', dataIndex: 'operator', width: 120 },
  { title: '备注', dataIndex: 'comment', ellipsis: true, tooltip: true },
]

watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadDetail()
      loadProcessRecords()
    }
  }
)

const loadDetail = async () => {
  loading.value = true
  try {
    const data = await fetchAlertRecordDetail(props.alertRecordId)
    record.value = data.details
  } catch (error) {
    console.error('加载详情失败:', error)
    Message.error('加载详情失败')
  } finally {
    loading.value = false
  }
}

const loadProcessRecords = async () => {
  try {
    const result = await fetchAlertProcessList({
      alert_record_id: props.alertRecordId,
      page: 1,
      page_size: 100,
    })
    processRecords.value = result.details.data || []
  } catch (error) {
    console.error('加载处理记录失败:', error)
  }
}

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

// 格式化函数
const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

const formatDuration = (seconds: number) => {
  if (!seconds) return '-'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

// 状态相关
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    firing: 'red',
    pending: 'orange',
    acked: 'gold',
    resolved: 'green',
    silenced: 'gray',
    suppressed: 'lightgray',
  }
  return colorMap[status] || 'blue'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    firing: '告警中',
    pending: '待处理',
    acked: '已确认',
    resolved: '已解决',
    silenced: '已屏蔽',
    suppressed: '已抑制',
  }
  return textMap[status] || status
}

const getNotifyStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    success: 'green',
    failed: 'red',
    pending: 'orange',
  }
  return colorMap[status] || 'blue'
}

const getNotifyStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    success: '成功',
    failed: '失败',
    pending: '待发送',
  }
  return textMap[status] || status
}

const getActionColor = (action: string) => {
  const colorMap: Record<string, string> = {
    ack: 'gold',
    resolve: 'green',
    silence: 'gray',
    comment: 'blue',
    assign: 'purple',
    escalate: 'orange',
    close: 'red',
  }
  return colorMap[action] || 'blue'
}

const getActionText = (action: string) => {
  const textMap: Record<string, string> = {
    ack: '确认',
    resolve: '解决',
    silence: '屏蔽',
    comment: '评论',
    assign: '分配',
    escalate: '升级',
    close: '关闭',
  }
  return textMap[action] || action
}
</script>

<style scoped>
.alert-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.mt-4 {
  margin-top: 16px;
}

.mt-6 {
  margin-top: 24px;
}

.mb-1 {
  margin-bottom: 4px;
}

.mb-2 {
  margin-bottom: 8px;
}

.font-bold {
  font-weight: bold;
}
</style>
