<template>
  <div class="incidents-page">
    <a-card :bordered="false" title="Incident 事件治理">
      <template #extra>
        <a-button type="primary" :loading="loading" :disabled="pageUnauthorized" @click="fetchData">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </template>

      <a-form :model="filters" layout="inline" class="filter-form">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="filters.keyword" allow-clear placeholder="编号 / 摘要 / 资源 UID" />
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="filters.status" allow-clear placeholder="全部">
            <a-option value="open">打开</a-option>
            <a-option value="assigned">已分派</a-option>
            <a-option value="in_progress">处理中</a-option>
            <a-option value="suspended">已挂起</a-option>
            <a-option value="resolved">已解决</a-option>
            <a-option value="closed">已关闭</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="severity" label="级别">
          <a-select v-model="filters.severity" allow-clear placeholder="全部">
            <a-option value="critical">紧急</a-option>
            <a-option value="major">严重</a-option>
            <a-option value="warning">警告</a-option>
            <a-option value="info">提示</a-option>
            <a-option value="minor">轻微</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="resource_uid" label="资源 UID">
          <a-input v-model="filters.resource_uid" allow-clear placeholder="category:identity" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button @click="resetFilters">重置</a-button>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <PageState :status="pageStatus" :error-text="errorMessage" @retry="fetchData">
      <a-table
        v-if="pageStatus !== 'empty' && pageStatus !== 'error' && pageStatus !== 'unauthorized'"
        row-key="id"
        :loading="loading"
        :data="rows"
        :columns="columns"
        :pagination="pagination"
        :scroll="{ x: 'max-content' }"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #incident_no="{ record }">
          <a-typography-text copyable>{{ record.incident_no }}</a-typography-text>
        </template>
        <template #status="{ record }">
          <a-tag :color="statusColor(record.status)">{{ statusText(record.status) }}</a-tag>
        </template>
        <template #severity="{ record }">
          <a-tag :color="severityColor(record.severity)">{{ severityText(record.severity) }}</a-tag>
        </template>
        <template #resource_uid="{ record }">
          <a-typography-text v-if="record.resource_uid" copyable>{{ record.resource_uid }}</a-typography-text>
          <span v-else>-</span>
        </template>
        <template #suppressed="{ record }">
          <a-tag v-if="record.suppressed" color="orange">已抑制</a-tag>
          <span v-else>-</span>
        </template>
        <template #opened_at="{ record }">{{ formatTime(record.opened_at) }}</template>
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" :disabled="pageUnauthorized" @click="showDetail(record)">详情</a-button>
            <a-dropdown trigger="click">
              <a-button type="text" size="small" :disabled="!canOperate">流转</a-button>
              <template #content>
                <a-doption v-for="item in nextStatuses(record.status)" :key="item.value" @click="handleTransition(record, item.value)">
                  {{ item.label }}
                </a-doption>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </a-table>
      </PageState>
    </a-card>

    <a-drawer v-model:visible="detailVisible" width="860px" title="Incident 详情" unmount-on-close>
      <a-descriptions v-if="current" :column="2" bordered size="medium">
        <a-descriptions-item label="事件编号">{{ current.incident_no }}</a-descriptions-item>
        <a-descriptions-item label="状态">{{ statusText(current.status) }}</a-descriptions-item>
        <a-descriptions-item label="级别">{{ severityText(current.severity) }}</a-descriptions-item>
        <a-descriptions-item label="告警数">{{ current.alert_count }}</a-descriptions-item>
        <a-descriptions-item label="资源 UID">{{ current.resource_uid || '-' }}</a-descriptions-item>
        <a-descriptions-item label="业务系统">{{ current.business_system_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="责任人">{{ current.owner_user_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="打开时间">{{ formatTime(current.opened_at) }}</a-descriptions-item>
        <a-descriptions-item label="摘要" :span="2">{{ current.summary || '-' }}</a-descriptions-item>
        <a-descriptions-item label="依赖抑制" :span="2">
          {{ current.suppressed ? current.suppression_reason || '已命中抑制规则' : '-' }}
        </a-descriptions-item>
      </a-descriptions>

      <a-tabs class="detail-tabs" default-active-key="timeline">
        <a-tab-pane key="timeline" title="时间线">
          <a-timeline>
            <a-timeline-item v-for="item in timeline" :key="`${item.event_type}-${item.occurred_at}`" :label="formatTime(item.occurred_at)">
              <strong>{{ eventText(item.event_type) }}</strong>
              <div class="timeline-message">{{ item.message || '-' }}</div>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>
        <a-tab-pane key="alerts" title="关联告警">
          <a-table row-key="id" :data="alerts" :pagination="false" size="small">
            <template #columns>
              <a-table-column title="ID" data-index="id" :width="80" />
              <a-table-column title="名称" data-index="alert_name" />
              <a-table-column title="状态" data-index="status" :width="110" />
              <a-table-column title="摘要" data-index="summary" />
              <a-table-column title="开始时间" data-index="starts_at" :width="180">
                <template #cell="{ record }">{{ formatTime(record.starts_at) }}</template>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="knowledge" title="关联知识">
          <div class="knowledge-toolbar">
            <a-button type="primary" size="small" @click="handleCreatePostmortemDraft">生成复盘草稿</a-button>
          </div>
          <a-table row-key="id" :data="knowledgeRelations" :pagination="false" size="small">
            <template #columns>
              <a-table-column title="类型" data-index="knowledge_type" :width="90" />
              <a-table-column title="标题" data-index="knowledge_title" />
              <a-table-column title="关系" data-index="relation_type" :width="110" />
              <a-table-column title="来源" data-index="source" :width="100" />
              <a-table-column title="分数" data-index="score" :width="80" />
            </template>
          </a-table>
          <a-divider orientation="left">推荐知识</a-divider>
          <a-table row-key="detection_point_id" :data="knowledgeRecommendations" :pagination="false" size="small">
            <template #columns>
              <a-table-column title="类型" data-index="knowledge_type" :width="90" />
              <a-table-column title="标题" data-index="title" />
              <a-table-column title="命中原因" data-index="reason" />
              <a-table-column title="分数" data-index="score" :width="80" />
              <a-table-column title="操作" :width="90">
                <template #cell="{ record }">
                  <a-button type="text" size="small" @click="handleRelateKnowledge(record)">关联</a-button>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="payload" title="上下文">
          <pre class="json-block">{{ prettyJSON(current?.labels) }}</pre>
          <pre class="json-block">{{ prettyJSON(current?.annotations) }}</pre>
        </a-tab-pane>
      </a-tabs>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import {
  fetchIncidentAlerts,
  fetchIncidents,
  fetchIncidentTimeline,
  transitionIncident,
  type Incident,
} from '@/api/ops/incident'
import {
  createPostmortemDraft,
  fetchIncidentKnowledge,
  fetchKnowledgeRecommendations,
  relateIncidentKnowledge,
  type IncidentKnowledgeRelation,
  type KnowledgeRecommendation,
} from '@/api/kb/knowledge'

const loading = ref(false)
const rows = ref<Incident[]>([])
const current = ref<Incident | null>(null)
const detailVisible = ref(false)
const errorMessage = ref('')
const pageUnauthorized = ref(false)
const timeline = ref<any[]>([])
const alerts = ref<any[]>([])
const knowledgeRelations = ref<IncidentKnowledgeRelation[]>([])
const knowledgeRecommendations = ref<KnowledgeRecommendation[]>([])

const filters = reactive({
  keyword: '',
  status: undefined as string | undefined,
  severity: undefined as string | undefined,
  resource_uid: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: true,
  showPageSize: true,
})

const columns: TableColumnData[] = [
  { title: '事件编号', dataIndex: 'incident_no', slotName: 'incident_no', width: 190 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 110 },
  { title: '级别', dataIndex: 'severity', slotName: 'severity', width: 100 },
  { title: '资源 UID', dataIndex: 'resource_uid', slotName: 'resource_uid', width: 230 },
  { title: '摘要', dataIndex: 'summary', ellipsis: true, tooltip: true },
  { title: '告警数', dataIndex: 'alert_count', width: 90 },
  { title: '依赖抑制', dataIndex: 'suppressed', slotName: 'suppressed', width: 110 },
  { title: '打开时间', dataIndex: 'opened_at', slotName: 'opened_at', width: 180 },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', fixed: 'right', width: 140 },
]

const canOperate = computed(() => !pageUnauthorized.value)

const pageStatus = computed(() => {
  if (pageUnauthorized.value) return 'unauthorized'
  if (loading.value) return 'loading'
  if (errorMessage.value && !rows.value.length) return 'error'
  if (!rows.value.length) return 'empty'
  return 'success'
})

const isForbidden = (error: any) => error?.response?.status === 403 || error?.code === 403 || error?.code === 401

const setLoadError = (error: any, fallback: string) => {
  if (isForbidden(error)) {
    pageUnauthorized.value = true
    errorMessage.value = '当前账号没有访问 Incident 事件的权限。'
    return
  }
  errorMessage.value = error?.message || fallback
}

const fetchData = async () => {
  loading.value = true
  errorMessage.value = ''
  pageUnauthorized.value = false
  try {
    const response: any = await fetchIncidents({
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: filters.keyword || undefined,
      status: filters.status,
      severity: filters.severity,
      resource_uid: filters.resource_uid || undefined,
    })
    rows.value = response.details?.data || []
    pagination.total = response.details?.total || 0
  } catch (error) {
    console.error('获取 Incident 失败:', error)
    setLoadError(error, '获取 Incident 失败')
    Message.error('获取 Incident 失败')
  } finally {
    loading.value = false
  }
}

const showDetail = async (record: Incident) => {
  current.value = record
  detailVisible.value = true
  const resourceCategory = record.resource_uid?.split(':')[0]
  const [timelineRes, alertsRes, knowledgeRes, recommendRes]: any[] = await Promise.all([
    fetchIncidentTimeline(record.id),
    fetchIncidentAlerts(record.id),
    fetchIncidentKnowledge(record.id),
    fetchKnowledgeRecommendations({ resource_category: resourceCategory, limit: 5 }),
  ])
  timeline.value = timelineRes.details || []
  alerts.value = alertsRes.details || []
  knowledgeRelations.value = knowledgeRes.details || []
  knowledgeRecommendations.value = recommendRes.details || []
}

const handleRelateKnowledge = async (record: KnowledgeRecommendation) => {
  if (!current.value) return
  await relateIncidentKnowledge({
    incident_id: current.value.id,
    knowledge_type: record.knowledge_type,
    knowledge_id: record.knowledge_id,
    knowledge_title: record.title,
    relation_type: 'recommended',
    source: 'manual',
    score: record.score,
    reason: record.reason,
  })
  Message.success('知识已关联')
  const response: any = await fetchIncidentKnowledge(current.value.id)
  knowledgeRelations.value = response.details || []
}

const handleCreatePostmortemDraft = async () => {
  if (!current.value) return
  await createPostmortemDraft({
    incident: {
      id: current.value.id,
      incident_no: current.value.incident_no,
      summary: current.value.summary,
      severity: current.value.severity,
      resource_uid: current.value.resource_uid,
      business_system_id: current.value.business_system_id,
      opened_at: current.value.opened_at,
      resolved_at: current.value.resolved_at,
    },
    timeline: timeline.value.map((item) => ({
      occurred_at: item.occurred_at,
      event_type: item.event_type,
      message: item.message,
    })),
    comments: [],
  })
  Message.success('复盘草稿已生成')
  const response: any = await fetchIncidentKnowledge(current.value.id)
  knowledgeRelations.value = response.details || []
}

const handleTransition = async (record: Incident, status: string) => {
  try {
    await transitionIncident(record.id, { status })
    Message.success('状态已更新')
    fetchData()
  } catch (error) {
    console.error('Incident 状态流转失败:', error)
    Message.error('Incident 状态流转失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetFilters = () => {
  filters.keyword = ''
  filters.status = undefined
  filters.severity = undefined
  filters.resource_uid = ''
  handleSearch()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchData()
}

const nextStatuses = (status: string) => {
  const map: Record<string, Array<{ value: string; label: string }>> = {
    open: [{ value: 'assigned', label: '分派' }],
    assigned: [{ value: 'in_progress', label: '开始处理' }],
    in_progress: [
      { value: 'suspended', label: '挂起' },
      { value: 'resolved', label: '解决' },
    ],
    suspended: [
      { value: 'in_progress', label: '重启处理' },
      { value: 'resolved', label: '解决' },
    ],
    resolved: [{ value: 'closed', label: '关闭' }],
  }
  return map[status] || []
}

const statusText = (value?: string) => {
  const map: Record<string, string> = {
    open: '打开',
    assigned: '已分派',
    in_progress: '处理中',
    suspended: '已挂起',
    resolved: '已解决',
    closed: '已关闭',
  }
  return value ? map[value] || value : '-'
}

const statusColor = (value?: string) => {
  const map: Record<string, string> = {
    open: 'red',
    assigned: 'blue',
    in_progress: 'arcoblue',
    suspended: 'orange',
    resolved: 'green',
    closed: 'gray',
  }
  return value ? map[value] || 'gray' : 'gray'
}

const severityText = (value?: string) => {
  const map: Record<string, string> = {
    critical: '紧急',
    major: '严重',
    warning: '警告',
    info: '提示',
    minor: '轻微',
  }
  return value ? map[value] || value : '-'
}

const severityColor = (value?: string) => {
  const map: Record<string, string> = {
    critical: 'red',
    major: 'orangered',
    warning: 'orange',
    info: 'blue',
    minor: 'gray',
  }
  return value ? map[value] || 'gray' : 'gray'
}

const eventText = (value?: string) => {
  const map: Record<string, string> = {
    incident_opened: '事件打开',
    incident_assigned: '事件分派',
    incident_in_progress: '开始处理',
    incident_suspended: '事件挂起',
    incident_resolved: '事件解决',
    incident_closed: '事件关闭',
    received: '告警接收',
    incident_upserted: '事件归并',
    notified: '通知发送',
    ticket_created: '工单创建',
  }
  return value ? map[value] || value : '-'
}

const formatTime = (value?: string) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString('zh-CN')
}

const prettyJSON = (value?: string) => {
  if (!value) return '{}'
  try {
    return JSON.stringify(JSON.parse(value), null, 2)
  } catch {
    return value
  }
}

onMounted(fetchData)
</script>

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

<style scoped lang="less">
.incidents-page {
  padding: 16px;
}

.filter-form {
  margin-bottom: 16px;
}

.detail-tabs {
  margin-top: 16px;
}

.timeline-message {
  margin-top: 4px;
  color: var(--color-text-2);
  word-break: break-word;
}

.json-block {
  max-height: 260px;
  overflow: auto;
  margin: 0 0 12px;
  padding: 12px;
  background: var(--color-fill-2);
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-word;
}

.knowledge-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
}

@media (max-width: 768px) {
  .incidents-page {
    padding: 12px;
  }

  .filter-form {
    display: block;
  }

  :deep(.arco-form-layout-inline .arco-form-item) {
    width: 100%;
    margin-right: 0;
  }

  :deep(.arco-card-header) {
    flex-wrap: wrap;
    gap: 8px;
  }

  :deep(.arco-card-extra) {
    width: 100%;
  }
}
</style>
