CouponController.ts 27 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
import type { AxiosResponse, AxiosStatic } from "axios";
import { isOrderCouponsDevMockActive } from "@/common/orderCouponsDevMock";
import mockOrderCouponsEnvelope from "./mockOrderCouponsEnvelope.json";

// region 前端扩展导入包(类型定义;实体入 lib 后可改为从 lib 引用)
// endregion

// region 请求/响应类型(与后端 OpenAPI 对齐;baseURL 见 `VITE_APP_API_URL`,一般为 `.../app/api/`,此处为相对路径 `coupon/...`)

/** POST coupon/verify — 核销优惠券 */
export interface CouponVerifyReq {
    couponId: string;
    orderId: number;
    orderCode?: string;
    transactionAmount?: number;
    vehicleId?: number;
    vehicleInfo?: string;
}

export interface CouponVerifyResp {
    couponId: string;
    orderId: number;
    actualDeduction: number;
}

/** GET coupon/popup — 获取待展示弹窗 */
export interface CouponPopupItem {
    couponId: string;
    templateName: string;
    faceAmount: number;
    validEndTime: string;
    distributionSource: string;
    /** 可选:1 抵扣车款;2 抵扣佣金(后端下发时优先于前端关键字推断) */
    deductionType?: number;
}

export interface CouponPopupResp {
    popupType: number;
    couponList: CouponPopupItem[];
}

/** GET coupon/popup — Spring `BaseResp` 外层 */
export interface CouponPopupApiEnvelope {
    code?: string;
    data?: CouponPopupResp | null;
    success?: boolean;
    message?: string;
}

/** 联调样例:GET coupon/popup 的 `res.data`(与后端约定一致后可删) */
const MOCK_COUPON_POPUP_HTTP_BODY: CouponPopupApiEnvelope = {
    code: "200",
    data: {
        popupType: 4,
        couponList: [
            {
                couponId: "CPN202605120000017",
                templateName: "20260508自测固定时间20元优惠券",
                faceAmount: 20,
                validEndTime: "2026-05-17 23:59:59",
                distributionSource: "手动发放",
                deductionType: 2,
            },
            {
                couponId: "CPN202605120000018",
                templateName: "新人参拍神券",
                faceAmount: 1000,
                validEndTime: "2026-12-31 23:59:59",
                distributionSource: "活动下发",
                deductionType: 2,
            },
            {
                couponId: "CPN202605120000019",
                templateName: "平台过户激励券·抵扣佣金",
                faceAmount: 50,
                validEndTime: "2026-06-30 23:59:59",
                distributionSource: "过户成功",
                deductionType: 2,
            },
        ],
    },
    success: true,
    message: "操作成功",
};

/**
 * 车辆详情等 `GET coupon/popup`:为 true 时使用本文件 `MOCK_COUPON_POPUP_HTTP_BODY`,不发请求;
 * 为 false(默认)时走真实 `axios.get('coupon/popup')`。
 */
const COUPON_POPUP_HTTP_MOCK_ENABLED = false;

function couponPopupUsesHttpMock(): boolean {
    return COUPON_POPUP_HTTP_MOCK_ENABLED;
}

/** GET coupon/order-coupons/{orderId}:`mockOrderCouponsEnvelope.json`(仅开发构建,见 `orderCouponsDevMock.ts`) */
function orderCouponsUsesHttpMock(): boolean {
    return isOrderCouponsDevMockActive();
}

/** 解析后的待通知优惠券弹窗(便于组件使用) */
export interface ParsedCouponPopup {
    popupType: number;
    couponList: CouponPopupItem[];
}

function normalizePopupCouponItem(
    raw: Record<string, unknown>,
    index: number
): CouponPopupItem {
    let couponId =
        typeof raw.couponId === "string"
            ? raw.couponId.trim()
            : String(raw.couponId ?? "").trim();
    if (!couponId) {
        couponId = `temp_${index}`;
    }
    let validEndTime = "";
    const vet = raw.validEndTime;
    if (typeof vet === "string") {
        validEndTime = vet;
    } else if (vet != null && typeof vet === "object" && Array.isArray(vet)) {
        validEndTime = String(vet);
    } else if (vet != null) {
        validEndTime = String(vet);
    }
    const dtRaw = raw.deductionType;
    let deductionType: number | undefined;
    if (typeof dtRaw === "number" && Number.isFinite(dtRaw)) {
        deductionType = dtRaw;
    } else if (dtRaw != null && typeof dtRaw !== "object") {
        const n = Number(dtRaw);
        if (Number.isFinite(n)) {
            deductionType = n;
        }
    }
    const item: CouponPopupItem = {
        couponId,
        templateName:
            typeof raw.templateName === "string"
                ? raw.templateName
                : String(raw.templateName ?? ""),
        faceAmount:
            typeof raw.faceAmount === "number"
                ? raw.faceAmount
                : Number(raw.faceAmount) || 0,
        validEndTime,
        distributionSource:
            typeof raw.distributionSource === "string"
                ? raw.distributionSource
                : String(raw.distributionSource ?? ""),
    };
    if (deductionType !== undefined) {
        item.deductionType = deductionType;
    }
    return item;
}

function parseJsonIfString(raw: unknown): unknown {
    if (typeof raw === "string") {
        try {
            return JSON.parse(raw) as unknown;
        } catch {
            return raw;
        }
    }
    return raw;
}

/** 小程序等环境下列表偶发为非 Array.isArray 的类数组;兼容 JSON 字符串、单券对象。 */
function normalizePopupCouponListRaw(
    raw: unknown
): Record<string, unknown>[] | null {
    const parsed = parseJsonIfString(raw);
    if (parsed == null) {
        return null;
    }
    const asRecords = (items: unknown[]): Record<string, unknown>[] => {
        const out: Record<string, unknown>[] = [];
        for (let i = 0; i < items.length; i++) {
            const row = items[i];
            if (row != null && typeof row === "object" && !Array.isArray(row)) {
                out.push(row as Record<string, unknown>);
            }
        }
        return out;
    };

    if (Array.isArray(parsed)) {
        const rows = asRecords(parsed);
        return rows.length ? rows : null;
    }

    if (Object.prototype.toString.call(parsed) === "[object Array]") {
        const rows = asRecords(Array.from(parsed as unknown[]));
        return rows.length ? rows : null;
    }

    if (typeof parsed === "object" && !Array.isArray(parsed)) {
        const o = parsed as Record<string, unknown>;
        const lenRaw = o.length;
        if (
            typeof lenRaw === "number" &&
            Number.isFinite(lenRaw) &&
            lenRaw >= 0 &&
            lenRaw <= 1e4
        ) {
            const buf: unknown[] = [];
            for (let i = 0; i < lenRaw; i++) {
                const key = String(i);
                if (Object.prototype.hasOwnProperty.call(o, key)) {
                    buf.push(o[key]);
                }
            }
            const rows = asRecords(buf);
            if (rows.length) {
                return rows;
            }
        }
        if (
            typeof o.couponId !== "undefined" ||
            typeof o.templateName !== "undefined"
        ) {
            return [o];
        }
    }

    return null;
}

function buildParsedCouponPopupFromRecord(
    r: Record<string, unknown>
): ParsedCouponPopup | null {
    const popupTypeRaw = r.popupType;
    const popupType =
        typeof popupTypeRaw === "number" ? popupTypeRaw : Number(popupTypeRaw);
    const rows = normalizePopupCouponListRaw(r.couponList);
    if (!rows || rows.length === 0) {
        return null;
    }
    const couponList: CouponPopupItem[] = [];
    rows.forEach((row, index) => {
        couponList.push(normalizePopupCouponItem(row, index));
    });
    if (couponList.length === 0) {
        return null;
    }
    const resolvedPopupType = Number.isFinite(popupType) ? popupType : 0;
    return {
        popupType: resolvedPopupType,
        couponList,
    };
}

function pickNestedEnvelopeField(r: Record<string, unknown>): unknown {
    if (Object.prototype.hasOwnProperty.call(r, "data")) {
        return r.data;
    }
    if (Object.prototype.hasOwnProperty.call(r, "result")) {
        return r.result;
    }
    return undefined;
}

/**
 * 将 axios `res.data` 剥到「最后一层 Spring BaseResp」:`{ success/code, data: { popupType, couponList } }`。
 * 兼容网关再包一层:`{ code, data: BaseResp }`,避免顶层有 code 就不再向内剥的问题。
 */
function peelToCouponEnvelope(raw: unknown): unknown {
    let cur: unknown = parseJsonIfString(raw);
    for (let step = 0; step < 8; step++) {
        if (cur == null || typeof cur !== "object" || Array.isArray(cur)) {
            return cur;
        }
        const r = cur as Record<string, unknown>;
        const nestedRaw = pickNestedEnvelopeField(r);
        if (nestedRaw === undefined) {
            return cur;
        }
        const inner = parseJsonIfString(nestedRaw);
        if (inner == null || typeof inner !== "object" || Array.isArray(inner)) {
            return cur;
        }
        const ir = inner as Record<string, unknown>;
        const innerLooksLikePopupBody =
            Object.prototype.hasOwnProperty.call(ir, "couponList") ||
            Object.prototype.hasOwnProperty.call(ir, "popupType");
        if (innerLooksLikePopupBody) {
            return cur;
        }
        const innerLooksLikeEnvelope =
            Object.prototype.hasOwnProperty.call(ir, "success") ||
            typeof ir.code !== "undefined";
        if (innerLooksLikeEnvelope) {
            cur = inner;
            continue;
        }
        return cur;
    }
    return cur;
}

/**
 * 从 axios 响应解析 coupon/popup 业务数据。
 * 兼容:body 为 JSON 字符串、`BaseResp` 嵌套、`data` 为字符串、根对象直接带 couponList、缺省 success 但有 data。
 */
export function extractCouponPopupPayload(
    res: AxiosResponse<unknown>
): ParsedCouponPopup | null {
    const rootUnknown = peelToCouponEnvelope(res?.data);
    if (
        rootUnknown == null ||
        typeof rootUnknown !== "object" ||
        Array.isArray(rootUnknown)
    ) {
        return null;
    }
    const root = rootUnknown as Record<string, unknown>;
    if (root.success === false) {
        return null;
    }
    let inner = parseJsonIfString(root.data);
    if (
        Array.isArray(inner) &&
        inner.length === 1 &&
        inner[0] != null &&
        typeof inner[0] === "object" &&
        !Array.isArray(inner[0])
    ) {
        inner = inner[0];
    }

    if (inner && typeof inner === "object" && !Array.isArray(inner)) {
        const parsed = buildParsedCouponPopupFromRecord(
            inner as Record<string, unknown>
        );
        if (parsed) {
            return parsed;
        }
    }
    const fromRoot = buildParsedCouponPopupFromRecord(root);
    if (fromRoot) {
        return fromRoot;
    }

    if (import.meta.env.DEV) {
        const hintEnvelope =
            root.success !== false &&
            (root.data !== undefined ||
                root.code !== undefined ||
                root.message !== undefined);
        if (hintEnvelope) {
            console.warn(
                "[coupon/popup] envelope present but parse returned null; check couponList shape",
                { keys: Object.keys(root), dataKind: typeof root.data },
            );
        }
    }
    return null;
}

/**
 * 解析 GET coupon/popup 的 BaseResp。
 * 说明:当前后端在查询成功时已批量标记弹窗通知为已触达,故前端应在即将展示弹窗前调用接口(勿仅预拉取不展示)。
 */
export function parseCouponPopupResponse(
    res: AxiosResponse<unknown>
): ParsedCouponPopup | null {
    return extractCouponPopupPayload(res);
}

export interface UsedCouponInfo {
    couponId: string;
    templateName: string;
    faceAmount: number;
    actualDeduction: number;
    deductionType: number;
    usageTime: string;
}

export interface OrderCouponItem {
    couponId: string;
    templateName: string;
    couponType: number;
    deductionType: number;
    faceAmount: number;
    thresholdAmount: number;
    actualDeduction: number;
    validStartTime: string;
    validEndTime: string;
    receiveTime: string;
    available: boolean;
    unavailableReason: string | null;
    recommended: boolean;
    usedByCurrentOrder: boolean;
    usedCouponInfo?: UsedCouponInfo;
}

/**
 * GET coupon/order-coupons 解析结果(待签署订单页用)。
 * - available=true:本单当前可选;配合 usedByCurrentOrder 表示是否已被本单占用(一般不可再选其它券)。
 * - available=false:不可选,用 unavailableReason 展示原因(门槛、时间、已核销等)。
 */
export interface OrderCouponsParseResult {
    list: OrderCouponItem[];
    success: boolean;
    message?: string;
}

function normalizeOrderCouponItem(
    raw: Record<string, unknown>,
    index: number
): OrderCouponItem {
    const couponIdRaw = raw.couponId;
    const couponId =
        typeof couponIdRaw === "string" && couponIdRaw.trim()
            ? couponIdRaw.trim()
            : String(couponIdRaw ?? `row_${index}`);

    const num = (v: unknown): number => {
        if (typeof v === "number" && Number.isFinite(v)) return v;
        const n = Number(v);
        return Number.isFinite(n) ? n : 0;
    };

    const str = (v: unknown): string =>
        typeof v === "string" ? v : String(v ?? "");

    const bool = (v: unknown): boolean =>
        v === true || v === "true" || v === 1 || v === "1";

    let usedCouponInfo: UsedCouponInfo | undefined;
    const uci = raw.usedCouponInfo;
    if (uci != null && typeof uci === "object" && !Array.isArray(uci)) {
        const u = uci as Record<string, unknown>;
        usedCouponInfo = {
            couponId: str(u.couponId),
            templateName: str(u.templateName),
            faceAmount: num(u.faceAmount),
            actualDeduction: num(u.actualDeduction),
            deductionType: num(u.deductionType),
            usageTime: str(u.usageTime),
        };
    }

    const ur = raw.unavailableReason;
    const unavailableReason =
        ur == null || ur === ""
            ? null
            : typeof ur === "string"
              ? ur
              : String(ur);

    return {
        couponId,
        templateName: str(raw.templateName),
        couponType: num(raw.couponType),
        deductionType: num(raw.deductionType),
        faceAmount: num(raw.faceAmount),
        thresholdAmount: num(raw.thresholdAmount),
        actualDeduction: num(raw.actualDeduction),
        validStartTime: str(raw.validStartTime),
        validEndTime: str(raw.validEndTime),
        receiveTime: str(raw.receiveTime),
        available: bool(raw.available),
        unavailableReason,
        recommended: bool(raw.recommended),
        usedByCurrentOrder: bool(raw.usedByCurrentOrder),
        usedCouponInfo,
    };
}

/** 从 Spring BaseResp / 网关包装中取出 order-coupons 的 data 数组 */
function extractOrderCouponsPayload(root: Record<string, unknown>): unknown[] {
    const dataRaw = parseJsonIfString(root.data);
    if (Array.isArray(dataRaw)) {
        return dataRaw;
    }
    return [];
}

/**
 * 解析 GET coupon/order-coupons:兼容 `{ success, data: OrderCouponItem[], message }` 及网关再包一层。
 * 调用方应使用本函数而非直接读 `res.data`,避免与后端信封不一致。
 */
export function parseOrderCouponsResponse(
    res: AxiosResponse<unknown>
): OrderCouponsParseResult {
    const fail = (message?: string): OrderCouponsParseResult => ({
        list: [],
        success: false,
        message,
    });

    const top = res?.data;
    if (top == null) {
        return fail();
    }

    if (Array.isArray(top)) {
        const list: OrderCouponItem[] = [];
        top.forEach((row, i) => {
            if (row != null && typeof row === "object" && !Array.isArray(row)) {
                list.push(
                    normalizeOrderCouponItem(row as Record<string, unknown>, i)
                );
            }
        });
        return { list, success: true };
    }

    const peeled = peelToCouponEnvelope(top);
    if (
        peeled == null ||
        typeof peeled !== "object" ||
        Array.isArray(peeled)
    ) {
        return fail();
    }

    const root = peeled as Record<string, unknown>;
    if (root.success === false) {
        const msg =
            typeof root.message === "string" ? root.message : undefined;
        return fail(msg);
    }

    const rows = extractOrderCouponsPayload(root);
    const list: OrderCouponItem[] = [];
    rows.forEach((row, i) => {
        if (row != null && typeof row === "object" && !Array.isArray(row)) {
            list.push(
                normalizeOrderCouponItem(row as Record<string, unknown>, i)
            );
        }
    });
    return { list, success: true };
}

/** POST coupon/verify 业务信封解析(与 Spring BaseResp 对齐) */
export interface CouponVerifyParseResult {
    success: boolean;
    data?: CouponVerifyResp;
    message?: string;
}

export function parseCouponVerifyResponse(
    res: AxiosResponse<unknown>
): CouponVerifyParseResult {
    const raw = res?.data;
    const fail = (message?: string): CouponVerifyParseResult => ({
        success: false,
        message,
    });
    if (raw == null || typeof raw !== "object") {
        return fail();
    }
    const peeled = peelToCouponEnvelope(raw);
    if (
        peeled == null ||
        typeof peeled !== "object" ||
        Array.isArray(peeled)
    ) {
        return fail();
    }
    const root = peeled as Record<string, unknown>;
    if (root.success === false) {
        return fail(
            typeof root.message === "string" ? root.message : undefined
        );
    }
    const inner = parseJsonIfString(root.data);
    if (
        inner == null ||
        typeof inner !== "object" ||
        Array.isArray(inner)
    ) {
        return { success: true };
    }
    const d = inner as Record<string, unknown>;
    return {
        success: true,
        data: {
            couponId: String(d.couponId ?? ""),
            orderId:
                typeof d.orderId === "number" ? d.orderId : Number(d.orderId) || 0,
            actualDeduction:
                typeof d.actualDeduction === "number"
                    ? d.actualDeduction
                    : Number(d.actualDeduction) || 0,
        },
    };
}

export interface CouponOrderInfo {
    orderId: number;
    orderCode: string;
    vehicleName: string;
    sourceNo: string;
}

/**
 * coupon/list 列表项,与后端 CouponAccountRespVO 对齐
 * status:1 待使用;2 已核销;3 已失效;4 已退回
 */
export interface CouponAccountRespVO {
    id: number;
    couponId: string;
    templateId: number;
    templateName: string;
    /** 1 固定面额券;2 阶梯满减券 */
    couponType: number;
    faceAmount: number;
    thresholdAmount: number;
    /** 1 抵扣车款;2 抵扣佣金 */
    deductionType: number;
    status: number;
    validStartTime: string;
    validEndTime: string;
    nuclearTime: string;
    nuclearOrderId: number;
    distributionType: number;
    distributionSource: string;
    createTime: string;
    description: string;
    approachingExpiry: boolean;
    orderInfo?: CouponOrderInfo;
}

/** @deprecated 请使用 CouponAccountRespVO,二者结构一致 */
export type MyCouponItem = CouponAccountRespVO;

/** POST coupon/list 请求体(与后端约定:page 从 1 起为第一页) */
export interface CouponListPageQuery {
    status: number;
    page: number;
    size: number;
}

export const COUPON_LIST_PAGE_SIZE = 10;

/** Spring Data Page 分页 data */
export interface CouponListPageData {
    totalElements?: number;
    totalPages?: number;
    first?: boolean;
    last?: boolean;
    size?: number;
    number?: number;
    numberOfElements?: number;
    empty?: boolean;
    content?: CouponAccountRespVO[];
    sort?: { empty?: boolean; sorted?: boolean; unsorted?: boolean };
    pageable?: Record<string, unknown>;
}

/** coupon/list 最外层响应 */
export interface CouponListApiEnvelope {
    code?: string;
    /** 分页结果;灰度期可能仍为数组(旧接口) */
    data?: CouponListPageData | CouponAccountRespVO[];
    success?: boolean;
    message?: string;
}

export interface CouponListPageParseResult {
    list: CouponAccountRespVO[];
    last: boolean;
    success: boolean;
    message?: string;
}

export type CouponDetail = CouponAccountRespVO;

/** GET coupon/latest-activity 响应信封 */
export interface LatestCouponActivityApiEnvelope {
    code?: string;
    data?: LatestCouponActivityResp | null;
    success?: boolean;
    message?: string;
}

/** GET coupon/latest-activity 的 data,与后端当前结构对齐 */
export interface LatestCouponActivityResp {
    id: number;
    activityId: string;
    activityName: string;
    validStartTime: string;
    validEndTime: string;
    distributionQuantity: number;
    agreementContent: string;
}

/** 解析 latest-activity:成功且有 data、且 activityName 非空时返回实体,否则 null */
export function parseLatestCouponActivityResponse(
    res: AxiosResponse<unknown>
): LatestCouponActivityResp | null {
    const envelope = res.data as
        | LatestCouponActivityApiEnvelope
        | null
        | undefined;
    if (!envelope || typeof envelope !== "object") {
        return null;
    }
    if (envelope.success === false) {
        return null;
    }
    const raw = envelope.data;
    if (raw == null || typeof raw !== "object") {
        return null;
    }
    const r = raw as unknown as Record<string, unknown>;
    const name =
        typeof r.activityName === "string" ? r.activityName.trim() : "";
    if (!name) {
        return null;
    }
    return {
        id: typeof r.id === "number" ? r.id : Number(r.id) || 0,
        activityId:
            typeof r.activityId === "string"
                ? r.activityId
                : String(r.activityId ?? ""),
        activityName: typeof r.activityName === "string" ? r.activityName : "",
        validStartTime:
            typeof r.validStartTime === "string"
                ? r.validStartTime
                : String(r.validStartTime ?? ""),
        validEndTime:
            typeof r.validEndTime === "string"
                ? r.validEndTime
                : String(r.validEndTime ?? ""),
        distributionQuantity:
            typeof r.distributionQuantity === "number"
                ? r.distributionQuantity
                : Number(r.distributionQuantity) || 0,
        agreementContent:
            typeof r.agreementContent === "string"
                ? r.agreementContent
                : String(r.agreementContent ?? ""),
    };
}

export interface CouponCountResp {
    unusedCount: number;
    verifiedCount: number;
    expiredCount: number;
}

/** GET coupon/red-dot — 是否有待通知优惠券弹窗(个人中心入口红点) */
export interface CouponRedDotResp {
    hasRedDot: boolean;
    pendingCount?: number;
}

/** 列表查询 status:1 待使用;2 已核销;3 已过期/已失效 */
export const CouponListQueryStatus = {
    UNUSED: 1,
    VERIFIED: 2,
    EXPIRED: 3,
} as const;

/** 解析 POST coupon/list 分页响应 */
export function parseCouponListPageResponse(
    res: AxiosResponse<unknown>
): CouponListPageParseResult {
    const envelope = res.data as CouponListApiEnvelope | null | undefined;
    const fail = (message?: string): CouponListPageParseResult => ({
        list: [],
        last: true,
        success: false,
        message,
    });
    if (!envelope || typeof envelope !== "object") {
        return fail();
    }
    if (envelope.success === false) {
        return fail(envelope.message);
    }
    const rawData = envelope.data;
    if (Array.isArray(rawData)) {
        return { list: rawData, last: true, success: true };
    }
    if (rawData && typeof rawData === "object") {
        const page = rawData as CouponListPageData;
        const content = Array.isArray(page.content) ? page.content : [];
        return {
            list: content,
            last: page.last === undefined ? true : Boolean(page.last),
            success: true,
        };
    }
    return { list: [], last: true, success: true };
}

// endregion

/**
 * 优惠券(Coupon)接口
 * @since 2026-04-16
 */
export class CouponController {
    /**
     * 核销优惠券
     * @param body couponId/orderId 必填;其余字段视后端兼容情况选填。
     */
    static verifyCoupon(
        axios: AxiosStatic,
        body: CouponVerifyReq
    ): Promise<AxiosResponse<CouponVerifyResp>> {
        return axios.post("coupon/verify", body);
    }

    /**
     * 获取待展示弹窗(车辆详情等场景)。
     * 当前服务端在成功返回数据时会将该用户本批次待通知弹窗批量标记为已触达,请勿在「仅探测、暂不展示」的场景调用。
     */
    static getCouponPopup(
        axios: AxiosStatic
    ): Promise<AxiosResponse<CouponPopupApiEnvelope>> {
        if (couponPopupUsesHttpMock()) {
            return Promise.resolve({
                data: MOCK_COUPON_POPUP_HTTP_BODY,
                status: 200,
                statusText: "OK",
                headers: {},
                config: {},
            } as AxiosResponse<CouponPopupApiEnvelope>);
        }
        return axios.get("coupon/popup");
    }

    /**
     * 获取订单可用优惠券列表(响应为 Spring BaseResp,请用 parseOrderCouponsResponse 解析)
     * @param orderId 订单 ID
     */
    static getOrderCoupons(
        axios: AxiosStatic,
        _orderId: number
    ): Promise<AxiosResponse<unknown>> {
        if (orderCouponsUsesHttpMock()) {
            return Promise.resolve({
                data: mockOrderCouponsEnvelope,
                status: 200,
                statusText: "OK",
                headers: {},
                config: {},
            } as AxiosResponse<unknown>);
        }
        return axios.get(`coupon/order-coupons/${_orderId}`);
    }

    /**
     * 我的优惠券列表(POST coupon/list,JSON:status / page / size;page 从 1 为第一页,与后端约定一致)
     */
    static getMyCouponList(
        axios: AxiosStatic,
        body: CouponListPageQuery
    ): Promise<AxiosResponse<CouponListApiEnvelope>> {
        return axios.post("coupon/list", body);
    }

    /**
     * 当前创建时间最新的可用优惠券活动(首页 P2 活动弹窗)
     */
    static getLatestCouponActivity(
        axios: AxiosStatic
    ): Promise<AxiosResponse<LatestCouponActivityApiEnvelope>> {
        return axios.get("coupon/latest-activity");
    }

    /**
     * 优惠券详情
     * @param couponId 优惠券实例 ID
     */
    static getCouponDetail(
        axios: AxiosStatic,
        couponId: string
    ): Promise<AxiosResponse<CouponDetail>> {
        return axios.get(`coupon/detail/${encodeURIComponent(couponId)}`);
    }

    /**
     * 各状态优惠券数量统计
     */
    static getCouponCount(
        axios: AxiosStatic
    ): Promise<AxiosResponse<CouponCountResp>> {
        return axios.get("coupon/count");
    }

    /**
     * 查询当前用户是否有待通知的优惠券弹窗(用于个人中心「优惠卡券」红点)
     */
    static getCouponRedDot(
        axios: AxiosStatic
    ): Promise<AxiosResponse<CouponRedDotResp>> {
        return axios.get("coupon/red-dot");
    }

    // region 前端扩展代码区
    // endregion
}