<template>
  <div v-if="app">
    <el-page-header @back="$router.back()" content="Webhook 告警" style="margin-bottom:24px" />

    <el-card style="margin-bottom:16px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="应用名称">{{ app.name }}</el-descriptions-item>
        <el-descriptions-item label="未确认告警">
          <el-tag v-if="unacknowledgedCount > 0" type="danger">{{ unacknowledgedCount }}</el-tag>
          <span v-else>0</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card>
      <template #header>告警列表</template>
      <div class="toolbar toolbar-space-between" style="margin-bottom:16px">
        <div style="display:flex;gap:12px;align-items:center">
          <el-select v-model="filterAcknowledged" placeholder="确认状态" clearable style="width:140px">
            <el-option label="未确认" :value="false" />
            <el-option label="已确认" :value="true" />
          </el-select>
          <el-button @click="loadAlerts" :loading="loading">查询</el-button>
        </div>
      </div>

      <el-table :data="alerts" v-loading="loading" border stripe>
        <el-table-column prop="webhookUrl" label="回调地址" min-width="260" show-overflow-tooltip />
        <el-table-column prop="alertType" label="类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.alertType === 'AUTO_DISABLED'" type="danger" size="small">自动禁用</el-tag>
            <el-tag v-else type="warning" size="small">{{ row.alertType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" min-width="240" show-overflow-tooltip />
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.acknowledged ? 'info' : 'danger'" size="small">
              {{ row.acknowledged ? '已确认' : '未确认' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="告警时间" width="170">
          <template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="!row.acknowledged"
              link
              type="primary"
              size="small"
              @click="acknowledge(row)"
            >确认</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="page"
        v-model:page-size="size"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        style="margin-top:16px"
        @change="loadAlerts"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { appApi, type App } from '@/api/app'
import { imAdminApi, type WebhookAlert } from '@/api/im'

const route = useRoute()
const app = ref<App | null>(null)
const appId = computed(() => route.params.appId as string)

const alerts = ref<WebhookAlert[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const filterAcknowledged = ref<boolean | ''>('')
const unacknowledgedCount = ref(0)

async function loadApp() {
  const res = await appApi.get(appId.value)
  app.value = res.data.data
}

async function loadAlerts() {
  loading.value = true
  try {
    const params: Record<string, unknown> = { page: page.value - 1, size: size.value }
    if (filterAcknowledged.value !== '') params.acknowledged = filterAcknowledged.value
    const res = await imAdminApi.listWebhookAlerts(appId.value, params)
    alerts.value = res.data.data.content
    total.value = res.data.data.totalElements
  } finally {
    loading.value = false
  }
}

async function loadUnacknowledgedCount() {
  const res = await imAdminApi.listWebhookAlerts(appId.value, { acknowledged: false, size: 1 })
  unacknowledgedCount.value = Number(res.data.data.totalElements)
}

async function acknowledge(row: WebhookAlert) {
  await imAdminApi.acknowledgeWebhookAlert(appId.value, row.id)
  ElMessage.success('已确认')
  await loadAlerts()
  await loadUnacknowledgedCount()
}

function formatTime(value: number) {
  return new Date(value).toLocaleString()
}

watch([filterAcknowledged], () => {
  page.value = 1
  loadAlerts()
})

onMounted(async () => {
  await Promise.all([loadApp(), loadAlerts(), loadUnacknowledgedCount()])
})
</script>
