<template>
  <el-card shadow="never">
    <template #header>
      <div class="toolbar">
        <span class="title">Callback 收件箱</span>
        <div class="actions">
          <el-select v-model="filterStatus" clearable placeholder="状态" class="filter" style="width: 140px">
            <el-option label="待处理 (PENDING)" value="PENDING" />
            <el-option label="已处理 (PROCESSED)" value="PROCESSED" />
            <el-option label="失败 (FAILED)" value="FAILED" />
            <el-option label="忽略 (IGNORED)" value="IGNORED" />
          </el-select>
          <el-input v-model="filterEventType" clearable placeholder="事件类型" class="filter" style="width: 160px" @keyup.enter="load" />
          <el-input v-model="filterSnCode" clearable placeholder="SN 编码" class="filter" style="width: 140px" @keyup.enter="load" />
          <el-input v-model="filterProjectId" clearable placeholder="项目 ID" class="filter" style="width: 120px" @keyup.enter="load" />
          <el-button type="primary" :loading="loading" @click="load">查询</el-button>
          <el-button @click="handleBatchRetry" :disabled="selectedCallbacks.length === 0">批量重试</el-button>
        </div>
      </div>
    </template>

    <el-table v-loading="loading" :data="rows" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="sourceSystem" label="来源" width="120" show-overflow-tooltip />
      <el-table-column prop="externalMessageId" label="外部消息 ID" min-width="160" show-overflow-tooltip />
      <el-table-column prop="eventType" label="事件类型" min-width="140" show-overflow-tooltip />
      <el-table-column prop="snCode" label="SN" width="120" show-overflow-tooltip />
      <el-table-column label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收件时间" width="170">
        <template #default="{ row }">{{ formatDateTime(row.receivedAt) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="goDetail(row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="load"
        @size-change="onSizeChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useAuthStore } from "../stores/auth";
import { listCallbackInbox, replayCallbackWebhookDelivery } from "../api/platform";
import { apiErrorMessage } from "../utils/apiErrorMessage";

const auth = useAuthStore();
const router = useRouter();

const loading = ref(false);
const rows = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const filterStatus = ref("");
const filterEventType = ref("");
const filterSnCode = ref("");
const filterProjectId = ref("");
const selectedCallbacks = ref([]);

function handleSelectionChange(val) {
  selectedCallbacks.value = val;
}

async function handleBatchRetry() {
  let success = 0;
  let fail = 0;
  for (const cb of selectedCallbacks.value) {
    try {
      await replayCallbackWebhookDelivery(cb.id);
      success++;
    } catch {
      fail++;
    }
  }
  ElMessage.success(`重试完成: ${success} 成功, ${fail} 失败`);
  load();
}

onMounted(async () => {
  auth.restoreAxiosAuth();
  await load();
});

function onSizeChange() {
  page.value = 1;
  load();
}

function statusLabel(s) {
  const u = String(s ?? "").toUpperCase();
  const map = { PENDING: "待处理", PROCESSED: "已处理", FAILED: "失败", IGNORED: "忽略" };
  return map[u] ?? String(s ?? "—");
}

function statusTagType(s) {
  const u = String(s ?? "").toUpperCase();
  if (u === "PENDING") return "warning";
  if (u === "PROCESSED") return "success";
  if (u === "FAILED") return "danger";
  if (u === "IGNORED") return "info";
  return "";
}

function formatDateTime(v) {
  if (v == null || v === "") return "—";
  if (typeof v === "string") return v.replace("T", " ").slice(0, 19);
  return String(v);
}

async function load() {
  loading.value = true;
  try {
    const { data } = await listCallbackInbox({
      page: page.value - 1,
      size: pageSize.value,
      status: filterStatus.value || undefined,
      eventType: filterEventType.value?.trim() || undefined,
      snCode: filterSnCode.value?.trim() || undefined,
      projectId: filterProjectId.value?.trim() || undefined,
    });
    const body = data && typeof data === "object" ? data : {};
    rows.value = Array.isArray(body.content) ? body.content : [];
    total.value = Number(body.totalElements ?? body.total ?? 0);
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载 Callback 收件箱失败"));
    rows.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

function goDetail(id) {
  router.push({ name: "callback-inbox-detail", params: { id: String(id) } });
}
</script>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
