@extends('admin.layouts.app')

@section('title', '平台订单')
@section('page_title', '平台订单')

@section('content')
@php
    // 失败原因过长时不生成 sync_error_keyword 链接，避免 URL 过长/特殊字符破坏 query
    $SYNC_ERROR_KEYWORD_LINK_MAX_LEN = (int) config('saasshop.platform_orders.sync_error_keyword_link_max_len', 200);
    $SYNC_FAILED_REASON_TRUNCATE_LEN = (int) config('saasshop.platform_orders.sync_failed_reason_display_truncate_len', 60);

    // back 参数用于“返回上一页（保留上下文）”，但 back 本身不应再包含 back（避免无限嵌套导致 URL 膨胀）
    $selfWithoutBack = \App\Support\BackUrl::selfWithoutBack();

    $currentQuery = request()->query();
    unset($currentQuery['back']);

    // back 安全护栏（全页通用）：
    // - 仅允许站内相对路径（/ 开头）
    // - 拒绝引号/尖括号（由于本页大量 href 采用 `{!! !!}` 原样输出，必须严控注入风险）
    // - 拒绝 nested back=（避免 URL 膨胀/绕过）
    $incomingBackForLinks = (string) request()->query('back', '');
    $safeBackForLinks = \App\Support\BackUrl::sanitizeForLinks($incomingBackForLinks);

    // 金额展示：精简视图尽量更短（整数不显示 .00），full 视图保持两位小数（便于对账）
    $formatMoneyCompact = function ($amount) {
        $v = (float) $amount;
        $rounded = round($v, 2);
        if (abs($rounded - round($rounded)) < 0.00001) {
            return (string) ((int) round($rounded));
        }

        return number_format($rounded, 2, '.', '');
    };

    // 安全版“保留当前 query 并覆盖字段”的链接构造器：
    // 统一抽到 Support\BackUrl，避免 Blade 内闭包口径漂移
    // 注意：该构造器会自动按安全口径保留/移除 back。
    $safeFullUrlWithQuery = function (array $overrides = []) use ($safeBackForLinks) {
        return \App\Support\BackUrl::currentPathWithQuery($overrides, $safeBackForLinks);
    };


    // 线索上下文（从开通线索跳转而来）：用于提示“当前范围已锁定线索”，以及生成一键清除入口
    $incomingLeadId = (int) request()->query('lead_id', 0);

    // 列表视图：默认精简（避免列表过长）；view=full 展开全部列
    $isFullView = ((string) request()->query('view', '') === 'full');
    // 清除线索锁定：移除 lead_id + page，但保留其它筛选上下文，并安全透传 back。
    $clearLeadUrl = \App\Support\BackUrl::currentPathWithQuery([
        'lead_id' => null,
        'page' => null,
    ], $safeBackForLinks);

    // 新建平台订单：统一入口（页面顶部），并尽量预填当前筛选上下文，提高运营下单效率
    // - 默认携带 back 回到本页自身（剔除 back query，避免嵌套）
    // - 若当前列表已筛选站点/套餐/订阅ID/线索ID，则预填到创建页，维持闭环追溯
    $createQuery = ['back' => $selfWithoutBack];
    if (trim((string) ($filters['merchant_id'] ?? '')) !== '') {
        $createQuery['merchant_id'] = (int) ($filters['merchant_id'] ?? 0);
    }
    if (trim((string) ($filters['plan_id'] ?? '')) !== '') {
        $createQuery['plan_id'] = (int) ($filters['plan_id'] ?? 0);
    }
    if (trim((string) ($filters['site_subscription_id'] ?? '')) !== '') {
        $createQuery['site_subscription_id'] = (int) ($filters['site_subscription_id'] ?? 0);
        // 治理口径：当从订阅维度锁定进入时：
        // 1) 显式声明 require_subscription=1（统一来源口径/便于排查链路来源）
        // 2) 显式声明 order_type=renewal（语义更清晰；create 页仍会二次强制兜底）
        $createQuery['require_subscription'] = '1';
        $createQuery['order_type'] = 'renewal';
    }
    // 线索联动：若当前列表已按 lead_id 锁定，则新建订单也应带上 lead_id，维持闭环追溯
    if (trim((string) ($filters['lead_id'] ?? '')) !== '') {
        $createQuery['lead_id'] = (int) ($filters['lead_id'] ?? 0);
    }

    $createOrderUrl = '/admin/platform-orders/create?' . \Illuminate\Support\Arr::query($createQuery);

    // 订阅锁定场景：提供更贴近 SOP 的“一键续费下单”（放在页面右上角主动作区，避免用户在页面中部寻找）
    $currentSubscription = $currentSubscription ?? null;
    $renewCreateUrl = '';
    if ($currentSubscription && (int) ($currentSubscription->id ?? 0) > 0) {
        $renewRemarkPrefix = (string) config('saasshop.platform_orders.renewal_order_remark_prefix', '来自订阅：');
        $renewCreateQuery = [
            'order_type' => 'renewal',
            'site_subscription_id' => $currentSubscription->id,
            'merchant_id' => $currentSubscription->merchant_id,
            'plan_id' => $currentSubscription->plan_id,
            'require_subscription' => '1',
            'quantity' => 1,
            'remark' => $renewRemarkPrefix . $currentSubscription->subscription_no,
            'back' => $selfWithoutBack,
        ];
        if (! (int) ($currentSubscription->plan_id ?? 0)) {
            unset($renewCreateQuery['plan_id']);
        }
        $renewCreateUrl = '/admin/platform-orders/create?' . \Illuminate\Support\Arr::query($renewCreateQuery);
    }
@endphp
<div class="page-header mb-20" data-page="admin.platform_orders.index">
    <div class="page-header-main">
        <div>
            <div class="page-header-title">平台订单</div>
            <div class="page-header-subtitle">这里是总台视角的平台收费主链骨架页，当前阶段先承接套餐订购 / 续费 / 生效跟踪。本页先提供可访问列表、基础筛选与摘要卡，后续再补详情、导出、支付记录与退款轨迹。<span class="muted">（建议运营日常优先使用：待支付 / 待生效 / 可同步 / 同步失败 / 续费缺订阅 等治理集合）</span></div>
        </div>

        <div class="page-header-actions">
            @if($safeBackForLinks !== '')
                <a href="{!! $safeBackForLinks !!}" class="btn btn-secondary btn-sm">返回上一页（保留上下文）</a>
            @endif

            <a class="btn btn-sm" href="{!! $createOrderUrl !!}">新建平台订单</a>
            @if($currentSubscription && $currentSubscription->id)
                <a class="btn btn-secondary btn-sm" href="{!! $renewCreateUrl ?? '' !!}">为该订阅创建续费订单</a>
            @endif
        </div>
    </div>
</div>

@php
    $currentSubscription = $currentSubscription ?? null;
@endphp

    @if($incomingLeadId > 0)
        <div class="mt-10">
            <div class="actions">
                <span class="badge">当前线索：#{{ $incomingLeadId }}</span>
                <span class="muted muted-xs">（已按 lead_id 过滤订单集合）</span>
                <a class="btn btn-secondary btn-sm" href="{!! $clearLeadUrl !!}">清除线索筛选</a>
            </div>

            <div class="mt-10">
                <div class="muted muted-xs">线索治理入口：</div>
                @php
                    // 线索治理快捷入口：需要保留 lead_id + 其它业务上下文（merchant/plan/subscription/keyword/back），
                    // 但不应继承 syncable_only/fail_only/page 等“工具型开关”，避免从其它集合切换时产生误判。
                    $buildLeadGovernUrl = function (array $overrides) use ($safeBackForLinks) {
                        return \App\Support\BackUrl::currentPathQuickFilter(
                            ['lead_id', 'merchant_id', 'plan_id', 'site_subscription_id', 'keyword'],
                            $overrides,
                            $safeBackForLinks
                        );
                    };

                    $leadUnpaidUrl = $buildLeadGovernUrl([
                        'payment_status' => 'unpaid',
                        'status' => null,
                    ]);

                    // 待生效口径与仪表盘一致：paid + pending + sync_status=unsynced（排除同步失败等异常单）
                    $leadPaidPendingUrl = $buildLeadGovernUrl([
                        'payment_status' => 'paid',
                        'status' => 'pending',
                        'sync_status' => 'unsynced',
                    ]);

                    $leadPaidNoReceiptUrl = $buildLeadGovernUrl([
                        'payment_status' => 'paid',
                        'receipt_status' => 'none',
                    ]);
                @endphp
                @php
                    $leadBmpaUrl = $buildLeadGovernUrl([
                        'payment_status' => 'unpaid',
                        'status' => 'pending',
                    ]);

                    $leadSyncableUrl = $buildLeadGovernUrl([
                        'syncable_only' => '1',
                        'sync_status' => 'unsynced',
                        'fail_only' => null,
                    ]);

                    $leadSyncFailedUrl = $buildLeadGovernUrl([
                        'sync_status' => 'failed',
                        'syncable_only' => null,
                    ]);

                    $leadRenewalMissingSubscriptionUrl = $buildLeadGovernUrl([
                        'renewal_missing_subscription' => '1',
                    ]);
                @endphp
                <div class="mt-6 actions gap-10">
                    <a class="btn btn-secondary btn-sm" href="{!! $leadUnpaidUrl !!}">查看待支付（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadPaidPendingUrl !!}">查看待生效（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadPaidNoReceiptUrl !!}">查看已付无回执（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadBmpaUrl !!}">查看可BMPA处理（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadSyncableUrl !!}">查看可同步（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadSyncFailedUrl !!}">查看同步失败（该线索）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $leadRenewalMissingSubscriptionUrl !!}">查看续费缺订阅（该线索）</a>
                </div>
            </div>
        </div>
    @endif

    @if($currentSubscription && $currentSubscription->id)
        <div class="mt-10">
            <div class="muted">当前已锁定订阅：</div>
            <div>
                @php
                    // 订阅详情链接：附带 back 回到本页（剔除 back，避免嵌套膨胀），并统一走 BackUrl helper。
                    $subShowUrl = \App\Support\BackUrl::withBack(
                        '/admin/site-subscriptions/' . $currentSubscription->id,
                        $selfWithoutBack
                    );
                @endphp
                @php
                    // 清除订阅锁定：保留其它筛选上下文（例如 lead_id/keyword/back），但移除 site_subscription_id + page。
                    $clearSubscriptionUrl = \App\Support\BackUrl::currentPathWithQuery([
                        'site_subscription_id' => null,
                        'page' => null,
                    ], $safeBackForLinks);
                @endphp
                <a class="link" href="{!! $subShowUrl !!}">{{ $currentSubscription->subscription_no }}</a>
                <span class="muted">（订阅ID：{{ $currentSubscription->id }}）</span>
                <span class="muted">｜</span>
                <a class="muted" href="{!! $clearSubscriptionUrl !!}">取消锁定订阅</a>
            </div>
            <div class="muted muted-xs">提示：本页快捷筛选会保留该订阅ID；右上角“新建平台订单”会自动预填订阅ID。</div>

            @php
                // 锁定订阅场景下的一键续费下单入口（更贴近收费闭环 SOP）
                $renewRemarkPrefix = (string) config('saasshop.platform_orders.renewal_order_remark_prefix', '来自订阅：');
                $renewCreateQuery = [
                    'order_type' => 'renewal',
                    'site_subscription_id' => $currentSubscription->id,
                    'merchant_id' => $currentSubscription->merchant_id,
                    'plan_id' => $currentSubscription->plan_id,
                    'require_subscription' => '1',
                    'quantity' => 1,
                    'remark' => $renewRemarkPrefix . $currentSubscription->subscription_no,
                    'back' => $selfWithoutBack,
                ];
                // plan_id 允许为空：为空时不传，避免 create 默认值误选 0
                if (!(int) $currentSubscription->plan_id) {
                    unset($renewCreateQuery['plan_id']);
                }
                $renewCreateUrl = '/admin/platform-orders/create?' . \Illuminate\Support\Arr::query($renewCreateQuery);
            @endphp

            @php
                // 右上角已提供同入口，订阅锁定区不再重复渲染（避免重复 CTA 噪音）
            @endphp

            <div class="mt-10">
                <div class="muted muted-xs">订阅治理入口：</div>
                @php
                    // 订阅治理快捷入口：保留订阅上下文（site_subscription_id + 其它业务上下文），但不继承 syncable_only/fail_only/page 等工具型开关。
                    $buildSubGovernUrl = function (array $overrides) use ($safeBackForLinks) {
                        return \App\Support\BackUrl::currentPathQuickFilter(
                            // 订阅锁定治理入口：除订阅ID外，也保留时间范围（便于运营在“近7天/某段时间窗口”内治理）
                            ['merchant_id', 'plan_id', 'site_subscription_id', 'keyword', 'lead_id', 'created_from', 'created_to'],
                            $overrides,
                            $safeBackForLinks
                        );
                    };

                    $subSyncableUrl = $buildSubGovernUrl([
                        'syncable_only' => '1',
                        'sync_status' => 'unsynced',
                        'fail_only' => null,
                    ]);

                    $subSyncFailedUrl = $buildSubGovernUrl([
                        'sync_status' => 'failed',
                        'syncable_only' => null,
                        // 从 BMPA 失败上下文切回同步失败集合：清理冲突开关
                        'bmpa_failed_only' => null,
                        'bmpa_error_keyword' => null,
                    ]);

                    $subUnpaidUrl = $buildSubGovernUrl([
                        'payment_status' => 'unpaid',
                        'status' => null,
                        'syncable_only' => null,
                        'sync_status' => null,
                        'fail_only' => null,
                    ]);

                    // 待生效口径与仪表盘一致：paid + pending + sync_status=unsynced（排除同步失败等异常单）
                    $subPaidPendingUrl = $buildSubGovernUrl([
                        'payment_status' => 'paid',
                        'status' => 'pending',
                        'syncable_only' => null,
                        'sync_status' => 'unsynced',
                        'fail_only' => null,
                    ]);

                    $subPaidNoReceiptUrl = $buildSubGovernUrl([
                        'payment_status' => 'paid',
                        'receipt_status' => 'none',
                        'syncable_only' => null,
                        'sync_status' => null,
                        'fail_only' => null,
                    ]);

                    $subRenewalMissingSubscriptionUrl = $buildSubGovernUrl([
                        'renewal_missing_subscription' => '1',
                    ]);
                @endphp
                <div class="mt-6 actions gap-10">
                    <a class="btn btn-secondary btn-sm" href="{!! $subSyncableUrl !!}">查看可同步（该订阅）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $subSyncFailedUrl !!}">查看同步失败（该订阅）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $subUnpaidUrl !!}">查看待支付（该订阅）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $subPaidPendingUrl !!}">查看待生效（该订阅）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $subPaidNoReceiptUrl !!}">查看已付无回执（该订阅）</a>
                    <a class="btn btn-secondary btn-sm" href="{!! $subRenewalMissingSubscriptionUrl !!}">查看续费缺订阅（该订阅）</a>
                </div>
            </div>
        </div>
    @endif

<div class="card mb-20">
    <div class="actions-spread">
        <div>
            <h3>快捷筛选</h3>
            <div class="muted mb-10">用于运营快速定位当前需要处理的订单集合（口径基于筛选条件组合）。</div>
        </div>
        @if($incomingLeadId > 0)
            <div class="muted">
                当前锁定线索：#{{ $incomingLeadId }}
                <a class="btn btn-secondary btn-sm" href="{!! $clearLeadUrl !!}">清除</a>
            </div>
        @endif
    </div>

    @php
        // 快捷筛选：尽量保留当前筛选上下文（站点/套餐/订阅ID/keyword/lead_id/back/时间范围等），仅覆盖目标筛选字段，并清空 page。
        // 注意：不保留 syncable_only/fail_only/bmpa_processable_only 等“工具型开关”，避免用户从一个集合切到另一个集合时被残留开关影响（导致误判/空结果）。
        $buildQuickFilterUrl = function (array $overrides) use ($safeBackForLinks) {
            // 快捷筛选：仅保留上下文字段（站点/套餐/订阅ID/keyword/lead_id/时间范围/安全 back），避免把其它筛选条件叠加导致空结果。
            // 该构造器内部会强制清空 page，并且不会继承 syncable_only/fail_only/bmpa_processable_only 等“工具型开关”。
            return \App\Support\BackUrl::currentPathQuickFilter(
                ['merchant_id', 'plan_id', 'site_subscription_id', 'keyword', 'lead_id', 'created_from', 'created_to'],
                $overrides,
                $safeBackForLinks
            );
        };

        // “全部”：清空筛选，但保留 back（用于返回来源页）
        // “全部”：清空筛选，但保留安全 back（用于返回来源页）
        $allUrl = \App\Support\BackUrl::withBack('/admin/platform-orders', $safeBackForLinks);
    @endphp

    <div class="inline-links" data-role="po-quickfilter-primary-group" aria-label="平台订单主链快捷筛选组">
        <a data-role="po-quickfilter-all" href="{!! $allUrl !!}" class="muted">全部</a>
        <a data-role="po-quickfilter-unpaid" href="{!! $buildQuickFilterUrl(['payment_status' => 'unpaid']) !!}" class="muted">待支付</a>
        <a data-role="po-quickfilter-bmpa-processable" href="{!! $buildQuickFilterUrl(['bmpa_processable_only' => '1']) !!}" class="muted">可BMPA处理</a>
        <a data-role="po-quickfilter-pending-effective" href="{!! $buildQuickFilterUrl(['payment_status' => 'paid', 'status' => 'pending', 'sync_status' => 'unsynced']) !!}" class="muted">待生效</a>
        <a data-role="po-quickfilter-syncable" href="{!! $buildQuickFilterUrl(['syncable_only' => '1', 'sync_status' => 'unsynced']) !!}" class="muted">可同步订阅</a>
        <a data-role="po-quickfilter-sync-failed" href="{!! $buildQuickFilterUrl(['sync_status' => 'failed']) !!}" class="muted">同步失败</a>
        <a data-role="po-quickfilter-bmpa-failed" href="{!! $buildQuickFilterUrl(['bmpa_failed_only' => '1']) !!}" class="muted">BMPA失败</a>
        <a data-role="po-quickfilter-bmpa-success" href="{!! $buildQuickFilterUrl(['bmpa_success_only' => '1']) !!}" class="muted">BMPA成功</a>
        <a data-role="po-quickfilter-renewal-missing-sub" href="{!! $buildQuickFilterUrl(['renewal_missing_subscription' => '1']) !!}" class="muted">续费缺订阅</a>
    </div>

    <div class="inline-links mt-6" data-role="po-quickfilter-receipt-refund-group" aria-label="平台订单收付治理快捷筛选组">
        <a data-role="po-quickfilter-receipt-has" href="{!! $buildQuickFilterUrl(['receipt_status' => 'has']) !!}" class="muted">有回执</a>
        <a data-role="po-quickfilter-paid-no-receipt" href="{!! $buildQuickFilterUrl(['payment_status' => 'paid', 'receipt_status' => 'none']) !!}" class="muted">已付无回执</a>
        <a data-role="po-quickfilter-refund-has" href="{!! $buildQuickFilterUrl(['refund_status' => 'has']) !!}" class="muted">有退款</a>
        <a data-role="po-quickfilter-refund-none" href="{!! $buildQuickFilterUrl(['refund_status' => 'none']) !!}" class="muted">无退款</a>
        <a data-role="po-quickfilter-partially-refunded" href="{!! $buildQuickFilterUrl(['payment_status' => 'partially_refunded']) !!}" class="muted">部分退款</a>
        <a data-role="po-quickfilter-refunded" href="{!! $buildQuickFilterUrl(['payment_status' => 'refunded']) !!}" class="muted">已退款</a>
    </div>

    <div class="inline-links mt-6" data-role="po-quickfilter-governance-batch-group" aria-label="平台订单异常与批量治理快捷筛选组">
        <a data-role="po-quickfilter-reconcile-mismatch" href="{!! $buildQuickFilterUrl(['reconcile_mismatch' => '1']) !!}" class="muted">对账不一致</a>
        <a data-role="po-quickfilter-refund-inconsistent" href="{!! $buildQuickFilterUrl(['refund_inconsistent' => '1']) !!}" class="muted">退款不一致</a>
        <a data-role="po-quickfilter-batch-synced-24h" href="{!! $buildQuickFilterUrl(['batch_synced_24h' => '1']) !!}" class="muted">近24小时批量同步</a>
        <a data-role="po-quickfilter-batch-bmpa-24h" href="{!! $buildQuickFilterUrl(['batch_mark_paid_and_activate_24h' => '1']) !!}" class="muted">近24小时批量BMPA</a>
        <a data-role="po-quickfilter-batch-activated-24h" href="{!! $buildQuickFilterUrl(['batch_mark_activated_24h' => '1']) !!}" class="muted">近24小时批量生效</a>
    </div>
</div>

<details id="filters" class="card mb-20 collapsible filters-card" data-role="collapsible" data-storage-key="admin.platform_orders.filters" open>
    <summary class="collapsible-summary filters-summary">
        <div class="flex-between items-center">
            <h3 class="mb-0">筛选条件</h3>
            <span class="muted muted-xs">点击收起/展开</span>
        </div>
    </summary>
    <div class="collapsible-body filters-body">
        <form method="get" action="/admin/platform-orders" class="grid-3 filters-grid">
        @if($safeBackForLinks !== '')
            <input type="hidden" name="back" value="{!! $safeBackForLinks !!}">
        @endif
        <select name="status">
            <option value="">全部订单状态</option>
            @foreach(($filterOptions['statuses'] ?? []) as $value => $label)
                <option value="{{ $value }}" @selected(($filters['status'] ?? '') === $value)>{{ $label }}</option>
            @endforeach
        </select>
        <select name="payment_status">
            <option value="">全部支付状态</option>
            @foreach(($filterOptions['paymentStatuses'] ?? []) as $value => $label)
                <option value="{{ $value }}" @selected(($filters['payment_status'] ?? '') === $value)>{{ $label }}</option>
            @endforeach
        </select>
        <select name="merchant_id">
            <option value="">全部站点</option>
            @foreach(($merchants ?? []) as $m)
                <option value="{{ $m->id }}" @selected((string)($filters['merchant_id'] ?? '') === (string)$m->id)>{{ $m->name }}</option>
            @endforeach
        </select>
        <select name="plan_id">
            <option value="">全部套餐</option>
            @foreach(($plans ?? []) as $p)
                <option value="{{ $p->id }}" @selected((string)($filters['plan_id'] ?? '') === (string)$p->id)>{{ $p->name }}</option>
            @endforeach
        </select>
        <select name="sync_status">
            <option value="">全部同步状态</option>
            <option value="unsynced" @selected(($filters['sync_status'] ?? '') === 'unsynced')>未同步</option>
            <option value="synced" @selected(($filters['sync_status'] ?? '') === 'synced')>已同步</option>
            <option value="failed" @selected(($filters['sync_status'] ?? '') === 'failed')>同步失败</option>
        </select>
        <div>
            <select name="receipt_status">
                <option value="">全部回执状态</option>
                <option value="has" @selected(($filters['receipt_status'] ?? '') === 'has')>有回执</option>
                <option value="none" @selected(($filters['receipt_status'] ?? '') === 'none')>无回执（广义）</option>
            </select>
            <div class="muted muted-xs mt-6" data-role="po-receipt-status-broad-none-hint">无回执（广义）会包含未支付订单；收费闭环治理请优先使用<a class="link" data-role="po-receipt-status-broad-none-go-paid-no-receipt" aria-label="切换到已付无回执快捷筛选" href="{!! $buildQuickFilterUrl(['payment_status' => 'paid', 'receipt_status' => 'none']) !!}">已付无回执</a>快捷筛选。</div>
        </div>
        <select name="refund_status">
            <option value="">全部退款状态</option>
            <option value="has" @selected(($filters['refund_status'] ?? '') === 'has')>有退款</option>
            <option value="none" @selected(($filters['refund_status'] ?? '') === 'none')>无退款</option>
        </select>

        <input type="number" name="site_subscription_id" placeholder="订阅ID（可选）" value="{{ $filters['site_subscription_id'] ?? '' }}" class="w-140">
        <input type="date" name="created_from" data-role="po-created-from" placeholder="创建时间从（YYYY-MM-DD）" value="{{ $filters['created_from'] ?? '' }}" class="w-180">
        <input type="date" name="created_to" data-role="po-created-to" placeholder="创建时间到（YYYY-MM-DD）" value="{{ $filters['created_to'] ?? '' }}" class="w-180">
        @php
            // 运营提效：常用时间范围快捷入口（保持 query/back 安全口径；不依赖 JS）。
            // 日期范围由 Controller 注入，避免 Blade 内多次 now() 调用跨天漂移。
            $today = (string) ($createdRangeToday ?? now()->format('Y-m-d'));
            $from7d = (string) ($createdRangeFrom7d ?? now()->subDays(6)->format('Y-m-d'));
            $from30d = (string) ($createdRangeFrom30d ?? now()->subDays(29)->format('Y-m-d'));

            $createdRangeTodayUrl = $safeFullUrlWithQuery([
                'created_from' => $today,
                'created_to' => $today,
                'page' => null,
            ]);
            $createdRange7dUrl = $safeFullUrlWithQuery([
                'created_from' => $from7d,
                'created_to' => $today,
                'page' => null,
            ]);
            $createdRange30dUrl = $safeFullUrlWithQuery([
                'created_from' => $from30d,
                'created_to' => $today,
                'page' => null,
            ]);
            $createdRangeClearUrl = $safeFullUrlWithQuery([
                'created_from' => null,
                'created_to' => null,
                'page' => null,
            ]);
        @endphp
        <span class="muted muted-xs" data-role="platform-orders-created-range-quick-links">
            时间快捷：
            <a class="link" data-role="po-created-range-today" href="{!! $createdRangeTodayUrl !!}">今天</a>
            <span class="muted">｜</span>
            <a class="link" data-role="po-created-range-7d" href="{!! $createdRange7dUrl !!}">近7天</a>
            <span class="muted">｜</span>
            <a class="link" data-role="po-created-range-30d" href="{!! $createdRange30dUrl !!}">近30天</a>
            <span class="muted">｜</span>
            <a class="link" data-role="po-created-range-clear" href="{!! $createdRangeClearUrl !!}">清空</a>
        </span>
        <label class="form-inline-row">
            <input type="checkbox" name="fail_only" value="1" @checked(($filters['fail_only'] ?? '') === '1')>
            <span>只看同步失败</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="bmpa_failed_only" value="1" @checked(($filters['bmpa_failed_only'] ?? '') === '1')>
            <span>只看批量标记支付失败</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="bmpa_success_only" value="1" @checked(($filters['bmpa_success_only'] ?? '') === '1')>
            <span>只看批量标记支付成功</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="synced_only" value="1" @checked(($filters['synced_only'] ?? '') === '1')>
            <span>只看已同步</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="syncable_only" value="1" @checked(($filters['syncable_only'] ?? '') === '1')>
            <span>只看可同步</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="bmpa_processable_only" value="1" @checked(($filters['bmpa_processable_only'] ?? '') === '1')>
            <span>只看可BMPA处理</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="renewal_missing_subscription" value="1" @checked(($filters['renewal_missing_subscription'] ?? '') === '1')>
            <span>只看续费缺订阅</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="batch_synced_24h" value="1" @checked(($filters['batch_synced_24h'] ?? '') === '1')>
            <span>最近24小时批量同步过</span>
        </label>
        <input type="text" name="batch_activation_run_id" placeholder="批次号 BAS run_id（可选）" value="{{ $filters['batch_activation_run_id'] ?? '' }}" class="w-200">
        <input type="text" name="batch_bmpa_run_id" placeholder="批次号 BMPA run_id（可选）" value="{{ $filters['batch_bmpa_run_id'] ?? '' }}" class="w-200">
        <label class="form-inline-row">
            <input type="checkbox" name="batch_mark_paid_and_activate_24h" value="1" @checked(($filters['batch_mark_paid_and_activate_24h'] ?? '') === '1')>
            <span>最近24小时批量BMPA过</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="batch_mark_activated_24h" value="1" @checked(($filters['batch_mark_activated_24h'] ?? '') === '1')>
            <span>最近24小时批量生效过</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="reconcile_mismatch" value="1" @checked(($filters['reconcile_mismatch'] ?? '') === '1')>
            <span>只看对账不一致（回执总额≠已付金额）</span>
        </label>
        <label class="form-inline-row">
            <input type="checkbox" name="refund_inconsistent" value="1" @checked(($filters['refund_inconsistent'] ?? '') === '1')>
            <span>只看退款不一致（状态 vs 退款总额）</span>
        </label>
        <input type="text" name="keyword" placeholder="关键词：订单号/站点/订阅号" value="{{ $filters['keyword'] ?? '' }}">
        <input type="number" name="lead_id" placeholder="线索ID（可选）" value="{{ $filters['lead_id'] ?? '' }}" class="w-140">
        <input type="text" name="sync_error_keyword" placeholder="同步失败原因关键词（可选）" value="{{ $filters['sync_error_keyword'] ?? '' }}">
        <input type="text" name="bmpa_error_keyword" placeholder="批量标记支付并生效失败原因关键词（可选）" value="{{ $filters['bmpa_error_keyword'] ?? '' }}">
        <div>
            <button class="btn btn-sm" type="submit">应用筛选</button>
        </div>
    </form>
    </div>
</details>

@php
    $batchActivationRunId = trim((string) ($filters['batch_activation_run_id'] ?? ''));
@endphp
@if($batchActivationRunId !== '')
    @php
        $runGoFailedUrl = $buildQuickFilterUrl([
            'batch_activation_run_id' => $batchActivationRunId,
            'sync_status' => 'failed',
            'page' => null,
        ]);
        $runGoUnsyncedUrl = $buildQuickFilterUrl([
            'batch_activation_run_id' => $batchActivationRunId,
            'sync_status' => 'unsynced',
            'page' => null,
        ]);
        $runGoSyncableUrl = $buildQuickFilterUrl([
            'batch_activation_run_id' => $batchActivationRunId,
            'sync_status' => 'unsynced',
            'syncable_only' => '1',
            'page' => null,
        ]);

        $runGoSuccessUrl = $buildQuickFilterUrl([
            'batch_activation_run_id' => $batchActivationRunId,
            'sync_status' => 'synced',
            'page' => null,
        ]);
    @endphp
    @php
        $runGoAllUrl = $buildQuickFilterUrl([
            'batch_activation_run_id' => $batchActivationRunId,
            'page' => null,
        ]);
    @endphp
    <div class="card mb-20 governance-block" data-role="batch-activation-run-id-badge">
        <div class="muted governance-block-title"><strong>当前 BAS 批次筛选</strong></div>
        <div class="muted governance-block-body">
            <div>
                当前 BAS run_id：<strong>{{ $batchActivationRunId }}</strong>
                <button type="button" class="btn btn-secondary btn-sm" data-action="copy-text" data-copy-text="{{ $batchActivationRunId }}" data-copy-label="BAS run_id">复制 run_id</button>
                @php
                    $basBatchReviewUrl = \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                        'type' => 'bas',
                        'run_id' => $batchActivationRunId,
                    ]), $selfWithoutBack);
                @endphp
                <a class="btn btn-secondary btn-sm" href="{!! $basBatchReviewUrl !!}">查看批次复盘</a>
                <span class="muted">｜</span>
                <a class="btn btn-secondary btn-sm" href="{!! $safeFullUrlWithQuery(['batch_activation_run_id' => null, 'page' => null]) !!}">清除 BAS 批次筛选</a>
            </div>
            <div class="mt-6">
                <span class="muted">快速查看：</span>
                <a class="link" href="{!! $runGoAllUrl !!}">本批次全部</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $runGoFailedUrl !!}">本批次失败</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $runGoSuccessUrl !!}">本批次成功</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $runGoUnsyncedUrl !!}">本批次未同步</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $runGoSyncableUrl !!}">本批次可同步重试</a>
            </div>
        </div>
    </div>
@endif

@php
    $batchBmpaRunId = trim((string) ($filters['batch_bmpa_run_id'] ?? ''));
@endphp
@if($batchBmpaRunId !== '')
    @php
        $bmpaGoFailedUrl = $buildQuickFilterUrl([
            'batch_bmpa_run_id' => $batchBmpaRunId,
            'bmpa_failed_only' => '1',
            'page' => null,
        ]);

        $bmpaGoAllUrl = $buildQuickFilterUrl([
            'batch_bmpa_run_id' => $batchBmpaRunId,
            'page' => null,
        ]);

        $bmpaGoProcessableUrl = $buildQuickFilterUrl([
            'batch_bmpa_run_id' => $batchBmpaRunId,
            'bmpa_processable_only' => '1',
            'page' => null,
        ]);

        $bmpaGoSuccessUrl = $buildQuickFilterUrl([
            'batch_bmpa_run_id' => $batchBmpaRunId,
            'bmpa_success_only' => '1',
            'page' => null,
        ]);
    @endphp
    <div class="card mb-20 governance-block" data-role="batch-bmpa-run-id-badge">
        <div class="muted governance-block-title"><strong>当前 BMPA 批次筛选</strong></div>
        <div class="muted governance-block-body">
            <div>
                当前 BMPA run_id：<strong>{{ $batchBmpaRunId }}</strong>
                <button type="button" class="btn btn-secondary btn-sm" data-action="copy-text" data-copy-text="{{ $batchBmpaRunId }}" data-copy-label="BMPA run_id">复制 run_id</button>
                @php
                    $bmpaBatchReviewUrl = \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                        'type' => 'bmpa',
                        'run_id' => $batchBmpaRunId,
                    ]), $selfWithoutBack);
                @endphp
                <a class="btn btn-secondary btn-sm" href="{!! $bmpaBatchReviewUrl !!}">查看批次复盘</a>
                <span class="muted">｜</span>
                <a class="btn btn-secondary btn-sm" href="{!! $safeFullUrlWithQuery(['batch_bmpa_run_id' => null, 'page' => null]) !!}">清除 BMPA 批次筛选</a>
            </div>
            <div class="mt-6">
                <span class="muted">快速查看：</span>
                <a class="link" href="{!! $bmpaGoAllUrl !!}">本批次全部</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $bmpaGoFailedUrl !!}">本批次 BMPA 失败</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $bmpaGoSuccessUrl !!}">本批次 BMPA 成功</a>
                <span class="muted">｜</span>
                <a class="link" href="{!! $bmpaGoProcessableUrl !!}">本批次可再次尝试（可BMPA处理）</a>
            </div>
        </div>
    </div>
@endif

<div class="grid-3 mb-20">
    <div class="card">
        <h3>平台订单总数</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-total-orders',
                'href' => $safeFullUrlWithQuery(['page' => null]),
                'label' => $summaryStats['total_orders'] ?? 0,
            ])
        </div>
    </div>
    <div class="card">
        <h3>已支付 / 已生效</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_pair', [
                'leftRole' => 'po-summary-link-paid-orders',
                'leftHref' => $safeFullUrlWithQuery(['payment_status' => 'paid', 'page' => null]),
                'leftLabel' => $summaryStats['paid_orders'] ?? 0,
                'rightRole' => 'po-summary-link-activated-orders',
                'rightHref' => $safeFullUrlWithQuery(['status' => 'activated', 'page' => null]),
                'rightLabel' => $summaryStats['activated_orders'] ?? 0,
                'separator' => '/',
                'separatorClass' => '',
            ])
        </div>
    </div>
    <div class="card">
        <h3>已同步 / 未同步</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_pair', [
                'leftRole' => 'po-summary-link-synced-orders',
                'leftHref' => $safeFullUrlWithQuery(['sync_status' => 'synced', 'page' => null]),
                'leftLabel' => $summaryStats['synced_orders'] ?? 0,
                'rightRole' => 'po-summary-link-unsynced-orders',
                'rightHref' => $safeFullUrlWithQuery(['sync_status' => 'unsynced', 'page' => null]),
                'rightLabel' => $summaryStats['unsynced_orders'] ?? 0,
                'separator' => '/',
                'separatorClass' => '',
            ])
        </div>
    </div>
    <div class="card">
        <h3>同步失败数</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-sync-failed-orders',
                'href' => $safeFullUrlWithQuery(['sync_status' => 'failed', 'page' => null]),
                'label' => $summaryStats['failed_sync_orders'] ?? 0,
            ])
        </div>
    </div>
    <div class="card">
        <h3>BMPA 成功 / 失败</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_pair', [
                'leftRole' => 'po-summary-link-bmpa-success-orders',
                'leftHref' => $safeFullUrlWithQuery(['bmpa_success_only' => '1', 'fail_only' => null, 'page' => null]),
                'leftLabel' => $summaryStats['bmpa_success_orders'] ?? 0,
                'rightRole' => 'po-summary-link-bmpa-failed-orders',
                'rightHref' => $safeFullUrlWithQuery(['bmpa_failed_only' => '1', 'fail_only' => null, 'page' => null]),
                'rightLabel' => $summaryStats['bmpa_failed_orders'] ?? 0,
                'separator' => '/',
                'separatorClass' => 'muted',
            ])
        </div>
        <div class="muted muted-xs">成功口径：存在 run_id 且无 error.message；失败口径：meta 失败标记</div>
    </div>
    <div class="card">
        <h3>可同步订单</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-syncable-orders',
                'href' => $safeFullUrlWithQuery(['syncable_only' => '1', 'sync_status' => 'unsynced', 'fail_only' => null, 'page' => null]),
                'label' => $summaryStats['syncable_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">已支付 + 已生效 + 未同步（续费单需已绑定订阅）</div>
    </div>
    <div class="card">
        <h3>续费缺订阅</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-renewal-missing-sub-orders',
                'href' => $safeFullUrlWithQuery(['renewal_missing_subscription' => '1', 'page' => null]),
                'label' => $summaryStats['renewal_missing_subscription_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">renewal + site_subscription_id 为空（需治理：去订单详情补订阅/核对来源）</div>
    </div>

    <div class="card">
        <h3>近24小时批量同步</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-batch-synced-24h-orders',
                'href' => $safeFullUrlWithQuery(['batch_synced_24h' => '1', 'page' => null]),
                'label' => $summaryStats['batch_synced_24h_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">基于 meta.batch_activation.at</div>
    </div>
    <div class="card">
        <h3>近24小时批量BMPA</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-batch-bmpa-24h-orders',
                'href' => $safeFullUrlWithQuery(['batch_mark_paid_and_activate_24h' => '1', 'page' => null]),
                'label' => $summaryStats['batch_mark_paid_and_activate_24h_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">基于 meta.batch_mark_paid_and_activate.at</div>
    </div>
    <div class="card">
        <h3>近24小时批量生效</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-batch-activated-24h-orders',
                'href' => $safeFullUrlWithQuery(['batch_mark_activated_24h' => '1', 'page' => null]),
                'label' => $summaryStats['batch_mark_activated_24h_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">基于 meta.batch_mark_activated.at</div>
    </div>
    <div class="card">
        <h3>部分退款 / 已退款</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_pair', [
                'leftRole' => 'po-summary-link-partially-refunded-orders',
                'leftHref' => $safeFullUrlWithQuery(['payment_status' => 'partially_refunded', 'page' => null]),
                'leftLabel' => $summaryStats['partially_refunded_orders'] ?? 0,
                'rightRole' => 'po-summary-link-refunded-orders',
                'rightHref' => $safeFullUrlWithQuery(['payment_status' => 'refunded', 'page' => null]),
                'rightLabel' => $summaryStats['refunded_orders'] ?? 0,
                'separator' => '/',
                'separatorClass' => '',
            ])
        </div>
    </div>
    <div class="card">
        <h3>退款总额</h3>
        <div class="metric-number">¥{{ number_format((float) ($summaryStats['total_refunded_amount'] ?? 0), 2) }}</div>
        <div class="muted muted-xs">基于 meta.refund_summary.total_amount（缺省回退汇总）</div>
        <div class="muted muted-xs">
            @include('admin.platform_orders._summary_text_link', [
                'role' => 'po-summary-link-view-refund-orders',
                'href' => $safeFullUrlWithQuery(['refund_status' => 'has', 'page' => null]),
                'label' => '查看有退款订单',
            ])
        </div>
    </div>
    <div class="card">
        <h3>有退款订单 / 无退款订单</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_pair', [
                'leftRole' => 'po-summary-link-refund-orders',
                'leftHref' => $safeFullUrlWithQuery(['refund_status' => 'has', 'page' => null]),
                'leftLabel' => $summaryStats['refund_orders'] ?? 0,
                'rightRole' => 'po-summary-link-no-refund-orders',
                'rightHref' => $safeFullUrlWithQuery(['refund_status' => 'none', 'page' => null]),
                'rightLabel' => $summaryStats['no_refund_orders'] ?? 0,
                'separator' => '/',
                'separatorClass' => '',
            ])
        </div>
        <div class="muted muted-xs">口径：refund_summary.total_amount 存在或 refund_receipts 有记录</div>
    </div>
    <div class="card">
        <h3>有回执订单 / 回执总额</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-receipt-orders',
                'href' => $safeFullUrlWithQuery(['receipt_status' => 'has', 'page' => null]),
                'label' => $summaryStats['receipt_orders'] ?? 0,
            ])
            / ¥{{ number_format((float) ($summaryStats['total_receipt_amount'] ?? 0), 2) }}
        </div>
        <div class="muted muted-xs">有回执口径：payment_summary.total_amount 存在或 payment_receipts 有记录</div>
        <div class="muted muted-xs">
            @include('admin.platform_orders._summary_text_link', [
                'role' => 'po-summary-link-view-no-receipt-orders',
                'href' => $safeFullUrlWithQuery(['payment_status' => 'paid', 'receipt_status' => 'none', 'page' => null]),
                'label' => '查看已付无回执订单',
            ])
        </div>
    </div>
    <div class="card">
        <h3>已付无回执订单</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-no-receipt-orders',
                'href' => $safeFullUrlWithQuery(['payment_status' => 'paid', 'receipt_status' => 'none', 'page' => null]),
                'label' => $summaryStats['no_receipt_orders'] ?? 0,
            ])
        </div>
        <div class="muted muted-xs">已支付且无 payment_summary / payment_receipts，优先进入补回执治理集合</div>
        <div class="muted muted-xs">
            @include('admin.platform_orders._summary_text_link', [
                'role' => 'po-summary-link-view-receipt-orders',
                'href' => $safeFullUrlWithQuery(['receipt_status' => 'has', 'page' => null]),
                'label' => '查看有回执订单',
            ])
        </div>
    </div>
    <div class="card">
        <h3>治理顺序建议（SOP）</h3>
        <div class="muted muted-xs">
            建议按以下顺序治理当前筛选集合：
            <ol class="muted-muted-xs list-indent">
                <li>先处理 @include('admin.platform_orders._summary_text_link', [
                    'role' => 'po-sop-link-reconcile-mismatch',
                    'href' => $safeFullUrlWithQuery(['reconcile_mismatch' => '1', 'page' => null]),
                    'label' => '对账不一致',
                ])：优先补齐支付回执，并核对回执渠道/金额，确保回执总额与已付金额一致。</li>
                <li>再处理 @include('admin.platform_orders._summary_text_link', [
                    'role' => 'po-sop-link-refund-inconsistent',
                    'href' => $safeFullUrlWithQuery(['refund_inconsistent' => '1', 'page' => null]),
                    'label' => '退款不一致',
                ])：优先补齐退款回执/核对退款轨迹/修正退款状态（带审计）。</li>
                <li>最后处理 @include('admin.platform_orders._summary_text_link', [
                    'role' => 'po-sop-link-syncable',
                    'href' => $safeFullUrlWithQuery(['syncable_only' => '1', 'sync_status' => 'unsynced', 'page' => null]),
                    'label' => '可同步',
                ])：确认无对账/退款异常、无同步失败原因后，再批量同步订阅。</li>
            </ol>
        </div>
        <div class="muted governance-block-footnote">说明：本页“批量同步/批量生效/清理失败标记”等工具动作会透传当前筛选条件；建议先缩小到明确集合再操作。</div>
        <div class="muted governance-block-footnote">提示：如果你是从其它页面（例如订阅详情/套餐页）通过 back 进入本页，建议优先用上方的「返回上一页」入口回到来源页，再继续操作。</div>
    </div>

    <div class="card">
        <h3>对账差额</h3>
        @php $delta = (float) ($summaryStats['reconciliation_delta'] ?? 0); @endphp
        <div class="metric-number">¥{{ number_format($delta, 2) }}</div>
        <div class="muted muted-xs">{{ $summaryStats['reconciliation_delta_note'] ?? '回执总额 - 订单已付总额' }}（当前筛选范围）</div>
        <div class="muted muted-xs">对账不一致订单：
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-reconcile-mismatch-orders',
                'href' => $safeFullUrlWithQuery(['reconcile_mismatch' => '1', 'page' => null]),
                'label' => $summaryStats['reconcile_mismatch_orders'] ?? 0,
            ])
        </div>
        @php $tol = (float) config('saasshop.amounts.tolerance', 0.01); @endphp
        <div class="muted muted-xs">当前容差：¥{{ number_format($tol, 2) }}</div>
        @if(abs($delta) >= $tol)
            <div class="muted text-danger mt-6">提示：差额超过容差，可能存在回执金额与订单金额不一致的订单。</div>
        @endif
    </div>
    <div class="card">
        <h3>退款不一致订单</h3>
        <div class="metric-number">
            @include('admin.platform_orders._summary_metric_link', [
                'role' => 'po-summary-link-refund-inconsistent-orders',
                'href' => $safeFullUrlWithQuery(['refund_inconsistent' => '1', 'page' => null]),
                'label' => $summaryStats['refund_inconsistent_orders'] ?? 0,
            ])
        </div>
        @php $refundTol = (float) config('saasshop.amounts.tolerance', 0.01); @endphp
        <div class="muted muted-xs">口径：状态=refunded 但退款总额 + 容差 < 已付；或状态!=refunded 且退款总额 >= 已付 + 容差</div>
        <div class="muted muted-xs">当前容差：¥{{ number_format($refundTol, 2) }}</div>
    </div>
    <div class="card">
        <h3>同步失败原因 TOP5</h3>
        @php $failedReasonStats = $failedReasonStats ?? []; @endphp
        @if(count($failedReasonStats) > 0)
            <div class="muted mt-6">
                @foreach($failedReasonStats as $item)
                    @php
                        $reason = (string) ($item['reason'] ?? '');
                        $count = (int) ($item['count'] ?? 0);
                    @endphp
                    <div>
                        @if($reason !== '' && $reason !== '（空）')
                            @php
                                $reasonText = mb_substr($reason, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN);
                                $reasonTooLong = mb_strlen($reason) > $SYNC_ERROR_KEYWORD_LINK_MAX_LEN;
                            @endphp

                            @if($reasonTooLong)
                                <span class="muted" title="{{ $reason }}">{{ $reasonText }}</span>
                                <span class="muted">（{{ $count }}）</span>
                                <span class="muted">｜</span>
                                <span class="muted">原因过长，请复制到筛选框</span>
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['sync_status' => 'failed', 'page' => null]),
                                    'label' => '进入同步失败集合',
                                ])
                            @else
                                <a class="link" title="{{ $reason }}" href="{!! $safeFullUrlWithQuery(['sync_error_keyword' => $reason, 'sync_status' => 'failed', 'page' => null]) !!}">{{ $reasonText }}</a>
                                <span class="muted">（{{ $count }}）</span>
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['sync_error_keyword' => $reason, 'sync_status' => 'unsynced', 'syncable_only' => '1', 'fail_only' => null, 'page' => null]),
                                    'label' => '切到可同步重试',
                                ])
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['sync_error_keyword' => $reason, 'sync_status' => 'failed', 'page' => null]),
                                    'label' => '进入失败集合',
                                ])
                            @endif
                        @else
                            <span class="muted">（空原因）</span>
                            <span class="muted">（{{ $count }}）</span>
                        @endif
                    </div>
                @endforeach
            </div>
        @else
            <div class="muted">暂无失败原因聚合数据</div>
        @endif
    </div>

    <div class="card">
        <h3>批量标记支付并生效失败原因 TOP5</h3>
        @php $bmpaFailedReasonStats = $bmpaFailedReasonStats ?? []; @endphp
        @if(count($bmpaFailedReasonStats) > 0)
            <div class="muted mt-6">
                @foreach($bmpaFailedReasonStats as $item)
                    @php
                        $reason = (string) ($item['reason'] ?? '');
                        $count = (int) ($item['count'] ?? 0);
                    @endphp
                    <div>
                        @if($reason !== '' && $reason !== '（空）')
                            @php
                                $reasonText = mb_substr($reason, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN);
                                $reasonTooLong = mb_strlen($reason) > $SYNC_ERROR_KEYWORD_LINK_MAX_LEN;
                            @endphp

                            @if($reasonTooLong)
                                <span class="muted" title="{{ $reason }}">{{ $reasonText }}</span>
                                <span class="muted">（{{ $count }}）</span>
                                <span class="muted">｜</span>
                                <span class="muted">原因过长，请复制到筛选框</span>
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['bmpa_failed_only' => '1', 'bmpa_error_keyword' => null, 'page' => null]),
                                    'label' => '进入失败集合',
                                ])
                            @else
                                <a class="link" title="{{ $reason }}" href="{!! $safeFullUrlWithQuery(['bmpa_failed_only' => '1', 'bmpa_error_keyword' => $reason, 'page' => null]) !!}">{{ $reasonText }}</a>
                                <span class="muted">（{{ $count }}）</span>
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['bmpa_error_keyword' => $reason, 'bmpa_processable_only' => '1', 'bmpa_failed_only' => null, 'page' => null]),
                                    'label' => '切到可处理集合重试',
                                ])
                                <span class="muted">｜</span>
                                @include('admin.platform_orders._summary_text_link', [
                                    'href' => $safeFullUrlWithQuery(['bmpa_failed_only' => '1', 'bmpa_error_keyword' => $reason, 'page' => null]),
                                    'label' => '进入失败集合',
                                ])
                            @endif
                        @else
                            <span class="muted">（空原因）</span>
                            <span class="muted">（{{ $count }}）</span>
                        @endif
                    </div>
                @endforeach
            </div>
        @else
            <div class="muted">暂无失败原因聚合数据</div>
        @endif
        <div class="muted muted-xs mt-6">提示：建议先点原因进入失败集合，完成回执/退款治理后，再切到「可BMPA处理」集合重试。</div>
    </div>
</div>

<div class="card mb-20">
    <h3>工具</h3>
    <div class="muted mb-10">清除仅影响订单 meta 中的失败标记，不改变订单/订阅状态。</div>

    @php
        $hasReconcileMismatchFilter = (($filters['reconcile_mismatch'] ?? '') === '1');
        $hasRefundInconsistentFilter = (($filters['refund_inconsistent'] ?? '') === '1');
        $hasSyncableOnlyFilter = (($filters['syncable_only'] ?? '') === '1');
        $hasSyncFailedFilter = (($filters['sync_status'] ?? '') === 'failed')
            || trim((string) ($filters['sync_error_keyword'] ?? '')) !== ''
            || (($filters['fail_only'] ?? '') === '1');
        $hasBmpaFailedFilter = ((($filters['bmpa_failed_only'] ?? '') === '1')
            || trim((string) ($filters['bmpa_error_keyword'] ?? '')) !== '');
    @endphp

    @if($hasReconcileMismatchFilter || $hasRefundInconsistentFilter)
        <div class="card governance-block mb-10">
            <div class="muted text-danger governance-block-title"><strong>工具动作治理提示</strong></div>
            <div class="muted governance-block-body">
                当前筛选包含
                @if($hasReconcileMismatchFilter)
                    @include('admin.platform_orders._summary_text_link', [
                        'href' => $safeFullUrlWithQuery(['reconcile_mismatch' => '1', 'page' => null]),
                        'label' => '对账不一致',
                    ])
                @endif
                @if($hasReconcileMismatchFilter && $hasRefundInconsistentFilter)
                    <span class="muted">与</span>
                @endif
                @if($hasRefundInconsistentFilter)
                    @include('admin.platform_orders._summary_text_link', [
                        'href' => $safeFullUrlWithQuery(['refund_inconsistent' => '1', 'page' => null]),
                        'label' => '退款不一致',
                    ])
                @endif
                。建议先完成金额/状态治理（补回执/核对退款/修正状态）后，再执行批量同步订阅等工具动作。
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._tool_anchor_button', [
                        'href' => '#batch-activate-subscriptions',
                        'label' => '定位到批量同步订阅工具',
                        'ariaLabel' => '定位到批量同步订阅工具',
                    ])
                </div>
            </div>
        </div>

        @if($hasSyncableOnlyFilter)
            <div class="card governance-block mb-10">
                <div class="muted text-danger governance-block-title"><strong>提示</strong></div>
                <div class="muted governance-block-body">
                    注意：当前同时勾选了「只看可同步」—— 这类订单会被批量同步订阅命中。若仍存在对账/退款异常，建议先进入治理集合处理完毕，再回到可同步集合执行批量同步。
                    <div class="mt-6 actions gap-10">
                        @include('admin.platform_orders._summary_text_link', [
                            'class' => 'btn btn-secondary btn-sm',
                            'href' => $safeFullUrlWithQuery(['syncable_only' => null, 'page' => null]),
                            'label' => '先去治理（取消只看可同步）',
                        ])
                    </div>
                </div>
            </div>
        @endif
    @endif

    @if((($filters['receipt_status'] ?? '') === 'none') && $hasSyncableOnlyFilter)
        <div class="card governance-block mb-10" data-role="po-tools-paid-no-receipt-hint" aria-label="已付无回执治理提示">
            <div class="muted text-danger governance-block-title"><strong>已付无回执提示</strong></div>
            <div class="muted governance-block-body">
                当前集合为「已付无回执」且已勾选「只看可同步」。为保证收费闭环可治理，建议先补齐支付回执留痕，再执行批量同步订阅。
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._tool_anchor_button', [
                        'href' => '#batch-activate-subscriptions',
                        'label' => '定位到批量同步订阅工具',
                        'ariaLabel' => '定位到批量同步订阅工具',
                    ])
                </div>
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._summary_text_link', [
                        'role' => 'po-tools-paid-no-receipt-go-receipt-has',
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery(['receipt_status' => 'has', 'page' => null]),
                        'label' => '切到有回执集合',
                        'ariaLabel' => '切到有回执集合',
                    ])
                    @include('admin.platform_orders._summary_text_link', [
                        'role' => 'po-tools-paid-no-receipt-clear-syncable',
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery(['syncable_only' => null, 'page' => null]),
                        'label' => '取消只看可同步（先治理）',
                        'ariaLabel' => '取消只看可同步（先治理）',
                    ])
                </div>
                <div class="muted governance-block-footnote" data-role="po-tools-paid-no-receipt-footnote" aria-label="已付无回执治理优先级说明">收费闭环优先：先补回执，再推进同步。</div>
            </div>
        </div>
    @endif

    @if($hasSyncFailedFilter)
        <div class="card governance-block mb-10">
            <div class="muted text-danger governance-block-title"><strong>同步失败治理提示</strong></div>
            <div class="muted governance-block-body">
                当前筛选包含「同步失败/失败原因」范围。建议先治理失败原因（修复数据或重试同步），再执行批量同步订阅等工具动作。
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._tool_anchor_button', [
                        'href' => '#batch-activate-subscriptions',
                        'label' => '定位到批量同步订阅工具',
                        'ariaLabel' => '定位到批量同步订阅工具',
                    ])
                </div>
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._summary_text_link', [
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery([
                            'sync_status' => 'failed',
                            // 进入失败集合：不应残留“只看可同步”等互斥开关
                            'syncable_only' => null,
                            'synced_only' => null,
                            'fail_only' => null,
                            // 从 BMPA 失败上下文切回同步失败集合时，需清理冲突开关
                            'bmpa_failed_only' => null,
                            'bmpa_error_keyword' => null,
                            'page' => null,
                        ]),
                        'label' => '进入同步失败集合',
                    ])
                    @include('admin.platform_orders._summary_text_link', [
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery(['syncable_only' => '1', 'sync_status' => 'unsynced', 'fail_only' => null, 'page' => null]),
                        'label' => '切到只看可同步（用于批量重试同步）',
                    ])
                </div>
            </div>
        </div>
    @endif

    @if($hasBmpaFailedFilter)
        <div class="card governance-block mb-10">
            <div class="muted text-danger governance-block-title"><strong>BMPA 失败治理提示</strong></div>
            <div class="muted governance-block-body">
                当前筛选包含「批量标记支付并生效失败/失败原因」范围。建议先补齐回执/核对退款/修正状态后，再切到「可BMPA处理」集合重试批量标记支付。
                <div class="mt-6 actions gap-10">
                    @include('admin.platform_orders._summary_text_link', [
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery([
                            'bmpa_failed_only' => '1',
                            // 进入失败集合：不应残留“只看可同步”等互斥开关
                            'syncable_only' => null,
                            'synced_only' => null,
                            // 从同步失败上下文切到 BMPA 失败集合时，需清理冲突开关
                            'fail_only' => null,
                            'sync_status' => null,
                            'sync_error_keyword' => null,
                            'page' => null,
                        ]),
                        'label' => '进入批量标记支付失败集合',
                    ])
                    @include('admin.platform_orders._summary_text_link', [
                        'class' => 'btn btn-secondary btn-sm',
                        'href' => $safeFullUrlWithQuery(['bmpa_processable_only' => '1', 'bmpa_failed_only' => null, 'page' => null]),
                        'label' => '切到可BMPA处理（用于重试）',
                    ])
                </div>
            </div>
        </div>
    @endif

    @php
        // 工具治理口径：统一只计算一次，避免多处重复调用 forIndex() 导致口径漂移/维护成本上升。
        $toolGuards = $toolGuards ?? \App\Support\PlatformOrderToolsGuard::forIndex((array) ($filters ?? []));
    @endphp

    <div class="tool-grid">
    <div class="tool-group focus-box">
        <div class="tool-group-title">导出</div>
        <form method="get" action="/admin/platform-orders/export" class="mb-0">
                <input type="hidden" name="download" value="1">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])

                <label class="form-inline-row mb-8">
                    <input type="checkbox" name="include_meta" value="1">
                    <span>包含原始 meta(JSON)（用于排障）</span>
                </label>

                <div class="mt-6">
                    <button class="btn btn-secondary btn-sm" type="submit">导出 CSV</button>
                </div>
            </form>
    </div>

    <div class="tool-group focus-box" id="batch-activate-subscriptions">
        <div class="tool-group-title">批量同步订阅</div>
        @php
            $batchActivateBlocked = (bool) ($toolGuards['batch_activate_subscriptions']['blocked'] ?? false);
            $batchActivateBlockedReason = (string) ($toolGuards['batch_activate_subscriptions']['reason'] ?? '');
        @endphp
        <form method="post" action="/admin/platform-orders/batch-activate-subscriptions" data-action="disable-on-submit" onsubmit="return confirm('确认批量同步当前筛选范围内“可同步”的订单？（仅处理：已支付+已生效+未同步）');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="filtered">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])

                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>

                <div class="muted mb-8">提示：建议先勾选筛选条件「只看可同步」，再执行批量同步。</div>
                <div class="mt-6">
                    <button class="btn btn-sm" type="submit" @disabled($batchActivateBlocked) title="{{ $batchActivateBlockedReason }}">批量同步订阅（当前筛选范围）</button>
                    @if($batchActivateBlocked)
                        @php
                            // 提效：被阻断时给一键跳转到「可同步订阅集合」（口径：syncable_only=1 + sync_status=unsynced）。
                            $goSyncableUrl = $buildQuickFilterUrl([
                                'syncable_only' => '1',
                                'sync_status' => 'unsynced',
                            ]);
                        @endphp
                        @include('admin.components.tool_blocked_hint', [
                            'dataRole' => 'batch-activate-subscriptions-blocked-hint',
                            'reason' => $batchActivateBlockedReason,
                            'actions' => [
                                ['label' => '切到可同步订阅集合', 'url' => $goSyncableUrl],
                            ],
                        ])
                    @endif
                </div>
            </form>

        <form method="post" action="/admin/platform-orders/batch-activate-subscriptions" data-action="disable-on-submit" onsubmit="return confirm('确认对全部订单执行批量同步？该操作仍只处理“已支付+已生效+未同步”的订单，但范围可能很大。');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="all">
                <label class="muted form-inline-row mb-8">
                    <span>确认输入</span>
                    <input type="text" name="confirm" placeholder="YES" class="w-140">
                    <span>（必须输入 YES 才会执行）</span>
                </label>
                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>
                <button class="btn btn-sm" type="submit">批量同步订阅（全部订单）</button>
            </form>
    </div>

    <div class="tool-group focus-box">
        <div class="tool-group-title">批量标记支付并生效（BMPA）</div>
        @php
            $batchBmpaBlocked = (bool) ($toolGuards['batch_bmpa']['blocked'] ?? false);
            $batchBmpaBlockedReason = (string) ($toolGuards['batch_bmpa']['reason'] ?? '');
        @endphp
        <form method="post" action="/admin/platform-orders/batch-mark-paid-and-activate" data-action="disable-on-submit" onsubmit="return confirm('确认批量将当前筛选范围内“待处理+未支付”的订单标记为已支付并生效，并同步订阅？（会补回执留痕；遇到退款/回执不一致会安全阀阻断并记录失败原因）');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="filtered">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])

                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>

                <div class="muted mb-8">提示：建议先筛选「待处理 + 未支付」后再执行，避免误操作。</div>
                <div class="mt-6">
                    <button class="btn btn-sm" type="submit" @disabled($batchBmpaBlocked) title="{{ $batchBmpaBlockedReason }}">批量标记支付并生效（含订阅同步）（当前筛选范围）</button>
                    @if($batchBmpaBlocked)
                        @php
                            // 提效：被阻断时给一键跳转到「可BMPA处理集合」（与仪表盘口径对齐）。
                            $goBmpaProcessableUrl = $buildQuickFilterUrl([
                                'bmpa_processable_only' => '1',
                            ]);
                        @endphp
                        @include('admin.components.tool_blocked_hint', [
                            'dataRole' => 'batch-bmpa-blocked-hint',
                            'reason' => $batchBmpaBlockedReason,
                            'actions' => [
                                ['label' => '切到可BMPA处理集合', 'url' => $goBmpaProcessableUrl],
                            ],
                        ])
                    @endif
                </div>
            </form>

        <form method="post" action="/admin/platform-orders/batch-mark-paid-and-activate" data-action="disable-on-submit" onsubmit="return confirm('确认对全部订单执行批量标记支付并生效（含订阅同步）？该操作仍只处理“待处理+未支付”的订单，但范围可能很大。');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="all">
                <label class="muted form-inline-row mb-8">
                    <span>确认输入</span>
                    <input type="text" name="confirm" placeholder="YES" class="w-140">
                    <span>（必须输入 YES 才会执行）</span>
                </label>
                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>
                <button class="btn btn-sm" type="submit">批量标记支付并生效（含订阅同步）（全部订单）</button>
            </form>
    </div>

    <div class="tool-group focus-box">
        <div class="tool-group-title">批量仅标记为已生效</div>
        @php
            $batchMarkActivatedBlocked = (bool) ($toolGuards['batch_mark_activated']['blocked'] ?? false);
            $batchMarkActivatedBlockedReason = (string) ($toolGuards['batch_mark_activated']['reason'] ?? '');
        @endphp
        <form method="post" action="/admin/platform-orders/batch-mark-activated" data-action="disable-on-submit" onsubmit="return confirm('确认批量将当前筛选范围内“已支付+待处理”的订单标记为已生效？（不修改支付状态，不自动同步订阅）');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="filtered">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])

                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>

                <div class="muted mb-8">提示：建议先用快捷筛选「待生效」（已支付+待处理）锁定范围，再执行批量生效。</div>
                <div class="mt-6">
                    <button class="btn btn-sm" type="submit" @disabled($batchMarkActivatedBlocked) title="{{ $batchMarkActivatedBlockedReason }}">批量仅标记为已生效（当前筛选范围）</button>
                    @if($batchMarkActivatedBlocked)
                        @php
                            // 提效：当被阻断时给一键跳转到“待生效集合”的入口（口径：paid + pending + sync_status=unsynced）。
                            // 说明：使用快捷筛选构造器，保留上下文（站点/套餐/订阅/keyword/lead/时间范围/back），并自动清空 page 与工具型开关。
                            $goPaidPendingUnsyncedUrl = $buildQuickFilterUrl([
                                'payment_status' => 'paid',
                                'status' => 'pending',
                                'sync_status' => 'unsynced',
                            ]);
                        @endphp
                        @include('admin.components.tool_blocked_hint', [
                            'dataRole' => 'batch-mark-activated-blocked-hint',
                            'reason' => $batchMarkActivatedBlockedReason,
                            'actions' => [
                                ['label' => '切到待生效集合', 'url' => $goPaidPendingUnsyncedUrl],
                            ],
                        ])
                    @endif
                </div>
            </form>

        <form method="post" action="/admin/platform-orders/batch-mark-activated" data-action="disable-on-submit" onsubmit="return confirm('确认对全部订单执行批量仅标记为已生效？该操作仍只处理“已支付+待处理”的订单，但范围可能很大。');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="all">
                <label class="muted form-inline-row mb-8">
                    <span>确认输入</span>
                    <input type="text" name="confirm" placeholder="YES" class="w-140">
                    <span>（必须输入 YES 才会执行）</span>
                </label>
                <label class="muted form-inline-row mb-8">
                    <span>本次最多处理</span>
                    <input type="number" name="limit" value="50" min="1" max="500" class="w-90">
                    <span>条（安全阀）</span>
                </label>
                <button class="btn btn-sm" type="submit">批量仅标记为已生效（全部订单）</button>
            </form>
    </div>

    <div class="tool-group focus-box">
        <div class="tool-group-title">清理失败标记：同步订阅</div>
        @php
            $clearSyncBlocked = (bool) ($toolGuards['clear_sync_errors']['blocked'] ?? false);
            $clearSyncBlockedReason = (string) ($toolGuards['clear_sync_errors']['reason'] ?? '');
        @endphp
        <form method="post" action="/admin/platform-orders/clear-sync-errors" data-action="disable-on-submit" onsubmit="return confirm('确认清除当前筛选范围内命中的订单的“同步失败”标记？');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="filtered">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])
                <div class="mt-6">
                    <button class="btn btn-danger btn-sm" type="submit" @disabled($clearSyncBlocked) title="{{ $clearSyncBlockedReason }}">清除同步失败标记（当前筛选范围）</button>
                    @if($clearSyncBlocked)
                        @php
                            // 提效：清理同步失败标记前必须先锁定失败集合；被阻断时给一键跳转入口。
                            $goSyncFailedUrl = $buildQuickFilterUrl([
                                'sync_status' => 'failed',
                                // 从 BMPA 失败上下文被阻断时，跳转到同步失败集合应清理 BMPA 开关，避免口径冲突导致空结果。
                                'bmpa_failed_only' => null,
                            ]);
                        @endphp
                        @include('admin.components.tool_blocked_hint', [
                            'dataRole' => 'clear-sync-errors-blocked-hint',
                            'reason' => $clearSyncBlockedReason,
                            'actions' => [
                                ['label' => '切到同步失败集合', 'url' => $goSyncFailedUrl],
                            ],
                        ])
                    @endif
                </div>
            </form>

        <form method="post" action="/admin/platform-orders/clear-sync-errors" data-action="disable-on-submit" onsubmit="return confirm('确认清除全部订单的“同步失败”标记？该操作不可逆（仅清理 meta 标记），请谨慎。');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="all">

                <label class="muted form-inline-row mb-8">
                    <span>确认输入</span>
                    <input type="text" name="confirm" placeholder="YES" class="w-140">
                    <span>（必须输入 YES 才会执行）</span>
                </label>

                <div class="mt-6">
                    <button class="btn btn-danger btn-sm" type="submit">清除同步失败标记（全部订单）</button>
                </div>
            </form>
    </div>

    <div class="tool-group focus-box">
        <div class="tool-group-title">清理失败标记：批量 BMPA</div>
        @php
            $clearBmpaBlocked = (bool) ($toolGuards['clear_bmpa_errors']['blocked'] ?? false);
            $clearBmpaBlockedReason = (string) ($toolGuards['clear_bmpa_errors']['reason'] ?? '');
        @endphp
        <form method="post" action="/admin/platform-orders/clear-bmpa-errors" data-action="disable-on-submit" onsubmit="return confirm('确认清除当前筛选范围内命中的订单的“批量标记支付失败”标记？');" class="mb-10">
                @csrf
                <input type="hidden" name="scope" value="filtered">
                @include('admin.components.filters_hidden_inputs', ['filters' => $filters ?? []])
                <div class="mt-6">
                    <button class="btn btn-danger btn-sm" type="submit" @disabled($clearBmpaBlocked) title="{{ $clearBmpaBlockedReason }}">清除批量标记支付失败标记（当前筛选范围）</button>
                    @if($clearBmpaBlocked)
                        @php
                            // 提效：清理 BMPA 失败标记前必须先锁定 BMPA 失败集合；被阻断时给一键跳转入口。
                            $goBmpaFailedUrl = $buildQuickFilterUrl([
                                'bmpa_failed_only' => '1',
                                // 从其它治理上下文被阻断时，跳转到 BMPA 失败集合应清理同步失败开关，避免口径冲突导致空结果。
                                'fail_only' => null,
                            ]);
                        @endphp
                        @include('admin.components.tool_blocked_hint', [
                            'dataRole' => 'clear-bmpa-errors-blocked-hint',
                            'reason' => $clearBmpaBlockedReason,
                            'actions' => [
                                ['label' => '切到 BMPA 失败集合', 'url' => $goBmpaFailedUrl],
                            ],
                        ])
                    @endif
                </div>
            </form>

        <form method="post" action="/admin/platform-orders/clear-bmpa-errors" data-action="disable-on-submit" onsubmit="return confirm('确认清除全部订单的“批量标记支付失败”标记？该操作不可逆（仅清理 meta 标记），请谨慎。');">
                @csrf
                <input type="hidden" name="scope" value="all">

                <label class="muted form-inline-row mb-8">
                    <span>确认输入</span>
                    <input type="text" name="confirm" placeholder="YES" class="w-140">
                    <span>（必须输入 YES 才会执行）</span>
                </label>

                <div class="mt-6">
                    <button class="btn btn-danger btn-sm" type="submit">清除批量标记支付失败标记（全部订单）</button>
                </div>
            </form>
    </div>
</div>
</div>


<div class="card list-card">
    <div class="list-card-header">
        <div>
            <h3 class="list-card-title">平台订单列表</h3>
        </div>
        {{-- 新建平台订单链接已在页面顶部统一生成（$createOrderUrl），避免口径漂移与重复入口 --}}
        @php
            $toggleViewUrl = $isFullView
                ? $safeFullUrlWithQuery(['view' => null, 'page' => null])
                : $safeFullUrlWithQuery(['view' => 'full', 'page' => null]);
            $toggleViewLabel = $isFullView ? '精简视图' : '展开全部列';
        @endphp
        <div class="actions gap-10">
            <a class="btn btn-secondary btn-sm" href="{!! $toggleViewUrl !!}">{{ $toggleViewLabel }}</a>
        </div>
    </div>
    <div class="list-card-body">
        <div class="table-wrap">
        <table class="list-card-table table-nowrap platform-orders-table {{ $isFullView ? 'is-full' : 'is-compact' }}">
            <thead>
            <tr>
                <th>ID</th>
                <th>订单号</th>
                <th>站点</th>
                <th>套餐</th>
                <th class="col-optional">订单类型</th>
                <th>订单状态</th>
                <th>支付状态</th>
                <th>应付金额</th>
                <th>已付金额</th>
                <th>下单时间</th>
                <th>支付时间</th>
                <th>同步状态</th>
                <th>订阅号</th>
                <th>订阅到期</th>
                <th class="col-optional">同步时间</th>
                <th class="col-optional">失败原因</th>
                <th class="col-optional">最近批量同步</th>
                <th class="col-optional">最近批量BMPA</th>
                <th class="col-optional">最近批量生效</th>
                <th class="col-optional">回执总额</th>
                <th class="col-optional">对账差额</th>
                <th class="col-optional">回执数</th>
                <th class="col-optional">退款数</th>
                <th class="col-optional">退款总额</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
        @forelse($orders as $order)
            <tr>
                <td>{{ $order->id }}</td>
                @php
                    $orderShowUrl = \App\Support\BackUrl::withBack('/admin/platform-orders/' . $order->id, $selfWithoutBack);
                @endphp
                <td>
                    <a href="{!! $orderShowUrl !!}">{{ $order->order_no }}</a>
                    @php
                        $rowLeadId = (int) (data_get($order->meta, 'platform_lead_id') ?? 0);
                        $rowLeadUrl = '';
                        if ($rowLeadId > 0) {
                            $rowLeadUrl = '/admin/platform-leads?' . \Illuminate\Support\Arr::query([
                                'lead_id' => $rowLeadId,
                                'back' => $selfWithoutBack,
                            ]);
                        }
                    @endphp
                    @if($rowLeadId > 0)
                        <div class="muted muted-xs row-meta">
                            <span class="muted muted-xs">线索：</span>
                            <a class="link muted-xs" href="{!! $rowLeadUrl !!}">#{{ $rowLeadId }}</a>
                        </div>
                    @endif
                </td>
                <td>
                    @if($order->merchant)
                        <a href="{!! $safeFullUrlWithQuery(['merchant_id' => $order->merchant->id, 'page' => null]) !!}" class="link">{{ $order->merchant->name }}</a>
                    @else
                        <span class="muted">未关联站点</span>
                    @endif
                </td>
                <td>
                    @php $planName = $order->plan_name ?: ($order->plan?->name ?? '未设置'); @endphp
                    @if($order->plan)
                        <a href="{!! $safeFullUrlWithQuery(['plan_id' => $order->plan->id, 'page' => null]) !!}" class="link">{{ $planName }}</a>
                    @else
                        {{ $planName }}
                    @endif
                </td>
                <td class="col-optional">
                    {{ $order->orderTypeLabel() }}
                    <div class="muted muted-xs">{{ $order->order_type }}</div>
                </td>
                <td>
                    {{ $statusLabels[$order->status] ?? $order->status }}
                    <div class="muted muted-xs">{{ $order->status }}</div>
                </td>
                <td>
                    {{ $paymentStatusLabels[$order->payment_status] ?? $order->payment_status }}
                    <div class="muted muted-xs">{{ $order->payment_status }}</div>

                    @php
                        $hasReceiptEvidenceRow = (data_get($order->meta, 'payment_summary.total_amount') !== null)
                            || (data_get($order->meta, 'payment_receipts.0.amount') !== null);
                        $noReceiptFixUrlRow = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-payment-receipt');
                    @endphp
                    @if($order->payment_status === 'paid' && ! $hasReceiptEvidenceRow)
                        <div class="muted text-danger muted-xs row-warn">
                            <span class="row-warn-prefix">已付无回执</span>
                            <span class="muted">｜</span>
                            <a class="link" href="{!! $noReceiptFixUrlRow !!}">去补回执</a>
                        </div>
                    @endif
                </td>
                <td>
                    @if($isFullView)
                        ¥{{ number_format((float) $order->payable_amount, 2) }}
                    @else
                        ¥{{ $formatMoneyCompact($order->payable_amount) }}
                    @endif
                </td>
                <td>
                    @if($isFullView)
                        ¥{{ number_format((float) $order->paid_amount, 2) }}
                    @else
                        ¥{{ $formatMoneyCompact($order->paid_amount) }}
                    @endif
                </td>
                <td>
                    @if($isFullView)
                        {{ optional($order->placed_at)->format('Y-m-d H:i:s') ?: '-' }}
                    @else
                        {{ optional($order->placed_at)->format('Y-m-d') ?: '-' }}
                    @endif
                </td>
                <td>
                    @if($isFullView)
                        {{ optional($order->paid_at)->format('Y-m-d H:i:s') ?: '-' }}
                    @else
                        {{ optional($order->paid_at)->format('Y-m-d') ?: '-' }}
                    @endif
                </td>
                <td>
                    @php
                        $syncedId = (int) data_get($order->meta, 'subscription_activation.subscription_id', 0);
                        $syncErr = (string) (data_get($order->meta, 'subscription_activation_error.message') ?? '');
                        $bmpaErrCompact = (string) (data_get($order->meta, 'batch_mark_paid_and_activate_error.message') ?? '');
                    @endphp
                    @if($syncedId > 0)
                        <a href="{!! $safeFullUrlWithQuery(['sync_status' => 'synced', 'page' => null]) !!}" class="link">已同步</a>
                    @elseif($syncErr !== '')
                        <a href="{!! $safeFullUrlWithQuery(['sync_status' => 'failed', 'page' => null]) !!}" class="link text-danger">同步失败</a>
                    @else
                        <a href="{!! $safeFullUrlWithQuery(['sync_status' => 'unsynced', 'page' => null]) !!}" class="muted">未同步</a>
                    @endif

                    @if(! $isFullView)
                        @if($syncErr !== '')
                            <div class="muted muted-xs text-danger row-warn">
                                <span class="row-warn-prefix">原因</span>
                                {{ mb_substr($syncErr, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}
                            </div>
                        @endif
                        @if($bmpaErrCompact !== '')
                            <div class="muted muted-xs text-danger row-warn">
                                <span class="row-warn-prefix">BMPA</span>
                                {{ mb_substr($bmpaErrCompact, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}
                            </div>
                        @endif
                    @endif
                </td>
                <td>
                    @if($order->siteSubscription)
                        <div>
                            @php
                                // 与本页“订单号 -> 详情页 back”口径一致：订阅详情 back 回到本页自身（剔除 back query，避免嵌套）
                                $subBack = $selfWithoutBack;
                                $subLink = \App\Support\BackUrl::withBack('/admin/site-subscriptions/' . $order->siteSubscription->id, $subBack);
                            @endphp
                            <a class="link" href="{!! $subLink !!}">{{ $order->siteSubscription->subscription_no }}</a>
                        </div>
                        <div class="muted muted-xs row-meta">
                            <span class="muted muted-xs">订阅ID：</span>
                            <a href="{!! $safeFullUrlWithQuery(['site_subscription_id' => $order->siteSubscription->id, 'page' => null]) !!}" class="muted muted-xs">{{ $order->siteSubscription->id }}</a>
                        </div>
                    @else
                        <span class="muted">-</span>
                        @if((string) ($order->order_type ?? '') === 'renewal')
                            <div class="muted muted-xs text-danger row-warn">
                                <span class="row-warn-prefix">治理</span>
                                续费单未绑定订阅
                            </div>
                        @endif
                    @endif
                </td>
                <td>
                    @if($isFullView)
                        {{ optional($order->siteSubscription?->ends_at)->format('Y-m-d H:i:s') ?: '-' }}
                    @else
                        {{ optional($order->siteSubscription?->ends_at)->format('Y-m-d') ?: '-' }}
                    @endif
                </td>
                <td class="col-optional">{{ data_get($order->meta, 'subscription_activation.synced_at') ?: '-' }}</td>
                <td class="col-optional">
                    @php
                        $syncErrMsg = (string) (data_get($order->meta, 'subscription_activation_error.message') ?? '');
                        $syncErrTooLong = $syncErrMsg !== '' && mb_strlen($syncErrMsg) > $SYNC_ERROR_KEYWORD_LINK_MAX_LEN;

                        $bmpaErrMsg = (string) (data_get($order->meta, 'batch_mark_paid_and_activate_error.message') ?? '');
                        $bmpaErrTooLong = $bmpaErrMsg !== '' && mb_strlen($bmpaErrMsg) > $SYNC_ERROR_KEYWORD_LINK_MAX_LEN;

                        $hasAnyErr = ($syncErrMsg !== '') || ($bmpaErrMsg !== '');
                    @endphp

                    @if(! $hasAnyErr)
                        <span class="muted">-</span>
                    @else
                        @if($syncErrMsg !== '')
                            @php
                                // 同步失败：默认落到“可执行集合”（优先同批次）
                                $basRunIdRow = (string) (data_get($order->meta, 'batch_activation.last_result.run_id') ?? '');
                                if ($basRunIdRow === '') {
                                    $basRunIdRow = (string) (data_get($order->meta, 'batch_activation.run_id') ?? '');
                                }

                                $syncGoFailedUrl = $buildQuickFilterUrl([
                                    'sync_status' => 'failed',
                                    'page' => null,
                                ]);

                                $syncGoBatchFailedUrl = '';
                                $syncGoBatchReasonUrl = '';
                                if ($basRunIdRow !== '') {
                                    $syncGoBatchFailedUrl = $buildQuickFilterUrl([
                                        'batch_activation_run_id' => $basRunIdRow,
                                        'sync_status' => 'failed',
                                        'page' => null,
                                    ]);

                                    if (! $syncErrTooLong) {
                                        $syncGoBatchReasonUrl = $buildQuickFilterUrl([
                                            'batch_activation_run_id' => $basRunIdRow,
                                            'sync_status' => 'failed',
                                            'sync_error_keyword' => $syncErrMsg,
                                            'page' => null,
                                        ]);
                                    }
                                }

                                $syncGoReasonUrl = $buildQuickFilterUrl([
                                    'sync_error_keyword' => $syncErrMsg,
                                    'sync_status' => 'failed',
                                    'page' => null,
                                ]);

                                $syncErrorLinkUrl = $syncGoBatchReasonUrl !== '' ? $syncGoBatchReasonUrl : $syncGoReasonUrl;
                            @endphp
                            <div>
                                <span class="muted muted-xs">同步：</span>
                                @if($syncErrTooLong)
                                    <span class="muted text-danger" title="{{ $syncErrMsg }}">{{ mb_substr($syncErrMsg, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}</span>
                                    <div class="muted text-danger muted-xs">原因过长，请复制到筛选框</div>

                                    @if($syncGoBatchFailedUrl !== '')
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $syncGoBatchFailedUrl !!}">进入本批次同步失败集合</a></div>
                                    @else
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $syncGoFailedUrl !!}">进入同步失败集合</a></div>
                                    @endif
                                @else
                                    <a class="link text-danger" href="{!! $syncErrorLinkUrl !!}">{{ mb_substr($syncErrMsg, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}</a>
                                @endif
                            </div>
                        @endif

                        @if($bmpaErrMsg !== '')
                            @php
                                $bmpaRunIdRow = (string) (data_get($order->meta, 'batch_mark_paid_and_activate.run_id') ?? '');

                                $bmpaGoFailedUrl = $buildQuickFilterUrl([
                                    'bmpa_failed_only' => '1',
                                    'page' => null,
                                ]);

                                $bmpaGoBatchFailedUrl = '';
                                if ($bmpaRunIdRow !== '') {
                                    $bmpaGoBatchFailedUrl = $buildQuickFilterUrl([
                                        'batch_bmpa_run_id' => $bmpaRunIdRow,
                                        'bmpa_failed_only' => '1',
                                        'page' => null,
                                    ]);
                                }

                                $bmpaGoBatchReasonUrl = '';
                                if ($bmpaRunIdRow !== '' && ! $bmpaErrTooLong) {
                                    $bmpaGoBatchReasonUrl = $buildQuickFilterUrl([
                                        'batch_bmpa_run_id' => $bmpaRunIdRow,
                                        'bmpa_failed_only' => '1',
                                        'bmpa_error_keyword' => $bmpaErrMsg,
                                        'page' => null,
                                    ]);
                                }
                            @endphp
                            <div class="mt-6">
                                <span class="muted muted-xs">BMPA：</span>
                                @if($bmpaErrTooLong)
                                    <span class="muted text-danger" title="{{ $bmpaErrMsg }}">{{ mb_substr($bmpaErrMsg, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}</span>
                                    <div class="muted text-danger muted-xs">原因过长，请复制到筛选框</div>

                                    @if($bmpaGoBatchFailedUrl !== '')
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $bmpaGoBatchFailedUrl !!}">进入本批次 BMPA 失败集合</a></div>
                                    @else
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $bmpaGoFailedUrl !!}">进入 BMPA 失败集合</a></div>
                                    @endif
                                @else
                                    <a class="link text-danger" href="{!! $safeFullUrlWithQuery(['bmpa_failed_only' => '1', 'bmpa_error_keyword' => $bmpaErrMsg, 'page' => null]) !!}">{{ mb_substr($bmpaErrMsg, 0, $SYNC_FAILED_REASON_TRUNCATE_LEN) }}</a>

                                    @if($bmpaGoBatchReasonUrl !== '')
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $bmpaGoBatchReasonUrl !!}">本批次按原因筛选</a></div>
                                    @elseif($bmpaGoBatchFailedUrl !== '')
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $bmpaGoBatchFailedUrl !!}">进入本批次 BMPA 失败集合</a></div>
                                    @else
                                        <div class="muted muted-xs">治理：<a class="link" href="{!! $bmpaGoFailedUrl !!}">进入 BMPA 失败集合</a></div>
                                    @endif
                                @endif
                            </div>
                        @endif
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        // 优先使用扁平字段 meta.batch_activation（便于筛选/统计，也避免遍历 audit）
                        $batchActivation = (array) (data_get($order->meta, 'batch_activation', []) ?? []);
                        $batchAt = (string) (data_get($batchActivation, 'at') ?? '');
                        $batchAdminId = data_get($batchActivation, 'admin_id');

                        // 兼容旧数据：若尚未写入 batch_activation，则回退从 meta.audit[] 中取最近一次批量同步记录
                        $audit = (array) (data_get($order->meta, 'audit', []) ?? []);
                        $lastBatch = null;
                        if ($batchAt === '' && count($audit) > 0) {
                            foreach (array_reverse($audit) as $item) {
                                if ((string) data_get($item, 'action') === 'batch_activate_subscription') {
                                    $lastBatch = $item;
                                    break;
                                }
                            }
                        }

                        if ($batchAt === '' && $lastBatch) {
                            $batchAt = (string) (data_get($lastBatch, 'at') ?? '');
                            $batchAdminId = data_get($lastBatch, 'admin_id');
                        }
                    @endphp
                    @if($batchAt !== '')
                        @php
                            $batchMode = (string) (data_get($batchActivation, 'mode') ?? '');
                            $batchModeText = $batchMode === 'queue' ? '队列' : ($batchMode !== '' ? $batchMode : '同步');

                            $batchScope = (string) (data_get($batchActivation, 'scope') ?? '');
                            $batchScopeText = $batchScope === 'all' ? '全量' : ($batchScope === 'filtered' ? '筛选' : ($batchScope !== '' ? $batchScope : '-'));
                        @endphp
                        @php
                            $lastResult = (array) (data_get($batchActivation, 'last_result', []) ?? []);
                            $lrRunId = (string) (data_get($lastResult, 'run_id') ?? '');
                            $lrSuccess = (int) (data_get($lastResult, 'success') ?? 0);
                            $lrFailed = (int) (data_get($lastResult, 'failed') ?? 0);
                            $lrTopReason = (string) (data_get($lastResult, 'top_reasons.0.reason') ?? '');
                            $lrTopReasonCount = (int) (data_get($lastResult, 'top_reasons.0.count') ?? 0);
                        @endphp
                        <div>{{ $batchAt }}</div>
                        <div class="muted">管理员：{{ $batchAdminId ?: '-' }}</div>
                        <div class="muted muted-xs">范围：{{ $batchScopeText }}；方式：{{ $batchModeText }}</div>
                        @if($lrRunId !== '')
                            <div class="muted muted-xs">批次：
                                <a class="link" href="/admin/platform-batches/show?type=bas&run_id={{ urlencode($lrRunId) }}&back={{ urlencode($selfWithoutBack) }}">{{ $lrRunId }}</a>
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $safeFullUrlWithQuery(['batch_activation_run_id' => $lrRunId, 'page' => null]) !!}">列表筛选</a>
                            </div>
                            <div class="muted muted-xs">结果：成功{{ $lrSuccess }} / 失败{{ $lrFailed }}</div>
                            @php
                                // 本批次一键治理入口：快速跳转到“同批次失败集合/按原因筛选”
                                $lrGoFailedUrl = $buildQuickFilterUrl([
                                    'batch_activation_run_id' => $lrRunId,
                                    'sync_status' => 'failed',
                                    'page' => null,
                                ]);

                                $lrGoTopReasonUrl = '';
                                if ($lrTopReason !== '' && mb_strlen($lrTopReason) <= $SYNC_ERROR_KEYWORD_LINK_MAX_LEN) {
                                    $lrGoTopReasonUrl = $buildQuickFilterUrl([
                                        'batch_activation_run_id' => $lrRunId,
                                        'sync_status' => 'failed',
                                        'sync_error_keyword' => $lrTopReason,
                                        'page' => null,
                                    ]);
                                }
                            @endphp
                            <div class="muted muted-xs">治理：
                                <a class="link" href="{!! $lrGoFailedUrl !!}">本批次失败</a>
                                @if($lrGoTopReasonUrl !== '')
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $lrGoTopReasonUrl !!}">按Top原因</a>
                                @endif
                            </div>
                            @if($lrTopReason !== '')
                                <div class="muted muted-xs">Top：{{ mb_substr($lrTopReason, 0, 40) }}（{{ $lrTopReasonCount }}）</div>
                            @endif
                        @endif
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        // 优先使用扁平字段 meta.batch_mark_paid_and_activate（便于筛选/统计，也避免遍历 audit）
                        $batchBmpa = (array) (data_get($order->meta, 'batch_mark_paid_and_activate', []) ?? []);
                        $bmpaAt = (string) (data_get($batchBmpa, 'at') ?? '');
                        $bmpaAdminId = data_get($batchBmpa, 'admin_id');
                        $bmpaRunId = (string) (data_get($batchBmpa, 'run_id') ?? '');

                        $bmpaLastResult = (array) (data_get($batchBmpa, 'last_result', []) ?? []);
                        $blrRunId = (string) (data_get($bmpaLastResult, 'run_id') ?? '');
                        $blrSuccess = (int) (data_get($bmpaLastResult, 'success') ?? 0);
                        $blrFailed = (int) (data_get($bmpaLastResult, 'failed') ?? 0);
                        $blrTopReason = (string) (data_get($bmpaLastResult, 'top_reasons.0.reason') ?? '');
                        $blrTopReasonCount = (int) (data_get($bmpaLastResult, 'top_reasons.0.count') ?? 0);
                    @endphp
                    @if($bmpaAt !== '')
                        @php
                            $bmpaMode = (string) (data_get($batchBmpa, 'mode') ?? '');
                            $bmpaModeText = $bmpaMode === 'queue' ? '队列' : ($bmpaMode !== '' ? $bmpaMode : '同步');

                            $bmpaScope = (string) (data_get($batchBmpa, 'scope') ?? '');
                            $bmpaScopeText = $bmpaScope === 'all' ? '全量' : ($bmpaScope === 'filtered' ? '筛选' : ($bmpaScope !== '' ? $bmpaScope : '-'));
                        @endphp
                        <div>{{ $bmpaAt }}</div>
                        <div class="muted">管理员：{{ $bmpaAdminId ?: '-' }}</div>
                        <div class="muted muted-xs">范围：{{ $bmpaScopeText }}；方式：{{ $bmpaModeText }}</div>

                        @if($bmpaRunId !== '')
                            <div class="muted muted-xs">批次：
                                <a class="link" href="/admin/platform-batches/show?type=bmpa&run_id={{ urlencode($bmpaRunId) }}&back={{ urlencode($selfWithoutBack) }}">{{ $bmpaRunId }}</a>
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $safeFullUrlWithQuery(['batch_bmpa_run_id' => $bmpaRunId, 'page' => null]) !!}">列表筛选</a>
                            </div>
                        @endif

                        @if($blrRunId !== '')
                            <div class="muted muted-xs">结果：成功{{ $blrSuccess }} / 失败{{ $blrFailed }}</div>
                            @php
                                // 本批次一键治理入口：快速跳转到“同批次 BMPA 失败集合/按原因筛选”
                                $blrGoFailedUrl = $buildQuickFilterUrl([
                                    'batch_bmpa_run_id' => $blrRunId,
                                    'bmpa_failed_only' => '1',
                                    'page' => null,
                                ]);

                                $blrGoTopReasonUrl = '';
                                if ($blrTopReason !== '' && mb_strlen($blrTopReason) <= $SYNC_ERROR_KEYWORD_LINK_MAX_LEN) {
                                    $blrGoTopReasonUrl = $buildQuickFilterUrl([
                                        'batch_bmpa_run_id' => $blrRunId,
                                        'bmpa_failed_only' => '1',
                                        'bmpa_error_keyword' => $blrTopReason,
                                        'page' => null,
                                    ]);
                                }
                            @endphp
                            <div class="muted muted-xs">治理：
                                <a class="link" href="{!! $blrGoFailedUrl !!}">本批次失败</a>
                                @if($blrGoTopReasonUrl !== '')
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $blrGoTopReasonUrl !!}">按Top原因</a>
                                @endif
                            </div>
                            @if($blrTopReason !== '')
                                <div class="muted muted-xs">Top：{{ mb_substr($blrTopReason, 0, 40) }}（{{ $blrTopReasonCount }}）</div>
                            @endif
                        @endif
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        // 优先使用扁平字段 meta.batch_mark_activated（便于筛选/统计，也避免遍历 audit）
                        $batchMarkActivated = (array) (data_get($order->meta, 'batch_mark_activated', []) ?? []);
                        $batchMarkAt = (string) (data_get($batchMarkActivated, 'at') ?? '');
                        $batchMarkAdminId = data_get($batchMarkActivated, 'admin_id');

                        // 兼容旧数据：若尚未写入 batch_mark_activated，则回退从 meta.audit[] 中取最近一次批量生效记录
                        $audit2 = (array) (data_get($order->meta, 'audit', []) ?? []);
                        $lastBatchMark = null;
                        if ($batchMarkAt === '' && count($audit2) > 0) {
                            foreach (array_reverse($audit2) as $item) {
                                if ((string) data_get($item, 'action') === 'batch_mark_activated') {
                                    $lastBatchMark = $item;
                                    break;
                                }
                            }
                        }

                        if ($batchMarkAt === '' && $lastBatchMark) {
                            $batchMarkAt = (string) (data_get($lastBatchMark, 'at') ?? '');
                            $batchMarkAdminId = data_get($lastBatchMark, 'admin_id');
                        }
                    @endphp
                    @if($batchMarkAt !== '')
                        <div>{{ $batchMarkAt }}</div>
                        <div class="muted">管理员：{{ $batchMarkAdminId ?: '-' }}</div>
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        $receiptTotal = (float) ($order->receipt_total ?? 0);
                    @endphp
                    @if($receiptTotal > 0)
                        <span class="muted">¥{{ number_format($receiptTotal, 2) }}</span>
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        $rowDelta = (float) ($order->reconciliation_delta_row ?? 0);
                        // 统一口径：按分取整判断是否对账不一致，避免浮点误差导致 0.01 边界不稳定
                        $isReconcileMismatchRow = (bool) $order->isReconcileMismatch();
                        // 最短治理路径：对账差额本质是“回执证据不一致”，列表行点击应直达可执行动作面板。
                        $reconcileShowUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-payment-receipt');
                    @endphp
                    @if($isReconcileMismatchRow)
                        @php $reconcileFixUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-payment-receipt'); @endphp
                        <a class="link text-danger" href="{!! $reconcileFixUrl !!}">¥{{ number_format($rowDelta, 2) }}</a>
                        <div class="muted text-danger muted-xs">
                            对账不一致
                            <span class="muted">｜</span>
                            <a class="link" href="{!! $reconcileFixUrl !!}">去补回执</a>
                        </div>
                    @else
                        <span class="muted">¥0.00</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        $receipts = (array) (data_get($order->meta, 'payment_receipts', []) ?? []);
                        $receiptSummaryCount = data_get($order->meta, 'payment_summary.count');
                        $receiptCount = $receiptSummaryCount !== null ? (int) $receiptSummaryCount : count($receipts);
                    @endphp
                    @if($receiptCount > 0)
                        @php
                            // spot-check：有回执时优先直达“回执列表区”（#payment-receipts），而非“新增回执表单”。
                            $receiptCountShowUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'payment-receipts');
                        @endphp
                        <a href="{!! $receiptCountShowUrl !!}" class="muted">{{ $receiptCount }}</a>
                    @else
                        <span class="muted">0</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        $refunds = (array) (data_get($order->meta, 'refund_receipts', []) ?? []);
                        $refundSummaryCount = data_get($order->meta, 'refund_summary.count');
                        $refundCount = $refundSummaryCount !== null ? (int) $refundSummaryCount : count($refunds);
                    @endphp
                    @if($refundCount > 0)
                        @php
                            // spot-check：有退款记录时优先直达“退款记录区”（#refund-receipts），而非“新增退款表单”。
                            $refundCountShowUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'refund-receipts');
                        @endphp
                        <a href="{!! $refundCountShowUrl !!}" class="muted">{{ $refundCount }}</a>
                    @else
                        <span class="muted">0</span>
                    @endif
                </td>
                <td class="col-optional">
                    @php
                        $refundTotal = (float) $order->refundTotal();
                        $isRefundInconsistent = (bool) $order->isRefundInconsistent();

                        $refundShowUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-refund-receipt');
                    @endphp
                    @if($refundTotal > 0)
                        @if($isRefundInconsistent)
                            @php $refundFixUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-refund-receipt'); @endphp
                            <a class="link text-danger" href="{!! $refundShowUrl !!}">¥{{ number_format($refundTotal, 2) }}</a>
                            <div class="muted text-danger muted-xs">
                                疑似不一致
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $refundFixUrl !!}">去核对退款</a>
                            </div>
                        @else
                            <a class="muted" href="{!! $refundShowUrl !!}">¥{{ number_format($refundTotal, 2) }}</a>
                        @endif
                    @else
                        @if($isRefundInconsistent)
                            <a class="link text-danger" href="{!! $refundShowUrl !!}">-</a>
                            <div class="muted text-danger muted-xs">疑似不一致</div>
                        @else
                            <span class="muted">-</span>
                        @endif
                    @endif
                </td>
                <td>
                    @php
                        $canActivate = ($order->payment_status === 'paid') && ($order->status === 'activated');
                        $alreadySynced = (int) data_get($order->meta, 'subscription_activation.subscription_id', 0) > 0;
                        $syncError = data_get($order->meta, 'subscription_activation_error.message');
                        $syncErrorAt = data_get($order->meta, 'subscription_activation_error.at');
                    @endphp
                    @php
                        $needReconcileFix = (bool) $order->isReconcileMismatch();
                        $needRefundFix = (bool) $order->isRefundInconsistent();
                        // 退款轨迹：只要存在退款汇总/退款回执，就视为“需核对”的治理信号（用于禁用部分动作并给入口）
                        $hasRefundTrace = ((float) $order->refundTotal()) > 0;

                        // 行级 BMPA 安全阀（列表页也应禁用，避免运营误触）：
                        // - 对账不一致/退款不一致：需先治理
                        // - 存在退款轨迹：需先核对退款轨迹与状态（避免带退款订单被推进）
                        // - 续费缺订阅：需先绑定订阅
                        $blockedByMissingSubscriptionOnRenewal = ((string) ($order->order_type ?? '') === 'renewal') && ((int) ($order->site_subscription_id ?? 0) <= 0);
                        $markPaidBlockedByGovernance = $needReconcileFix || $needRefundFix || $hasRefundTrace || $blockedByMissingSubscriptionOnRenewal;

                        // 仅当订单尚未处于 paid+activated 时，且未命中治理阻断时，才允许点击
                        $canMarkPaid = ((($order->payment_status !== 'paid') || ($order->status !== 'activated')) && (! $markPaidBlockedByGovernance));

                        // 精简视图也要可达的“治理入口”：不要只依赖可选列（col-optional）里的提示
                        $reconcileFixUrlCompact = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-payment-receipt');
                        $refundFixUrlCompact = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-refund-receipt');
                        $relationFixUrlCompactForBmpa = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'relation-subscription');
                        $refundTraceFixUrlCompact = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'add-refund-receipt');
                    @endphp

                    @if($needReconcileFix || $needRefundFix || $hasRefundTrace || $blockedByMissingSubscriptionOnRenewal)
                        <div class="governance-hints row-warn">
                            @if($needReconcileFix)
                                <div class="muted text-danger muted-xs governance-hint">
                                    <span class="row-warn-prefix">对账</span>
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $reconcileFixUrlCompact !!}">去补回执</a>
                                </div>
                            @endif
                            @if($needRefundFix)
                                <div class="muted text-danger muted-xs governance-hint">
                                    <span class="row-warn-prefix">退款</span>
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $refundFixUrlCompact !!}">去核对退款</a>
                                </div>
                            @endif
                            @if($hasRefundTrace && (! $needRefundFix))
                                <div class="muted text-danger muted-xs governance-hint">
                                    <span class="row-warn-prefix">退款</span>
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $refundTraceFixUrlCompact !!}">有退款轨迹，请核对</a>
                                </div>
                            @endif
                            @if($blockedByMissingSubscriptionOnRenewal)
                                <div class="muted text-danger muted-xs governance-hint">
                                    <span class="row-warn-prefix">订阅</span>
                                    <span class="muted">｜</span>
                                    <a class="link" href="{!! $relationFixUrlCompactForBmpa !!}">去关联订阅</a>
                                </div>
                            @endif
                        </div>
                    @endif

                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-paid-and-activate" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单标记为已支付并生效？此操作会推进状态并尝试同步订阅');" class="mb-6">
                        @csrf
                        <button class="btn btn-sm" type="submit" @disabled(! $canMarkPaid)>标记支付并生效</button>
                    </form>

                    @php
                        $canMarkActivatedOnly = ($order->payment_status === 'paid') && ($order->status !== 'activated');
                        // 安全阀对齐后端：以下情况不允许“仅标记为已生效”（后端 markActivated 也会阻断）
                        // - 续费缺订阅：需先绑定订阅
                        // - 对账不一致：需先补回执/核对金额
                        // - 存在退款轨迹：需先核对退款轨迹与退款状态
                        $markActivatedBlockedByMissingSubscriptionOnRenewalRow = ((string) ($order->order_type ?? '') === 'renewal')
                            && ((int) ($order->site_subscription_id ?? 0) <= 0);
                        $markActivatedBlockedByGovernanceRow = (bool) ($order->isReconcileMismatch() || (((float) $order->refundTotal()) > 0));
                    @endphp
                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-activated" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单标记为已生效？（不修改支付状态，不自动同步订阅）');" class="mb-6">
                        @csrf
                        <button class="btn btn-secondary btn-sm" type="submit" @disabled(! $canMarkActivatedOnly || $markActivatedBlockedByMissingSubscriptionOnRenewalRow || $markActivatedBlockedByGovernanceRow)>仅标记为已生效</button>
                    </form>
                    @if($markActivatedBlockedByMissingSubscriptionOnRenewalRow || $markActivatedBlockedByGovernanceRow)
                        <div class="muted text-danger mt-6">
                            @if($markActivatedBlockedByMissingSubscriptionOnRenewalRow)
                                续费缺订阅不可直接标记生效
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $relationFixUrlCompactForBmpa !!}">去关联订阅</a>
                            @elseif((bool) $order->isReconcileMismatch())
                                对账不一致不可直接标记生效
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $reconcileFixUrlCompact !!}">去补回执</a>
                            @else
                                有退款轨迹不可直接标记生效
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $refundTraceFixUrlCompact !!}">去核对退款</a>
                            @endif
                        </div>
                    @endif

                    @php
                        $syncBlockedByGovernanceRow = (bool) ($order->isReconcileMismatch() || $order->isRefundInconsistent());
                        $syncBlockedByMissingSubscriptionOnRenewalRow = ((string) ($order->order_type ?? '') === 'renewal')
                            && ((int) ($order->site_subscription_id ?? 0) <= 0);

                        // 最短治理路径：续费缺订阅直接落到“关联订阅”面板。
                        $relationFixUrlCompact = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $selfWithoutBack, 'relation-subscription');

                        $syncBlockedRow = $syncBlockedByGovernanceRow || $syncBlockedByMissingSubscriptionOnRenewalRow;
                    @endphp
                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/activate-subscription" data-action="disable-on-submit" onsubmit="return confirm('确认同步订阅？将根据该订单创建/续期订阅');">
                        @csrf
                        <button class="btn btn-secondary btn-sm" type="submit" @disabled(! $canActivate || $alreadySynced || $syncBlockedRow)>{{ $alreadySynced ? '已同步' : '同步订阅' }}</button>
                    </form>

                    @if(! $canActivate)
                        <div class="muted mt-6">需已支付且订单状态为已生效</div>
                    @elseif($alreadySynced)
                        <div class="muted mt-6">该订单已完成同步（幂等保护）</div>
                    @elseif($syncBlockedRow)
                        <div class="muted text-danger mt-6">
                            需先完成治理后再同步
                            @if($syncBlockedByMissingSubscriptionOnRenewalRow)
                                <span class="muted">｜</span>
                                <a class="link" href="{!! $relationFixUrlCompactForBmpa !!}">去关联订阅</a>
                            @endif
                        </div>
                    @endif

                    @if($syncError)
                        <div class="muted text-danger mt-6">同步失败：{{ $syncError }}{{ $syncErrorAt ? '（' . $syncErrorAt . '）' : '' }}</div>
                    @endif

                    @php
                        // 对账明细导出：减少“先点详情页再导出”的额外跳转。
                        // 仅当存在支付/退款回执证据时展示（避免列表噪音）。
                        $hasLedgerEvidenceRow = (bool) ($order->hasLedgerEvidence());

                        // 列表页导出默认带“订单摘要”，便于离线流转（财务/运营对账）
                        $exportLedgerUrlRow = $order->exportLedgerUrl(['include_order_snapshot' => 1]);
                    @endphp
                    @if($hasLedgerEvidenceRow)
                        <div class="mt-6">
                            <a class="link muted muted-xs" href="{!! $exportLedgerUrlRow !!}" target="_blank" rel="noopener">导出对账明细</a>
                        </div>
                    @endif
                </td>
            </tr>
        @empty
            <tr>
                <td colspan="18" class="muted table-empty">暂无平台订单，当前阶段骨架已就位，可继续补套餐下单、支付回执与订阅生效链路。</td>
            </tr>
        @endforelse
        </tbody>
        </table>
        </div>
    </div>
</div>

<div class="pagination-wrap">{{ $orders->links('pagination.admin') }}</div>
@endsection
