<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="回调地址">{{ webhookUrl }}</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="filterEvent" placeholder="事件类型" clearable style="width:180px">
            <el-option label="message.sent" value="message.sent" />
            <el-option label="message.revoked" value="message.revoked" />
            <el-option label="message.edited" value="message.edited" />
            <el-option label="message.read" value="message.read" />
          </el-select>
          <el-select v-model="filterSuccess" placeholder="状态" clearable style="width:120px">
            <el-option label="成功" :value="true" />
            <el-option label="失败" :value="false" />
          </el-select>
          <el-button @click="loadDeliveries" :loading="loading">查询</el-button>
        </div>
      </div>

      <el-table :data="deliveries" v-loading="loading" border stripe>
        <el-table-column prop="callbackEvent" label="事件" width="160" />
        <el-table-column prop="attempt" label="重试次数" width="90" />
        <el-table-column label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.success ? 'success' : 'danger'" size="small">
              {{ row.success ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="httpStatus" label="HTTP" width="90" />
        <el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip />
        <el-table-column prop="responseBody" label="响应体" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="时间" width="170">
          <template #default="{ row }">{{ formatTime(row.createdAt) }}</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="loadDeliveries"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { appApi, type App } from '@/api/app'
import { imAdminApi, type WebhookDelivery } from '@/api/im'
import { formatTime } from '@/utils/date'

const route = useRoute()
const app = ref<App | null>(null)
const appKey = computed(() => route.params.appKey as string)
const webhookId = computed(() => route.params.webhookId as string)
const webhookUrl = ref('')

const deliveries = ref<WebhookDelivery[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(20)
const total = ref(0)
const filterEvent = ref('')
const filterSuccess = ref<boolean | ''>('')

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

async function loadWebhook() {
  const res = await imAdminApi.listWebhooks(appKey.value)
  const wh = res.data.data.find((w) => w.id === webhookId.value)
  if (wh) webhookUrl.value = wh.url
}

async function loadDeliveries() {
  loading.value = true
  try {
    const params: Record<string, unknown> = { page: page.value - 1, size: size.value }
    if (filterEvent.value) params.callbackEvent = filterEvent.value
    if (filterSuccess.value !== '') params.success = filterSuccess.value
    const res = await imAdminApi.listWebhookDeliveries(appKey.value, params)
    deliveries.value = res.data.data.content
    total.value = res.data.data.totalElements
  } finally {
    loading.value = false
  }
}


watch([filterEvent, filterSuccess], () => {
  page.value = 1
  loadDeliveries()
})

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