<template>
  <div class="table-box zfb-examine-page">
    <h1 class="page-title">查看支付宝审核</h1>

    <el-alert v-if="loadError" class="mb-16" type="warning" :closable="false" show-icon :title="loadError" />

    <ProTable row-key="_rowKey" :columns="columns" :request-api="getExamineList" :init-param="initParam" :pagination="false">
      <template #signUrl="scope">
        <el-link v-if="isHttpUrl(scope.row.signUrl)" :href="scope.row.signUrl" target="_blank" type="primary">
          {{ scope.row.signUrl }}
        </el-link>
        <span v-else>{{ scope.row.signUrl }}</span>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import type { ColumnProps } from "@/components/ProTable/interface";
import { getAlipayExamine } from "@/api/modules/businessInfo";

/** 与产品约定：查询指定进件订单 */
const ALIPAY_EXAMINE_ORDER = "2026040700502000000050184000";

type ExamineDisplayRow = {
  id: string;
  applymentNo: string;
  signUrl: string;
  applymentState: string;
  rejectReason: string;
  _rowKey: string;
};

const KEY_ID = ["id", "Id", "_id"];
const KEY_APPLYMENT_NO = [
  "order",
  "order_id",
  "orderId",
  "applyment_id",
  "applymentId",
  "out_request_no",
  "outRequestNo",
  "business_code",
  "businessCode"
];
const KEY_SIGN = ["sign_url", "signUrl", "signing_url", "signingUrl", "agreement_url", "agreementUrl"];
const KEY_REJECT = ["reject_reason", "rejectReason", "fail_reason", "failReason", "reason", "sub_msg", "subMsg"];

/** 支付宝 / 直付通常见状态码（接口若返回英文枚举可在此补充） */
const APPLYMENT_STATE_LABEL: Record<string, string> = {
  AUDITING: "审核中",
  AUDIT_PASS: "审核通过",
  AUDIT_REJECT: "审核驳回",
  AUDITING_WAIT_FOR_CONFIRM: "待确认",
  CANCEL: "已撤销",
  SUCCESS: "成功",
  FAIL: "失败",
  PROCESSING: "处理中"
};

function formatApplymentStateLabel(raw: string): string {
  const t = String(raw ?? "").trim();
  if (!t || t === "—") return "—";
  const upper = t.toUpperCase().replace(/\s+/g, "_");
  if (APPLYMENT_STATE_LABEL[upper]) return APPLYMENT_STATE_LABEL[upper];
  if (APPLYMENT_STATE_LABEL[t]) return APPLYMENT_STATE_LABEL[t];
  return t;
}

function pickApplymentStateRaw(row: Record<string, unknown>): string {
  const codeKeys = [
    "applyment_state",
    "applymentState",
    "order_status",
    "orderStatus",
    "status",
    "audit_status",
    "auditStatus",
    "state"
  ] as const;
  for (const k of codeKeys) {
    if (Object.prototype.hasOwnProperty.call(row, k)) {
      const v = row[k];
      if (v !== undefined && v !== null && v !== "") {
        return String(v).trim();
      }
    }
  }
  const descKeys = ["applyment_state_desc", "applymentStateDesc", "status_desc", "statusDesc", "msg", "message"] as const;
  for (const k of descKeys) {
    if (Object.prototype.hasOwnProperty.call(row, k)) {
      const v = row[k];
      if (v !== undefined && v !== null && v !== "") {
        return String(v).trim();
      }
    }
  }
  return "";
}

const loadError = ref("");

const initParam = reactive({ order: ALIPAY_EXAMINE_ORDER });

const columns: ColumnProps<ExamineDisplayRow>[] = [
  { prop: "id", label: "ID", width: 100, align: "center" },
  { prop: "applymentNo", label: "订单号 / 申请单号", minWidth: 200 },
  { prop: "signUrl", label: "签约链接", minWidth: 220 },
  { prop: "applymentState", label: "状态", minWidth: 140 },
  { prop: "rejectReason", label: "驳回 / 失败原因", minWidth: 200 }
];

function formatCell(v: unknown): string {
  if (v === null || v === undefined || v === "") return "—";
  if (typeof v === "object") {
    try {
      return JSON.stringify(v);
    } catch {
      return String(v);
    }
  }
  return String(v);
}

function isHttpUrl(s: string): boolean {
  if (!s || s === "—") return false;
  return /^https?:\/\//i.test(s.trim());
}

function pickField(row: Record<string, unknown>, keys: string[]): string {
  for (const k of keys) {
    if (Object.prototype.hasOwnProperty.call(row, k)) {
      const v = row[k];
      if (v !== undefined && v !== null && v !== "") {
        return formatCell(v);
      }
    }
  }
  return "—";
}

function normalizeRow(row: Record<string, unknown>): Omit<ExamineDisplayRow, "_rowKey"> {
  const stateRaw = pickApplymentStateRaw(row);
  return {
    id: pickField(row, KEY_ID),
    applymentNo: pickField(row, KEY_APPLYMENT_NO),
    signUrl: pickField(row, KEY_SIGN),
    applymentState: stateRaw ? formatApplymentStateLabel(stateRaw) : "—",
    rejectReason: pickField(row, KEY_REJECT)
  };
}

function unwrapPayload(raw: unknown): unknown {
  if (raw === null || raw === undefined) return null;
  if (Array.isArray(raw)) return raw;
  if (typeof raw !== "object") return raw;
  const o = raw as Record<string, unknown>;
  if (Array.isArray(o.list)) return o.list;
  if (Array.isArray(o.records)) return o.records;
  if (Array.isArray(o.rows)) return o.rows;
  if (o.data !== undefined && o.data !== null) {
    const inner = o.data;
    if (Array.isArray(inner)) return inner;
    if (typeof inner === "object" && !Array.isArray(inner)) {
      const obj = inner as Record<string, unknown>;
      if (Array.isArray(obj.list)) return obj.list;
      if (Array.isArray(obj.records)) return obj.records;
    }
    return inner;
  }
  return raw;
}

function isPlainObjectRow(x: unknown): x is Record<string, unknown> {
  return x !== null && typeof x === "object" && !Array.isArray(x);
}

function buildDisplayRows(payload: unknown): Omit<ExamineDisplayRow, "_rowKey">[] {
  if (payload === null || payload === undefined) return [];

  if (Array.isArray(payload)) {
    if (payload.length === 0) return [];
    if (isPlainObjectRow(payload[0])) {
      return (payload as Record<string, unknown>[]).map(normalizeRow);
    }
    return [
      {
        id: "—",
        applymentNo: "—",
        signUrl: "—",
        applymentState: "—",
        rejectReason: formatCell(payload)
      }
    ];
  }

  if (isPlainObjectRow(payload)) {
    return [normalizeRow(payload)];
  }

  return [
    {
      id: "—",
      applymentNo: "—",
      signUrl: "—",
      applymentState: "—",
      rejectReason: formatCell(payload)
    }
  ];
}

function withRowKeys(rows: Omit<ExamineDisplayRow, "_rowKey">[]): ExamineDisplayRow[] {
  return rows.map((r, i) => ({
    ...r,
    _rowKey: `zfb-examine-${i}-${r.id}-${r.applymentNo}`.replace(/\s/g, "")
  }));
}

/**
 * 与 ProTable 约定一致：返回 { data }。
 */
async function getExamineList(_params: unknown) {
  loadError.value = "";
  try {
    const res = (await getAlipayExamine({ order: ALIPAY_EXAMINE_ORDER })) as { data?: unknown };
    const payload = unwrapPayload(res?.data ?? res);
    const list = withRowKeys(buildDisplayRows(payload));
    return { data: list };
  } catch (e: unknown) {
    const msg = e && typeof e === "object" && "msg" in e ? String((e as { msg?: string }).msg) : "";
    loadError.value = msg || "获取支付宝审核信息失败";
    return { data: [] as ExamineDisplayRow[] };
  }
}
</script>

<style scoped lang="scss">
.zfb-examine-page {
  padding: 24px 32px 40px;
  background: #ffffff;
}
.page-title {
  margin: 0 0 20px;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
.mb-16 {
  margin-bottom: 16px;
}
</style>
