<template>
  <div class="alert-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <!-- <a-button type="text" @click="handleGoBack">
          <template #icon><icon-left /></template>
          返回列表
        </a-button> -->
        <a-divider direction="vertical" />
        <h2 class="page-title">告警详情</h2>
        <a-tag v-if="record" :color="getStatusColor(record.status)" size="large" class="status-tag">
          {{ getStatusText(record.status) }}
        </a-tag>
      </div>
      <div class="header-right">
        <a-space v-if="record && (record.status === 'pending' || record.status === 'firing')">
          <a-button type="primary" @click="handleAck">
            <template #icon><icon-check /></template>
            确认
          </a-button>
          <a-button type="outline" status="success" @click="handleResolve">
            <template #icon><icon-check-circle /></template>
            解决
          </a-button>
          <a-button type="outline" status="warning" @click="handleSilence">
            <template #icon><icon-mute /></template>
            屏蔽
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="page-content">
      <a-spin :loading="loading" style="width: 100%">
        <div v-if="!loading && record" class="detail-container">
          <a-card class="detail-card">
            <!-- 基础信息 -->
            <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 || 'blue'">
                  {{ record.severity?.name || record.severity?.code || '-' }}
                </a-tag>
                <span v-else>-</span>
              </a-descriptions-item>
              <a-descriptions-item label="告警指纹">
                <span class="code-text">{{ record.fingerprint || '-' }}</span>
              </a-descriptions-item>
              <a-descriptions-item label="策略ID / 规则ID">
                {{ record.policy_id || '-' }} / {{ record.rule_id || '-' }}
              </a-descriptions-item>
            </a-descriptions>

            <!-- 告警内容 -->
            <a-descriptions title="告警内容" :column="2" bordered class="mt-4">
              <a-descriptions-item label="摘要" :span="2">
                {{ record.summary || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="描述" :span="2">
                {{ record.description || '-' }}
              </a-descriptions-item>
              <a-descriptions-item label="当前值">
                <span class="highlight-value">{{ record.value || '-' }}</span>
              </a-descriptions-item>
              <a-descriptions-item label="阈值">
                <span class="threshold-value">{{ record.threshold || '-' }}</span>
              </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-item label="更新时间">{{ formatDateTime(record.updated_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="关联工单">
                <template v-if="record.feedback_ticket_id">
                  <a-link @click="handleGoToTicket(record.feedback_ticket_id)">
                    工单 #{{ record.feedback_ticket_id }}
                  </a-link>
                </template>
                <template v-else>-</template>
              </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-item label="最近通知时间">{{ record.notified_at ? formatDateTime(record.notified_at) : '-' }}</a-descriptions-item>
            </a-descriptions>

            <!-- 标签 -->
            <a-descriptions title="标签 (Labels)" :column="1" bordered class="mt-4">
              <a-descriptions-item label="Labels">
                <div v-if="labels && Object.keys(labels).length > 0" class="tags-container">
                  <a-tag v-for="(value, key) in labels" :key="key" color="arcoblue">
                    {{ key }}: {{ value }}
                  </a-tag>
                </div>
                <span v-else>-</span>
              </a-descriptions-item>
            </a-descriptions>

            <!-- 注解 -->
            <a-descriptions title="注解 (Annotations)" :column="1" bordered class="mt-4">
              <a-descriptions-item label="Annotations">
                <div v-if="annotations && Object.keys(annotations).length > 0" class="tags-container">
                  <a-tag v-for="(value, key) in annotations" :key="key" color="green">
                    {{ key }}: {{ value }}
                  </a-tag>
                </div>
                <span v-else>-</span>
              </a-descriptions-item>
            </a-descriptions>

            <!-- 分组信息 -->
            <a-descriptions title="分组信息" :column="2" bordered class="mt-4">
              <a-descriptions-item label="分组键">
                <span class="code-text">{{ record.group_key || '-' }}</span>
              </a-descriptions-item>
              <a-descriptions-item label="分组标签">
                <div v-if="groupLabels && Object.keys(groupLabels).length > 0" class="tags-container">
                  <a-tag v-for="(value, key) in groupLabels" :key="key" color="purple">
                    {{ key }}: {{ value }}
                  </a-tag>
                </div>
                <span v-else>-</span>
              </a-descriptions-item>
            </a-descriptions>

            <!-- 原始数据 -->
            <a-descriptions title="原始数据 (Raw Data)" :column="1" bordered class="mt-4">
              <a-descriptions-item label="Raw Data">
                <div class="raw-data-wrapper">
                  <a-button type="text" size="small" @click="toggleRawData" class="toggle-btn">
                    {{ showRawData ? '收起' : '展开' }}
                    <template #icon>
                      <icon-down v-if="!showRawData" />
                      <icon-up v-else />
                    </template>
                  </a-button>
                  <pre v-if="showRawData" class="raw-data">{{ rawDataFormatted }}</pre>
                  <span v-else class="empty-text">点击展开查看原始数据</span>
                </div>
              </a-descriptions-item>
            </a-descriptions>

            <!-- 处理记录 -->
            <div class="mt-4">
              <div class="section-title">处理记录</div>
              <a-table
                :data="processRecords"
                :columns="processColumns"
                :pagination="false"
                :loading="processLoading"
                size="medium"
              >
                <template #action="{ record }">
                  <a-tag :color="getActionColor(record.action)">
                    {{ getActionText(record.action) }}
                  </a-tag>
                </template>
                <template #created_at="{ record }">
                  {{ formatDateTime(record.created_at) }}
                </template>
              </a-table>
              <a-empty v-if="!processLoading && processRecords.length === 0" description="暂无处理记录" />
            </div>
          </a-card>
        </div>

        <!-- 加载失败状态 -->
        <div v-if="!loading && !record" class="error-state">
          <a-result status="404" title="告警记录不存在">
            <template #subtitle>
              该告警记录可能已被删除或您没有权限查看
            </template>
            <template #extra>
              <a-button type="primary" @click="handleGoBack">
                返回列表
              </a-button>
            </template>
          </a-result>
        </div>
      </a-spin>
    </div>

    <!-- 确认对话框 -->
    <AckDialog
      v-model:visible="ackDialogVisible"
      :alert-record-id="alertId"
      @success="handleActionSuccess"
    />

    <!-- 解决对话框 -->
    <ResolveDialog
      v-model:visible="resolveDialogVisible"
      :alert-record-id="alertId"
      @success="handleActionSuccess"
    />

    <!-- 屏蔽对话框 -->
    <SilenceDialog
      v-model:visible="silenceDialogVisible"
      :alert-record-id="alertId"
      @success="handleActionSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import {
  IconLeft,
  IconCheck,
  IconCheckCircle,
  IconMute,
  IconDown,
  IconUp
} from '@arco-design/web-vue/es/icon'
import { fetchAlertRecordDetail, fetchAlertProcessList } from '@/api/ops/alertRecord'
import AckDialog from '../tackle/components/AckDialog.vue'
import ResolveDialog from '../tackle/components/ResolveDialog.vue'
import SilenceDialog from '../tackle/components/SilenceDialog.vue'

const route = useRoute()
const router = useRouter()

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

// 对话框状态
const ackDialogVisible = ref(false)
const resolveDialogVisible = ref(false)
const silenceDialogVisible = ref(false)

// 告警ID
const alertId = computed(() => Number(route.query.id))

// 解析标签
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 groupLabels = computed(() => {
  if (!record.value?.group_labels) return null
  try {
    return JSON.parse(record.value.group_labels)
  } catch {
    return null
  }
})

// 格式化原始数据
const rawDataFormatted = computed(() => {
  if (!record.value?.raw_data) return '-'
  try {
    const data = JSON.parse(record.value.raw_data)
    return JSON.stringify(data, null, 2)
  } catch {
    return record.value.raw_data
  }
})

// 处理记录表格列
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 }
]

// 加载详情
const loadDetail = async () => {
  if (!alertId.value) {
    Message.error('告警ID无效')
    return
  }

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

// 加载处理记录
const loadProcessRecords = async () => {
  if (!alertId.value) return

  processLoading.value = true
  try {
    const result = await fetchAlertProcessList({
      alert_record_id: alertId.value,
      page: 1,
      page_size: 100
    })
    processRecords.value = result.details?.data || result.data || []
  } catch (error) {
    console.error('加载处理记录失败:', error)
  } finally {
    processLoading.value = false
  }
}

// 返回
const handleGoBack = () => {
  router.back()
}

// 跳转工单
const handleGoToTicket = (ticketId: number) => {
  router.push(`/ops/ticket/${ticketId}`)
}

// 确认
const handleAck = () => {
  ackDialogVisible.value = true
}

// 解决
const handleResolve = () => {
  resolveDialogVisible.value = true
}

// 屏蔽
const handleSilence = () => {
  silenceDialogVisible.value = true
}

// 操作成功回调
const handleActionSuccess = () => {
  loadDetail()
  loadProcessRecords()
}

// 切换原始数据显示
const toggleRawData = () => {
  showRawData.value = !showRawData.value
}

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化持续时间
const formatDuration = (seconds: number) => {
  if (!seconds) return '-'
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  const parts: string[] = []
  if (days > 0) parts.push(`${days}天`)
  if (hours > 0) parts.push(`${hours}小时`)
  if (minutes > 0) parts.push(`${minutes}分钟`)
  if (secs > 0 && parts.length === 0) parts.push(`${secs}秒`)

  return parts.length > 0 ? parts.join('') : '-'
}

// 获取状态颜色
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
}

onMounted(() => {
  loadDetail()
  loadProcessRecords()
})
</script>

<script lang="ts">
export default {
  name: 'AlertDetailPage',
}
</script>

<style scoped lang="less">
.alert-detail-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-fill-2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;

  .header-left {
    display: flex;
    align-items: center;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }

    .status-tag {
      margin-left: 12px;
    }
  }
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.detail-container {
  max-width: 1200px;
  margin: 0 auto;
}

.detail-card {
  :deep(.arco-card-body) {
    padding: 20px;
  }
}

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

.code-text {
  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
  font-size: 13px;
  background: var(--color-fill-2);
  padding: 2px 6px;
  border-radius: 4px;
}

.highlight-value {
  color: rgb(var(--danger-6));
  font-weight: 600;
}

.threshold-value {
  color: rgb(var(--warning-6));
  font-weight: 600;
}

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

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  padding-left: 10px;
  border-left: 3px solid rgb(var(--primary-6));
}

.raw-data-wrapper {
  .toggle-btn {
    margin-bottom: 8px;
  }

  .raw-data {
    margin: 0;
    padding: 12px;
    background: var(--color-fill-1);
    border-radius: 6px;
    font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
    font-size: 12px;
    line-height: 1.6;
    overflow-x: auto;
    white-space: pre-wrap;
    word-break: break-all;
    max-height: 400px;
    overflow-y: auto;
  }

  .empty-text {
    color: var(--color-text-3);
  }
}

.error-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

// 响应式布局
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;

    .header-right {
      width: 100%;
    }
  }

  :deep(.arco-descriptions) {
    .arco-descriptions-table {
      table-layout: fixed;
    }

    .arco-descriptions-item-label {
      width: 100px;
    }
  }
}
</style>