<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'

import AdminPaginationBar from '@/components/admin/AdminPaginationBar.vue'
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import { showConfirm, showError, showSuccess } from '@/lib/feedback'
import { fetchAdminWebhookEvents, replayAdminWebhookEvent } from '@/services/admin'
import type { AdminPagination, AdminWebhookEventListItem } from '@/types/admin'
import { hasAdminRole } from '@/utils/admin-auth'
import { formatAdminDateTime } from '@/utils/admin-time'
import { formatAdminWebhookEventType } from '@/utils/admin-webhook'
import { adminWebhookProcessedOptions, adminWebhookVisibilityOptions } from '@/utils/admin-options'

const loading = ref(true)
const actionLoadingId = ref<number | null>(null)
const errorMessage = ref('')
const items = ref<AdminWebhookEventListItem[]>([])
const provider = ref('')
const platform = ref('')
const platformOrderId = ref('')
const processed = ref('')
const visibility = ref('important')
const relatedOrderId = ref('')
const dateFrom = ref('')
const dateTo = ref('')
const pagination = ref<AdminPagination>({
  page: 1,
  pageSize: 20,
  total: 0,
})

const canReplay = hasAdminRole('admin')

const summary = computed(() => ({
  processedCount: items.value.filter((item) => item.processed).length,
  failedCount: items.value.filter((item) => !item.processed || Boolean(item.processError)).length,
  importantCount: items.value.filter((item) => item.visibilityLevel === 'important').length,
}))

async function loadEvents(page = pagination.value.page) {
  loading.value = true
  errorMessage.value = ''

  try {
    const response = await fetchAdminWebhookEvents({
      page,
      pageSize: pagination.value.pageSize,
      provider: provider.value.trim(),
      platform: platform.value.trim(),
      platformOrderId: platformOrderId.value.trim(),
      processed: processed.value.trim(),
      visibility: visibility.value.trim(),
      relatedOrderId: relatedOrderId.value.trim(),
      dateFrom: dateFrom.value.trim(),
      dateTo: dateTo.value.trim(),
    })
    items.value = response.data.items
    pagination.value = response.data.pagination
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '读取 webhook 列表失败'
  } finally {
    loading.value = false
  }
}

async function submitReplay(item: AdminWebhookEventListItem) {
  try {
    await showConfirm(
      `确认重放 webhook #${item.eventId} 吗？`,
      '确认重放',
      {
        type: 'warning',
        confirmButtonText: '继续重放',
        cancelButtonText: '取消',
      },
    )
  } catch {
    return
  }

  actionLoadingId.value = item.eventId

  try {
    await replayAdminWebhookEvent(item.eventId)
    showSuccess('Webhook 已重放')
    await loadEvents()
  } catch (error) {
    showError(error instanceof Error ? error.message : '重放 webhook 失败')
  } finally {
    actionLoadingId.value = null
  }
}

function resetFilters() {
  provider.value = ''
  platform.value = ''
  platformOrderId.value = ''
  processed.value = ''
  visibility.value = 'important'
  relatedOrderId.value = ''
  dateFrom.value = ''
  dateTo.value = ''
  void loadEvents(1)
}

function formatRequestTimestamp(value: string) {
  const normalized = String(value || '').trim()

  if (!/^\d{10,13}$/.test(normalized)) {
    return normalized || '-'
  }

  const epochMs = normalized.length === 13 ? Number(normalized) : Number(normalized) * 1000
  return formatAdminDateTime(new Date(epochMs).toISOString())
}

function formatAmount(item: AdminWebhookEventListItem) {
  return item.totalAmount ? `${item.totalAmount} ${item.currency}` : '-'
}

function formatVisibilityLabel(value: string) {
  return value === 'ignored' ? '已忽略' : '重要'
}

onMounted(loadEvents)
</script>

<template>
  <section class="admin-panel">
    <header class="panel-header">
      <div class="panel-header-copy">
        <h1>Webhook 日志</h1>
        <p>查看平台推送处理情况、验签结果、请求来源和错误信息。</p>
      </div>
      <div class="panel-header-badge">共 {{ pagination.total }} 条事件</div>
    </header>

    <section class="filters-card">
      <div class="filters-grid">
        <label class="filter-field">
          <span>服务商</span>
          <input v-model="provider" class="text-input" placeholder="如 agiso" />
        </label>
        <label class="filter-field">
          <span>业务平台</span>
          <input v-model="platform" class="text-input" placeholder="如 xianyu / taobao" />
        </label>
        <label class="filter-field">
          <span>处理结果</span>
          <select v-model="processed" class="text-input select-input">
            <option v-for="option in adminWebhookProcessedOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </label>
        <label class="filter-field">
          <span>可见级别</span>
          <select v-model="visibility" class="text-input select-input">
            <option v-for="option in adminWebhookVisibilityOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </label>
        <label class="filter-field">
          <span>平台订单号</span>
          <input v-model="platformOrderId" class="text-input" placeholder="平台订单号" />
        </label>
        <label class="filter-field">
          <span>关联订单 ID</span>
          <input v-model="relatedOrderId" class="text-input" placeholder="后台订单 ID" />
        </label>
        <label class="filter-field">
          <span>开始日期</span>
          <input v-model="dateFrom" class="text-input" type="date" />
        </label>
        <label class="filter-field">
          <span>结束日期</span>
          <input v-model="dateTo" class="text-input" type="date" />
        </label>
      </div>
      <div class="filters-actions">
        <span class="filters-hint">Webhook 事件已拆成来源、摘要、订单、验签、请求来源几个信息块，排查会更直观。</span>
        <div class="filters-button-row">
          <el-button round @click="resetFilters">重置</el-button>
          <el-button round type="primary" @click="() => loadEvents(1)">查询</el-button>
        </div>
      </div>
    </section>

    <section v-if="!loading && items.length > 0" class="summary-grid">
      <article class="summary-card summary-card-success">
        <span class="summary-label">当前页处理成功</span>
        <strong class="summary-value">{{ summary.processedCount }}</strong>
        <span class="summary-meta">已通过处理链路，通常无需人工介入</span>
      </article>
      <article class="summary-card summary-card-danger">
        <span class="summary-label">当前页异常 / 失败</span>
        <strong class="summary-value">{{ summary.failedCount }}</strong>
        <span class="summary-meta">优先查看验签、处理错误和请求来源</span>
      </article>
      <article class="summary-card summary-card-primary">
        <span class="summary-label">当前页重要事件</span>
        <strong class="summary-value">{{ summary.importantCount }}</strong>
        <span class="summary-meta">仅重要模式下更适合日常排查</span>
      </article>
    </section>

    <p v-if="errorMessage" class="error-copy">{{ errorMessage }}</p>
    <div v-if="loading" class="empty-block">Webhook 列表加载中</div>
    <div v-else-if="items.length === 0" class="empty-block">当前筛选条件下暂无 Webhook 事件</div>

    <div v-else class="events-shell">
      <div class="events-toolbar">
        <div>
          <strong>Webhook 列表</strong>
          <span>第 {{ pagination.page }} 页，当前展示 {{ items.length }} 条</span>
        </div>
      </div>

      <div class="event-list">
        <article v-for="item in items" :key="item.eventId" class="event-card">
          <div class="event-card-top">
            <div class="event-identity">
              <RouterLink :to="`/admin/webhook-events/${item.eventId}`" class="cell-link event-no">
                #{{ item.eventId }} · {{ formatAdminWebhookEventType(item.eventType) }}
              </RouterLink>
              <div class="event-meta-row">
                <span class="compact-chip">{{ item.provider || '-' }}</span>
                <span class="compact-chip">{{ item.platform || '-' }}</span>
                <span v-if="item.shopName || item.shopId" class="compact-chip compact-chip--muted">
                  {{ item.shopName || item.shopId }}
                </span>
              </div>
            </div>
            <div class="event-top-actions">
              <span class="compact-chip compact-chip--muted">{{ formatVisibilityLabel(item.visibilityLevel) }}</span>
              <el-button
                v-if="canReplay"
                :loading="actionLoadingId === item.eventId"
                class="secondary-action"
                @click="submitReplay(item)"
              >
                重放
              </el-button>
            </div>
          </div>

          <div class="event-grid">
            <section class="event-section">
              <span class="section-label">来源</span>
              <div class="cell-stack">
                <div class="cell-title">{{ item.provider }} / {{ item.platform }}</div>
                <div v-if="item.platformRaw && item.platformRaw !== item.platform" class="cell-subtle">
                  原始平台 {{ item.platformRaw }}
                </div>
                <div class="meta-chip-row">
                  <span class="meta-chip">店铺 {{ item.shopName || item.shopId || '-' }}</span>
                  <span v-if="item.shopId" class="meta-chip">ID {{ item.shopId }}</span>
                </div>
              </div>
            </section>

            <section class="event-section">
              <span class="section-label">事件摘要</span>
              <div class="cell-stack">
                <div class="cell-title">{{ formatAdminWebhookEventType(item.eventType) }}</div>
                <div v-if="item.messageText" class="cell-subtle">{{ item.messageText }}</div>
                <div class="meta-chip-row">
                  <span v-if="item.aopic" class="meta-chip">aopic {{ item.aopic }}</span>
                  <span v-if="item.itemCount" class="meta-chip">商品 {{ item.itemCount }}</span>
                </div>
                <div class="mono-inline event-key" :title="item.eventKey">Key: {{ item.eventKey }}</div>
              </div>
            </section>

            <section class="event-section">
              <span class="section-label">订单与店铺</span>
              <div class="cell-stack">
                <div class="cell-title">平台单 {{ item.platformOrderId || '-' }}</div>
                <div class="cell-subtle">买家 {{ item.buyerName || item.buyerId || '-' }}</div>
                <div class="cell-subtle">金额 {{ formatAmount(item) }}</div>
                <div class="meta-chip-row">
                  <span class="meta-chip">
                    关联订单
                    <template v-if="item.relatedOrderId">
                      <RouterLink class="inline-link" :to="`/admin/orders/${item.relatedOrderId}`">{{ item.relatedOrderId }}</RouterLink>
                    </template>
                    <template v-else>-</template>
                  </span>
                  <span class="meta-chip">任务 {{ item.taskCount }}</span>
                </div>
              </div>
            </section>

            <section class="event-section">
              <span class="section-label">验签与处理</span>
              <div class="cell-stack">
                <div class="tag-row">
                  <AdminStatusTag :status="item.signatureValid ? 'success' : 'failed'" />
                  <AdminStatusTag :status="item.processed ? 'success' : 'failed'" />
                </div>
                <div class="cell-subtle" :title="item.requestSign || '-'">签名 {{ item.requestSign || '-' }}</div>
                <div v-if="item.processError" class="error-inline">{{ item.processError }}</div>
              </div>
            </section>

            <section class="event-section">
              <span class="section-label">请求来源</span>
              <div class="cell-stack">
                <div class="cell-title">{{ item.sourceHost || '-' }}</div>
                <div class="cell-subtle">IP {{ item.sourceIp || '-' }}</div>
                <div class="cell-subtle line-clamp-2">UA {{ item.userAgent || '-' }}</div>
                <div class="cell-subtle">请求时间 {{ formatRequestTimestamp(item.requestTimestamp) }}</div>
              </div>
            </section>

            <section class="event-section">
              <span class="section-label">时间</span>
              <div class="cell-stack">
                <div class="cell-title">{{ formatAdminDateTime(item.createdAt) }}</div>
                <div class="cell-subtle">事件 ID #{{ item.eventId }}</div>
              </div>
            </section>
          </div>
        </article>
      </div>

      <AdminPaginationBar
        :page="pagination.page"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :loading="loading"
        @change="loadEvents"
      />
    </div>
  </section>
</template>

<style scoped>
.admin-panel {
  display: grid;
  gap: 14px;
  min-width: 0;
}

.panel-header {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
}

.panel-header-copy {
  min-width: 0;
}

.panel-header h1 {
  margin: 0;
  font-size: 34px;
  line-height: 1.05;
  letter-spacing: -0.04em;
  color: #1d3555;
}

.panel-header p {
  margin: 6px 0 0;
  font-size: 14px;
  color: #64748b;
}

.panel-header-badge {
  flex: 0 0 auto;
  min-height: 34px;
  padding: 0 14px;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.82);
  border: 1px solid rgba(86, 108, 138, 0.12);
  color: #38506e;
  font-size: 12px;
  font-weight: 700;
  display: inline-flex;
  align-items: center;
}

.filters-card,
.summary-card,
.events-shell,
.empty-block,
.error-copy {
  padding: 16px 18px;
  border-radius: 18px;
  background: rgba(255, 255, 255, 0.94);
  border: 1px solid rgba(86, 108, 138, 0.1);
  box-shadow: 0 14px 36px rgba(30, 49, 78, 0.06);
}

.filters-card {
  display: grid;
  gap: 14px;
}

.filters-grid {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 12px;
}

.filter-field {
  display: grid;
  gap: 6px;
  min-width: 0;
}

.filter-field span {
  color: #5d6f87;
  font-size: 12px;
  font-weight: 600;
}

.filters-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.filters-hint {
  color: #64748b;
  font-size: 12px;
}

.filters-button-row {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.text-input {
  width: 100%;
  min-height: 38px;
  padding: 0 12px;
  border-radius: 12px;
  border: 1px solid rgba(86, 108, 138, 0.18);
  background: rgba(255, 255, 255, 0.94);
  color: #24364e;
  font-size: 13px;
}

.select-input {
  appearance: none;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.summary-card {
  display: grid;
  gap: 6px;
  position: relative;
  overflow: hidden;
}

.summary-card::after {
  content: '';
  position: absolute;
  inset: auto -26px -26px auto;
  width: 96px;
  height: 96px;
  border-radius: 999px;
  opacity: 0.14;
}

.summary-card-success::after {
  background: #12b76a;
}

.summary-card-danger::after {
  background: #f04438;
}

.summary-card-primary::after {
  background: #2563eb;
}

.summary-label {
  color: #51647d;
  font-size: 12px;
  font-weight: 700;
  letter-spacing: 0.04em;
}

.summary-value {
  font-size: 34px;
  line-height: 1;
  color: #1d3555;
}

.summary-meta {
  color: #70829a;
  font-size: 12px;
}

.error-copy {
  margin: 0;
  color: #b42318;
}

.empty-block {
  color: #64748b;
}

.events-shell {
  display: grid;
  gap: 14px;
  min-width: 0;
}

.events-toolbar strong {
  display: block;
  color: #1f324a;
  font-size: 14px;
}

.events-toolbar span {
  display: block;
  margin-top: 4px;
  color: #64748b;
  font-size: 12px;
}

.event-list {
  display: grid;
  gap: 12px;
}

.event-card {
  display: grid;
  gap: 14px;
  padding: 14px;
  border-radius: 16px;
  background: linear-gradient(180deg, rgba(248, 251, 255, 0.98) 0%, #ffffff 100%);
  border: 1px solid rgba(86, 108, 138, 0.12);
}

.event-card-top {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.event-identity {
  min-width: 0;
  display: grid;
  gap: 8px;
}

.event-no {
  display: inline-block;
  max-width: 100%;
  font-size: 20px;
  line-height: 1.1;
  font-weight: 800;
  color: #132238;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.event-meta-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.event-top-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.compact-chip {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  max-width: 100%;
  padding: 0 10px;
  border-radius: 999px;
  background: #f4f7fb;
  border: 1px solid rgba(86, 108, 138, 0.1);
  color: #44556c;
  font-size: 12px;
  font-weight: 600;
}

.compact-chip--muted {
  color: #6b7c93;
}

.secondary-action {
  min-width: 82px;
  min-height: 30px;
  padding: 0 12px;
  border-radius: 999px;
  font-weight: 600;
  font-size: 12px;
  background: #ffffff;
  border-color: rgba(86, 108, 138, 0.18);
  color: #344054;
}

.secondary-action:hover,
.secondary-action:focus {
  border-color: rgba(23, 92, 211, 0.28);
  color: #175cd3;
  background: #f8fbff;
}

.event-grid {
  display: grid;
  grid-template-columns: repeat(6, minmax(0, 1fr));
  gap: 10px;
  min-width: 0;
}

.event-section {
  display: grid;
  gap: 6px;
  min-width: 0;
  padding: 10px 11px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.78);
  border: 1px solid rgba(86, 108, 138, 0.08);
}

.section-label {
  color: #71839b;
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
}

.cell-stack {
  display: grid;
  gap: 6px;
  min-width: 0;
}

.cell-title {
  color: #0f172a;
  font-weight: 700;
  line-height: 1.4;
  word-break: break-word;
}

.cell-subtle {
  color: #64748b;
  font-size: 12px;
  line-height: 1.5;
  word-break: break-word;
}

.meta-chip-row,
.tag-row {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.meta-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  min-height: 24px;
  padding: 0 8px;
  border-radius: 999px;
  color: #475467;
  background: #f8fafc;
  border: 1px solid rgba(148, 163, 184, 0.24);
  font-size: 12px;
}

.inline-link {
  color: #175cd3;
  font-weight: 700;
  text-decoration: none;
}

.cell-link {
  color: inherit;
  text-decoration: none;
}

.cell-link:hover {
  color: #175cd3;
}

.mono-inline {
  color: #344054;
  font-size: 12px;
  line-height: 1.6;
  font-family: var(--font-mono);
  overflow-wrap: anywhere;
}

.event-key {
  color: #71839b;
  font-size: 10px;
  line-height: 1.4;
}

.error-inline {
  display: block;
  color: #b42318;
  font-size: 12px;
  line-height: 1.5;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.event-top-actions :deep(.el-button > span) {
  white-space: nowrap;
}

@media (max-width: 1400px) {
  .filters-grid {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}

@media (max-width: 1180px) {
  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .event-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

@media (max-width: 980px) {
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .filters-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .filters-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  .event-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 720px) {
  .panel-header h1 {
    font-size: 28px;
  }

  .filters-grid,
  .summary-grid,
  .event-grid {
    grid-template-columns: 1fr;
  }

  .filters-button-row,
  .event-card-top,
  .event-top-actions {
    width: 100%;
  }

  .filters-button-row {
    justify-content: stretch;
  }

  .filters-button-row :deep(.el-button),
  .event-top-actions :deep(.el-button) {
    flex: 1 1 auto;
  }

  .event-card-top {
    flex-direction: column;
    align-items: flex-start;
  }

  .event-no {
    font-size: 18px;
  }
}
</style>
