<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

import AdminStatusTag from "@/components/admin/AdminStatusTag.vue";
import { fetchAdminOrderDetail } from "@/services/admin";
import type { AdminOrderDetail } from "@/types/admin";
import {
  formatAutoDeliveryReason,
  formatBindingRoleSummary,
  formatBindingCountSummary,
  resolveTaskAutoDeliveryStatus,
  formatTaskAutoDeliveryReason,
} from "@/utils/admin-display";
import { formatAdminDateTime } from "@/utils/admin-time";
import { formatAdminWebhookEventType } from "@/utils/admin-webhook";

const route = useRoute();
const loading = ref(true);
const errorMessage = ref("");
const detail = ref<AdminOrderDetail | null>(null);

onMounted(async () => {
  try {
    const response = await fetchAdminOrderDetail(
      String(route.params.orderId || "")
    );
    detail.value = response.data;
  } catch (error) {
    errorMessage.value =
      error instanceof Error ? error.message : "读取订单详情失败";
  } finally {
    loading.value = false;
  }
});

function formatJsonBlock(value: Record<string, unknown>) {
  return JSON.stringify(value || {}, null, 2);
}

function formatSpecSummary(spec: Record<string, unknown>) {
  const entries = Object.entries(spec || {})
    .filter(
      ([, value]) =>
        value !== null && value !== undefined && String(value).trim() !== ""
    )
    .slice(0, 4)
    .map(([key, value]) => `${key}: ${String(value)}`);

  return entries.length > 0 ? entries.join(" | ") : "-";
}
</script>

<template>
  <section class="admin-panel">
    <AdminPageHeader
      title="订单详情"
      description="查看订单原始信息、商品子项和关联任务。"
    />

    <p v-if="errorMessage" class="error-copy">{{ errorMessage }}</p>

    <el-skeleton v-if="loading" :rows="8" animated />

    <template v-else-if="detail">
      <section class="info-card">
        <div class="info-card-header">
          <div>
            <h2>{{ detail.order.platformOrderId }}</h2>
            <p class="subtitle">
              {{ detail.order.platform }} /
              {{ detail.order.shopName || detail.order.shopId || "未识别店铺" }}
            </p>
          </div>
          <div class="status-stack">
            <AdminStatusTag :status="detail.order.payStatus" />
            <AdminStatusTag :status="detail.order.orderStatus" />
            <AdminStatusTag
              :status="detail.order.bindingSummary.systemBindingStatus"
            />
            <AdminStatusTag
              :status="detail.order.bindingSummary.userBindingStatus"
            />
          </div>
        </div>

        <div class="info-grid">
          <article class="info-tile">
            <span>商品标题</span>
            <strong>{{ detail.order.itemSummary || "-" }}</strong>
            <small>来自订单详情 title / 商品标题字段</small>
          </article>
          <article class="info-tile">
            <span>订单金额</span>
            <strong
              >{{ detail.order.totalAmount }}
              {{ detail.order.currency }}</strong
            >
            <small
              >支付时间：{{ formatAdminDateTime(detail.order.paidAt) }}</small
            >
          </article>
          <article class="info-tile">
            <span>买家信息</span>
            <strong>{{ detail.order.buyerName || "-" }}</strong>
            <small>ID：{{ detail.order.buyerId || "-" }}</small>
          </article>
          <article class="info-tile">
            <span>联系方式</span>
            <strong>{{ detail.order.receiverContact || "-" }}</strong>
            <small
              >店铺：{{
                detail.order.shopName || detail.order.shopId || "-"
              }}</small
            >
          </article>
          <article class="info-tile">
            <span>任务进度</span>
            <strong
              >{{ detail.order.bindingSummary.completedBindingTaskCount }}/{{
                detail.order.bindingSummary.totalTaskCount
              }}
              完整绑定</strong
            >
            <small
              >{{ detail.order.bindingSummary.systemBoundTaskCount }}/{{
                detail.order.bindingSummary.totalTaskCount
              }}
              系统绑定</small
            >
          </article>
          <article class="info-tile">
            <span>库存绑定</span>
            <strong
              >{{
                detail.order.bindingSummary.totalBindingCount
              }}
              条绑定记录</strong
            >
            <small
              >预占 {{ detail.order.bindingSummary.reservedBindingCount }} ·
              已消费 {{ detail.order.bindingSummary.consumedBindingCount }} ·
              已释放
              {{ detail.order.bindingSummary.releasedBindingCount }}</small
            >
          </article>
          <article v-if="detail.order.agisoAutoDelivery" class="info-tile">
            <span>自动发货</span>
            <div class="tile-tag-line">
              <AdminStatusTag :status="detail.order.agisoAutoDelivery.status" />
            </div>
            <strong>
              {{
                detail.order.agisoAutoDelivery.errorMessage ||
                formatAutoDeliveryReason(
                  detail.order.agisoAutoDelivery.reason
                ) ||
                "全部任务交付后会自动触发"
              }}
            </strong>
            <small>
              已交付 {{ detail.order.agisoAutoDelivery.deliveredTaskCount }}/{{
                detail.order.agisoAutoDelivery.totalTaskCount
              }}
              · 最近执行
              {{
                formatAdminDateTime(detail.order.agisoAutoDelivery.updatedAt)
              }}
            </small>
          </article>
        </div>

        <el-table :data="[detail.order]" size="small" :show-header="false">
          <el-table-column label="内部订单 ID" width="120">
            <template #default="{ row }">{{ row.orderId }}</template>
          </el-table-column>
          <el-table-column label="提供方" width="120">
            <template #default="{ row }">{{ row.provider }}</template>
          </el-table-column>
          <el-table-column label="平台" width="100">
            <template #default="{ row }">{{ row.platform }}</template>
          </el-table-column>
          <el-table-column label="店铺 ID">
            <template #default="{ row }">{{ row.shopId || "-" }}</template>
          </el-table-column>
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">{{
              formatAdminDateTime(row.createdAt)
            }}</template>
          </el-table-column>
          <el-table-column label="更新时间" width="180">
            <template #default="{ row }">{{
              formatAdminDateTime(row.updatedAt)
            }}</template>
          </el-table-column>
        </el-table>
      </section>

      <section class="info-card">
        <h3>商品子项</h3>
        <el-table :data="detail.items" size="small">
          <el-table-column prop="skuCode" label="SKU" />
          <el-table-column prop="itemTitle" label="标题">
            <template #default="{ row }">{{ row.itemTitle || "-" }}</template>
          </el-table-column>
          <el-table-column prop="skuName" label="商品" />
          <el-table-column prop="deliveryMode" label="发放方式" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column label="规格摘要">
            <template #default="{ row }">{{
              formatSpecSummary(row.spec)
            }}</template>
          </el-table-column>
        </el-table>
      </section>

      <section class="info-card">
        <h3>关联任务</h3>
        <el-table :data="detail.tasks" size="small">
          <el-table-column label="任务号">
            <template #default="{ row }">
              <RouterLink :to="`/admin/tasks/${row.taskId}`">{{
                row.taskNo
              }}</RouterLink>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="{ row }">
              <AdminStatusTag :status="row.status" />
            </template>
          </el-table-column>
          <el-table-column label="系统绑定">
            <template #default="{ row }">
              <AdminStatusTag :status="row.systemBindingStatus" />
            </template>
          </el-table-column>
          <el-table-column label="完整绑定">
            <template #default="{ row }">
              <AdminStatusTag :status="row.userBindingStatus" />
            </template>
          </el-table-column>
          <el-table-column label="自动发货">
            <template #default="{ row }">
              <div class="tile-tag-line">
                <AdminStatusTag :status="resolveTaskAutoDeliveryStatus(row)" />
              </div>
              <div class="binding-copy">
                {{ formatTaskAutoDeliveryReason(row) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库存绑定">
            <template #default="{ row }">
              <div>{{ formatBindingCountSummary(row.bindingSummary) }}</div>
              <div class="binding-copy">
                角色 {{ formatBindingRoleSummary(row.bindingSummary.roleKeys) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="登录方式">
            <template #default="{ row }">{{ row.loginType || "-" }}</template>
          </el-table-column>
          <el-table-column label="错误">
            <template #default="{ row }">{{ row.lastError || "-" }}</template>
          </el-table-column>
        </el-table>
      </section>

      <section class="info-card">
        <h3>Webhook 摘要</h3>
        <el-table :data="detail.webhookEvents" size="small">
          <el-table-column label="事件 ID">
            <template #default="{ row }">
              <RouterLink :to="`/admin/webhook-events/${row.eventId}`">{{
                row.eventId
              }}</RouterLink>
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template #default="{ row }">{{
              formatAdminWebhookEventType(row.eventType)
            }}</template>
          </el-table-column>
          <el-table-column label="平台 / 店铺">
            <template #default="{ row }"
              >{{ row.platform }} /
              {{ row.shopName || row.shopId || "-" }}</template
            >
          </el-table-column>
          <el-table-column label="验签">
            <template #default="{ row }">
              <AdminStatusTag
                :status="row.signatureValid ? 'success' : 'failed'"
              />
            </template>
          </el-table-column>
          <el-table-column label="处理">
            <template #default="{ row }">
              <AdminStatusTag :status="row.processed ? 'success' : 'failed'" />
            </template>
          </el-table-column>
          <el-table-column label="时间" width="180">
            <template #default="{ row }">{{
              formatAdminDateTime(row.createdAt)
            }}</template>
          </el-table-column>
          <template #empty>
            <el-empty description="当前订单还没有关联的 webhook 记录" />
          </template>
        </el-table>
      </section>

      <section class="info-card">
        <h3>原始载荷</h3>
        <details class="payload-box">
          <summary>展开查看原始订单 JSON</summary>
          <pre>{{ formatJsonBlock(detail.order.rawPayload) }}</pre>
        </details>
      </section>
    </template>

    <el-empty v-else description="订单不存在或已被删除" />
  </section>
</template>

<style scoped>
.admin-panel {
  display: grid;
  gap: var(--space-4);
}

.info-card {
  padding: 18px;
  border-radius: var(--radius-lg);
  background: var(--bg-surface);
  border: 1px solid var(--border-default);
}

.info-card h3 {
  margin: 0 0 var(--space-4);
  color: var(--text-primary);
}

.error-copy {
  padding: 18px;
  border-radius: var(--radius-lg);
  background: var(--bg-surface);
  border: 1px solid var(--border-default);
  color: var(--color-danger);
}

.info-card-header {
  display: flex;
  justify-content: space-between;
  gap: var(--space-4);
  align-items: flex-start;
  margin-bottom: var(--space-4);
}

.info-card-header h2 {
  margin: 0;
  color: var(--text-primary);
}

.subtitle {
  margin: var(--space-2) 0 0;
  color: var(--text-secondary);
}

.status-stack {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  justify-content: flex-end;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: var(--space-3);
  margin-bottom: var(--space-4);
}

.info-tile {
  padding: 14px var(--space-4);
  border-radius: var(--radius-md);
  background: linear-gradient(
    180deg,
    rgba(247, 250, 255, 0.98),
    rgba(241, 245, 249, 0.92)
  );
  border: 1px solid var(--border-default);
  display: grid;
  gap: 6px;
}

.info-tile span,
.info-tile small {
  color: var(--text-secondary);
}

.info-tile strong {
  color: var(--text-primary);
}

.tile-tag-line {
  display: flex;
  align-items: center;
}

.binding-copy {
  margin-top: 6px;
  color: var(--text-secondary);
  font-size: var(--text-xs);
}

.payload-box summary {
  cursor: pointer;
  color: var(--color-primary);
  font-weight: 600;
}

.payload-box pre {
  margin: var(--space-3) 0 0;
  padding: 14px;
  overflow-y: auto;
  border-radius: var(--radius-md);
  background: #0f172a;
  color: #dbeafe;
  font-size: var(--text-xs);
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

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

@media (max-width: 900px) {
  .info-card-header {
    flex-direction: column;
  }

  .status-stack {
    justify-content: flex-start;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
