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

import { useAdminListPage } from "@/composables/useAdminListPage";
import { useAdminListQuerySync } from "@/composables/useAdminListQuerySync";
import AdminPageHeader from "@/components/admin/AdminPageHeader.vue";
import AdminStatusTag from "@/components/admin/AdminStatusTag.vue";
import { fetchAdminOrders } from "@/services/admin";
import type { AdminOrderListItem } from "@/types/admin";
import { adminPayStatusOptions } from "@/utils/admin-options";
import { formatAdminDateTime } from "@/utils/admin-time";

const route = useRoute();
const router = useRouter();
const { readQueryString, readQueryPage, syncRouteQuery } =
  useAdminListQuerySync(route, router);

const platformOrderId = ref(readQueryString("platformOrderId"));
const payStatus = ref(readQueryString("payStatus"));
const skuCode = ref(readQueryString("skuCode"));
const dateRange = ref<string[]>(
  [readQueryString("dateFrom"), readQueryString("dateTo")].filter(Boolean)
);

const {
  loading,
  errorMessage,
  items,
  pagination,
  loadPage: loadOrders,
} = useAdminListPage<AdminOrderListItem>({
  defaultErrorMessage: "读取订单列表失败",
  fetchPage: (page, pageSize) =>
    fetchAdminOrders({
      page,
      pageSize,
      platformOrderId: platformOrderId.value.trim(),
      payStatus: payStatus.value.trim(),
      skuCode: skuCode.value.trim(),
      dateFrom: dateRange.value[0] || "",
      dateTo: dateRange.value[1] || "",
    }),
});

const summary = computed(() => ({
  paidCount: items.value.filter((item) => item.payStatus === "paid").length,
  refundedCount: items.value.filter((item) => item.payStatus === "refunded")
    .length,
  bindingReadyCount: items.value.filter(
    (item) => item.completedBindingTaskCount > 0
  ).length,
  issueCount: items.value.filter((item) => hasOrderIssue(item)).length,
}));

function resetFilters() {
  platformOrderId.value = "";
  payStatus.value = "";
  skuCode.value = "";
  dateRange.value = [];
  void applyFilters(1);
}

async function applyFilters(page = 1) {
  await syncRouteQuery(page, {
    platformOrderId: platformOrderId.value,
    payStatus: payStatus.value,
    skuCode: skuCode.value,
    dateFrom: dateRange.value[0] || "",
    dateTo: dateRange.value[1] || "",
  });
  await loadOrders(page);
}

function resolveBuyerLabel(item: AdminOrderListItem) {
  return item.buyerName || item.buyerId || "未识别";
}

function resolveShopLabel(item: AdminOrderListItem) {
  return item.shopName || item.shopId || "未识别店铺";
}

function resolveItemSummary(item: AdminOrderListItem) {
  return item.itemSummary || "未识别商品";
}

function resolveBindingTone(completedCount: number, totalCount: number) {
  if (completedCount <= 0) return "warning";
  return completedCount === totalCount ? "success" : "primary";
}

function resolveBindingSummary(item: AdminOrderListItem) {
  return `共 ${item.totalBindingCount} 条 · 预占 ${item.reservedBindingCount} · 已消耗 ${item.consumedBindingCount} · 已释放 ${item.releasedBindingCount}`;
}

function hasOrderIssue(item: AdminOrderListItem) {
  return (
    ["refunded", "failed", "unpaid"].includes(item.payStatus) ||
    item.systemBindingStatus === "binding_exception" ||
    item.userBindingStatus === "binding_exception"
  );
}

function resolveFollowUpText(item: AdminOrderListItem) {
  if (
    item.userBindingStatus === "binding_exception" ||
    item.systemBindingStatus === "binding_exception"
  )
    return "绑定异常";
  if (item.completedBindingTaskCount <= 0) return "等待完整绑定";
  if (item.systemBoundTaskCount < item.taskCount) return "系统绑定未完成";
  return "链路正常";
}

function resolveFollowUpTone(item: AdminOrderListItem) {
  if (hasOrderIssue(item)) return "danger";
  if (
    item.completedBindingTaskCount <= 0 ||
    item.systemBoundTaskCount < item.taskCount
  )
    return "warning";
  return "success";
}

onMounted(() => {
  void applyFilters(readQueryPage());
});
</script>

<template>
  <div class="orders-page list-page">
    <AdminPageHeader
      title="订单列表"
      description="查看平台订单、支付状态、商品摘要和对应任务推进情况。"
    >
      <template #extra>
        <span class="total-badge">共 {{ pagination.total }} 条订单</span>
      </template>
    </AdminPageHeader>

    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">查询订单</span>
          <span class="card-desc"
            >按平台订单号、支付状态、SKU 和日期范围筛选。</span
          >
        </div>
      </template>
      <div class="filter-grid">
        <el-input
          v-model="platformOrderId"
          class="filter-control"
          placeholder="平台订单号（模糊匹配）"
          clearable
          @keyup.enter="applyFilters(1)"
        />
        <el-select
          v-model="payStatus"
          class="filter-control"
          placeholder="支付状态"
          clearable
        >
          <el-option
            v-for="opt in adminPayStatusOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
        <el-input
          v-model="skuCode"
          class="filter-control"
          placeholder="SKU，如 dnf-cdk-a"
          clearable
          @keyup.enter="applyFilters(1)"
        />
        <el-date-picker
          v-model="dateRange"
          class="filter-control"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          range-separator="至"
          value-format="YYYY-MM-DD"
        />
        <div class="filter-buttons">
          <el-button round @click="resetFilters">重置</el-button>
          <el-button round type="primary" @click="applyFilters(1)"
            >查询</el-button
          >
        </div>
      </div>
    </el-card>

    <div v-if="!loading && items.length > 0" class="summary-strip">
      <span class="summary-title">当前页</span>
      <span class="summary-metric" data-tone="success"
        >已支付 <strong>{{ summary.paidCount }}</strong></span
      >
      <span class="summary-metric" data-tone="danger"
        >已退款 <strong>{{ summary.refundedCount }}</strong></span
      >
      <span class="summary-metric" data-tone="primary"
        >完整绑定 <strong>{{ summary.bindingReadyCount }}</strong></span
      >
      <span
        class="summary-metric"
        :data-tone="summary.issueCount > 0 ? 'warning' : 'muted'"
        >需关注 <strong>{{ summary.issueCount }}</strong></span
      >
    </div>

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      :closable="false"
      class="mt-4"
    />

    <el-card
      shadow="never"
      class="section-card"
      v-loading="loading"
      element-loading-text="订单列表加载中"
    >
      <template v-if="items.length === 0 && !loading">
        <el-empty description="当前筛选条件下暂无订单" :image-size="60" />
      </template>

      <template v-else>
        <div class="orders-toolbar table-toolbar">
          <strong>订单明细</strong>
          <span
            >第 {{ pagination.page }} 页，当前展示 {{ items.length }} 条</span
          >
        </div>

        <el-table
          :data="items"
          stripe
          size="small"
          class="orders-table data-table"
        >
          <el-table-column label="订单信息" min-width="220">
            <template #default="{ row }">
              <div class="cell-stack">
                <RouterLink
                  :to="`/admin/orders/${row.orderId}`"
                  class="order-no id-link"
                  :title="row.platformOrderId"
                >
                  {{ row.platformOrderId }}
                </RouterLink>
                <div class="cell-meta-row">
                  <span class="compact-chip">{{ row.platform || "-" }}</span>
                  <span class="compact-chip">{{ resolveShopLabel(row) }}</span>
                  <span class="compact-chip compact-chip--muted"
                    >买家 {{ resolveBuyerLabel(row) }}</span
                  >
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品摘要" min-width="180">
            <template #default="{ row }">
              <div class="cell-stack">
                <span class="cell-title" :title="resolveItemSummary(row)">{{
                  resolveItemSummary(row)
                }}</span>
                <span class="cell-subline"
                  >{{ row.itemCount }} 项，合计 {{ row.totalQuantity }} 件</span
                >
                <span
                  class="cell-subline"
                  :title="resolveBindingSummary(row)"
                  >{{ resolveBindingSummary(row) }}</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="支付/状态" min-width="140">
            <template #default="{ row }">
              <div class="cell-stack">
                <AdminStatusTag :status="row.payStatus" :show-raw="false" />
                <div class="status-stack">
                  <AdminStatusTag :status="row.orderStatus" :show-raw="false" />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="交付状态" min-width="230">
            <template #default="{ row }">
              <div class="cell-stack">
                <div class="status-stack">
                  <AdminStatusTag
                    :status="row.systemBindingStatus"
                    :show-raw="false"
                  />
                  <AdminStatusTag
                    :status="row.userBindingStatus"
                    :show-raw="false"
                  />
                </div>
                <span
                  class="follow-up-chip"
                  :data-tone="resolveFollowUpTone(row)"
                  >{{ resolveFollowUpText(row) }}</span
                >
                <div class="progress-row-stack">
                  <span
                    class="progress-chip"
                    :data-tone="
                      resolveBindingTone(
                        row.completedBindingTaskCount,
                        row.taskCount
                      )
                    "
                  >
                    完整 {{ row.completedBindingTaskCount }}/{{ row.taskCount }}
                  </span>
                  <span
                    class="progress-chip"
                    :data-tone="
                      resolveBindingTone(
                        row.systemBoundTaskCount,
                        row.taskCount
                      )
                    "
                  >
                    系统 {{ row.systemBoundTaskCount }}/{{ row.taskCount }}
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="金额 / 时间" min-width="180">
            <template #default="{ row }">
              <div class="cell-stack">
                <span class="cell-title amount-text"
                  >{{ row.totalAmount }} {{ row.currency }}</span
                >
                <span class="cell-subline"
                  >支付 {{ formatAdminDateTime(row.paidAt) }}</span
                >
                <span class="cell-subline"
                  >更新 {{ formatAdminDateTime(row.updatedAt) }}</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ row }">
              <RouterLink
                :to="`/admin/orders/${row.orderId}`"
                class="detail-link"
                >详情</RouterLink
              >
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="pagination.total > 0"
          v-model:current-page="pagination.page"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, prev, pager, next"
          class="pagination-center"
          @current-change="applyFilters"
        />
      </template>
    </el-card>
  </div>
</template>

<style scoped>
@import "../../../styles/admin-list-pages.css";

.filter-grid {
  grid-template-columns:
    minmax(200px, 1fr) minmax(130px, 0.6fr) minmax(180px, 0.9fr)
    minmax(320px, 1.4fr) minmax(150px, 0.55fr);
}

.amount-text {
  white-space: nowrap;
}

.progress-row-stack {
  display: flex;
  flex-wrap: wrap;
  gap: var(--space-2);
  margin-top: 2px;
}

.progress-chip,
.follow-up-chip {
  display: inline-flex;
  align-items: center;
  min-height: 26px;
  padding: 0 9px;
  border-radius: var(--radius-full);
  font-size: var(--text-xs);
  font-weight: 700;
  border: 1px solid transparent;
  white-space: nowrap;
}
.progress-chip[data-tone="success"] {
  color: #0f766e;
  background: var(--color-success-light);
  border-color: #a6f4c5;
}
.progress-chip[data-tone="primary"] {
  color: var(--color-primary-dark);
  background: var(--color-primary-light);
  border-color: #b2ddff;
}
.progress-chip[data-tone="warning"] {
  color: #b54708;
  background: var(--color-warning-light);
  border-color: #fedf89;
}
.follow-up-chip[data-tone="success"] {
  color: #0f766e;
  background: var(--color-success-light);
  border-color: #a6f4c5;
}
.follow-up-chip[data-tone="warning"] {
  color: #b54708;
  background: var(--color-warning-light);
  border-color: #fedf89;
}
.follow-up-chip[data-tone="danger"] {
  color: var(--color-danger-dark);
  background: var(--color-danger-light);
  border-color: #fecaca;
}

@media (max-width: 1200px) {
  .filter-grid {
    grid-template-columns: repeat(4, minmax(0, 1fr));
  }
}
</style>
