@extends('admin.layouts.app')

@section('title', '订阅详情')
@section('page_title', '订阅详情')

@section('content')
@php
    // 统一构造平台订单跳转链接：避免手写拼接导致编码/漏字段问题
    // 注意：这里使用相对路径，避免测试/不同 APP_URL 环境下生成绝对域名导致断言与展示不一致
    // 同时：自动附带 back 参数，保证“从订阅详情跳到订单列表/治理后能回到订阅详情并保留上下文”
    $platformOrdersBaseUrl = '/admin/platform-orders';

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

    // back 安全护栏（全页通用）：用于 `{!! !!}` 输出的 href（避免 &amp; 破坏回链）
    $incomingBack = (string) request()->query('back', '');
    $safeBackForLinks = \App\Support\BackUrl::sanitizeForLinks($incomingBack);

    $makePlatformOrderUrl = function (array $query) use ($platformOrdersBaseUrl, $selfWithoutBack) {
        // 若调用方显式传了 back，则不覆盖；否则默认回到当前订阅详情页（剔除 back，避免嵌套）
        $query = $query + ['back' => $selfWithoutBack];

        return $platformOrdersBaseUrl . '?' . \Illuminate\Support\Arr::query($query);
    };
@endphp

@php
    // 用于构建“保留当前上下文”的订阅列表跳转链接（从订阅详情跳回列表后可一键返回本订阅详情）
    // 统一收敛：订阅详情页自身（剔除 back）直接复用 BackUrl::selfWithoutBack，避免手写拼接口径漂移。
    $subscriptionShowSelf = \App\Support\BackUrl::selfWithoutBack();

    $makeSubscriptionIndexUrl = function (array $query) use ($subscriptionShowSelf) {
        $url = '/admin/site-subscriptions';
        if (count($query) > 0) {
            $url .= '?' . \Illuminate\Support\Arr::query($query);
        }

        return \App\Support\BackUrl::withBack($url, $subscriptionShowSelf);
    };
@endphp

<div class="page-header mb-20" data-page="admin.site_subscriptions.show">
    <div class="page-header-main">
        <div>
            <div class="page-header-title">订阅详情</div>
            <div class="page-header-subtitle">这里是总台视角的订阅详情页，用于运营排查“订阅状态/到期/关联平台订单/同步记录”。</div>
        </div>

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

    <div class="page-header-meta">
        <div>订阅号：<strong>{{ $subscription->subscription_no }}</strong></div>
        <div>状态：{{ ($statusLabels[$subscription->status] ?? $subscription->status) }}（{{ $subscription->status }}）</div>
        <div>到期：{{ optional($subscription->ends_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
    </div>
</div>

<div class="card mb-20">
    <div class="grid-4">
        <div>
            <div class="muted">订阅号</div>
            <div class="num-md">{{ $subscription->subscription_no }}</div>
        </div>
        <div>
            <div class="muted">状态</div>
            <div class="num-md">{{ ($statusLabels[$subscription->status] ?? $subscription->status) }} <span class="muted">({{ $subscription->status }})</span></div>
            <div class="mt-6">
                <form method="post" action="/admin/site-subscriptions/{{ $subscription->id }}/set-status" class="actions gap-10" data-action="disable-on-submit">
                    @csrf
                    <select name="status" onchange="this.form.submit()" class="w-140">
                        @foreach(($statusLabels ?? []) as $value => $label)
                            <option value="{{ $value }}" @selected($subscription->status === $value)>{{ $label }}</option>
                        @endforeach
                    </select>
                    <noscript><button type="submit" class="btn btn-secondary btn-sm">更新状态</button></noscript>
                </form>
                <div class="muted muted-xs mt-6">治理动作：可手工修正订阅状态（仅改状态字段，不自动改到期时间/订阅同步记录）。</div>
            </div>
        </div>
        <div>
            <div class="muted">站点</div>
            <div class="num-md">
                @if($subscription->merchant)
                    <a class="link" href="{!! $makeSubscriptionIndexUrl(['merchant_id' => $subscription->merchant->id]) !!}">{{ $subscription->merchant->name }}</a>
                @else
                    未关联站点
                @endif
            </div>
        </div>
        <div>
            <div class="muted">套餐</div>
            <div class="num-md">
                @php $planName = $subscription->plan_name ?: ($subscription->plan?->name ?? '未设置'); @endphp
                @if($subscription->plan)
                    <a class="link" href="{!! $makeSubscriptionIndexUrl(['plan_id' => $subscription->plan->id]) !!}">{{ $planName }}</a>
                @else
                    {{ $planName }}
                @endif
            </div>
        </div>
    </div>

    <div class="grid-4 mt-10">
        <div>
            <div class="muted">计费周期 / 周期(月)</div>
            <div class="num-md">{{ $subscription->billing_cycle ?: '-' }} / {{ (int) $subscription->period_months }}</div>
        </div>
        <div>
            <div class="muted">金额</div>
            <div class="num-md">¥{{ number_format((float) $subscription->amount, 2) }}</div>
        </div>
        <div>
            <div class="muted">开始时间</div>
            <div class="num-md">{{ optional($subscription->starts_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
        </div>
        <div>
            <div class="muted">到期时间</div>
            <div class="num-md">{{ optional($subscription->ends_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
        </div>
    </div>

    <div class="grid-4 mt-10">
        <div>
            <div class="muted">到期状态（按到期时间）</div>
            <div class="num-md">{{ $expiryLabel }}</div>
        </div>
        <div>
            <div class="muted">试用到期</div>
            <div class="num-md">{{ optional($subscription->trial_ends_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
        </div>
        <div>
            <div class="muted">生效时间</div>
            <div class="num-md">{{ optional($subscription->activated_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
        </div>
        <div>
            <div class="muted">取消时间</div>
            <div class="num-md">{{ optional($subscription->cancelled_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
        </div>
    </div>

        @if($subscription->subscription_no)
            <div class="mt-6 actions gap-10">
                {{-- 去重降噪：下方摘要卡/表格头部已提供“全部订单/可同步”等跳转入口，这里仅保留治理相关入口与下单入口 --}}
                <a class="btn btn-secondary btn-sm" href="{!! $makePlatformOrderUrl(['merchant_id' => $subscription->merchant_id, 'plan_id' => $subscription->plan_id, 'renewal_missing_subscription' => '1']) !!}">查看续费缺订阅订单（同站点/同套餐）</a>
                <a class="btn btn-secondary btn-sm" href="{!! $makePlatformOrderUrl(['merchant_id' => $subscription->merchant_id, 'plan_id' => $subscription->plan_id, 'payment_status' => 'paid', 'receipt_status' => 'none']) !!}">查看已付无回执订单（同站点/同套餐）</a>
                @php
                    $createRenewalOrderUrl = '/admin/platform-orders/create?' . \Illuminate\Support\Arr::query([
                        'merchant_id' => $subscription->merchant_id,
                        'plan_id' => $subscription->plan_id,
                        'site_subscription_id' => $subscription->id,
                        'order_type' => 'renewal',
                        'require_subscription' => '1',
                        'quantity' => 1,
                        'remark' => (string) config('saasshop.platform_orders.renewal_order_remark_prefix', '来自订阅：') . $subscription->subscription_no,
                        // 保留 back：创建订单 -> 订单详情后可一键返回本订阅详情
                        'back' => $selfWithoutBack,
                    ]);
                @endphp
                <a class="btn btn-sm" href="{!! $createRenewalOrderUrl !!}">创建续费订单</a>
            </div>
        @endif
    </div>

    <div class="mt-10" id="syncable-batch">
        @php
            $reconcileMismatchOrders = (int) ($summaryStats['reconcile_mismatch_orders'] ?? 0);
            $refundInconsistentOrders = (int) ($summaryStats['refund_inconsistent_orders'] ?? 0);
        @endphp

        @if($reconcileMismatchOrders > 0 || $refundInconsistentOrders > 0)
            <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($reconcileMismatchOrders > 0)
                        <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'reconcile_mismatch' => '1']) !!}">对账不一致</a>
                        <span class="muted">（{{ $reconcileMismatchOrders }}）</span>
                    @endif
                    @if($reconcileMismatchOrders > 0 && $refundInconsistentOrders > 0)
                        <span class="muted">与</span>
                    @endif
                    @if($refundInconsistentOrders > 0)
                        <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'refund_inconsistent' => '1']) !!}">退款不一致</a>
                        <span class="muted">（{{ $refundInconsistentOrders }}）</span>
                    @endif
                    订单。建议先逐单治理金额/状态口径（补回执/核对退款/修正状态），再批量同步订阅。

                    {{-- 去重降噪：上方正文已给出筛选入口链接，这里不再重复放置“进入XX订单列表”按钮 --}}
                </div>
            </div>
        @endif

        <form method="post" action="/admin/platform-orders/batch-activate-subscriptions" data-action="disable-on-submit" onsubmit="return confirm('确认批量同步该订阅下“可同步”的订单？（仅处理：已支付+已生效+未同步）');">
            @csrf
            <input type="hidden" name="scope" value="filtered">
            <input type="hidden" name="site_subscription_id" value="{{ $subscription->id }}">
            <input type="hidden" name="syncable_only" value="1">
            <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>
            <div class="muted muted-xs mt-6">提示：点击后按钮会自动禁用，避免重复提交。</div>
        </form>
        <div class="muted muted-xs mt-6">说明：该按钮等价于平台订单页的“批量同步订阅（当前筛选范围）”，已内置只处理可同步订单（已支付+已生效+未同步）。</div>
    </div>
</div>

<div class="grid-4 mb-20">

    <div class="card">
        <h3>关联订单总数</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id]) !!}">{{ $summaryStats['total_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">点击跳转：该订阅下全部平台订单</div>
    </div>
    <div class="card">
        <h3>已同步</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'sync_status' => 'synced']) !!}">{{ $summaryStats['synced_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">点击跳转：该订阅下「已同步」订单</div>
    </div>
    <div class="card">
        <h3>同步失败</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'sync_status' => 'failed']) !!}">{{ $summaryStats['failed_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">点击跳转：该订阅下「同步失败」订单</div>
    </div>
    <div class="card">
        <h3>可同步（已支付+已生效+未同步）</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'syncable_only' => '1', 'sync_status' => 'unsynced']) !!}">{{ $summaryStats['syncable_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">点击跳转：该订阅下「可同步订阅」订单</div>
    </div>
    <div class="card">
        <h3>未同步（无记录）</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'sync_status' => 'unsynced']) !!}">{{ $summaryStats['unsynced_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">口径：meta 无 activation 且无 error；点击跳转可查看明细</div>
    </div>

    <div class="card">
        <h3>有回执订单 / 回执总额</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'receipt_status' => 'has']) !!}">{{ $summaryStats['receipt_orders'] ?? 0 }}</a>
            / ¥{{ number_format((float) ($summaryStats['total_receipt_amount'] ?? 0), 2) }}
        </div>
        <div class="muted muted-xs">点击订单数可跳转：该订阅下「有回执」订单</div>
        <div class="muted muted-xs">
            已付无回执订单：
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'payment_status' => 'paid', 'receipt_status' => 'none']) !!}">{{ $summaryStats['no_receipt_orders'] ?? 0 }}</a>
        </div>
    </div>

    <div class="card">
        <h3>有退款订单 / 退款总额</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'refund_status' => 'has']) !!}">{{ $summaryStats['refund_orders'] ?? 0 }}</a>
            / ¥{{ number_format((float) ($summaryStats['total_refunded_amount'] ?? 0), 2) }}
        </div>
        <div class="muted muted-xs">点击订单数可跳转：该订阅下「有退款」订单</div>
        <div class="muted muted-xs">
            无退款订单：
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'refund_status' => 'none']) !!}">{{ $summaryStats['no_refund_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">
            退款不一致订单：
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'refund_inconsistent' => '1']) !!}">{{ $summaryStats['refund_inconsistent_orders'] ?? 0 }}</a>
        </div>
        @php $refundTol = (float) config('saasshop.amounts.tolerance', 0.01); @endphp
        <div class="muted muted-xs">当前容差：¥{{ number_format($refundTol, 2) }}</div>
        @if(((int) ($summaryStats['refund_inconsistent_orders'] ?? 0)) > 0)
            <div class="card governance-block mt-10">
                <div class="muted text-danger governance-block-title"><strong>退款不一致治理提示</strong></div>
                <div class="muted governance-block-body">
                    提示：存在退款状态与退款总额不一致订单。
                    <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'refund_inconsistent' => '1']) !!}">查看退款不一致订单</a>
                    （建议先逐单核对退款轨迹，再在订单详情页使用「退款状态治理」修正状态；仅修口径，不会自动生成回执/退款回执）。
                </div>
            </div>
        @endif
    </div>

    <div class="card">
        <h3>对账差额（回执-已付）</h3>
        @php $delta = (float) ($summaryStats['reconciliation_delta'] ?? 0); @endphp
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'reconcile_mismatch' => '1']) !!}">¥{{ number_format($delta, 2) }}</a>
        </div>
        <div class="muted muted-xs">点击差额可跳转：该订阅下「对账不一致」订单</div>
        <div class="muted muted-xs">
            对账不一致订单：
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'reconcile_mismatch' => '1']) !!}">{{ $summaryStats['reconcile_mismatch_orders'] ?? 0 }}</a>
        </div>
        @php $tol = (float) config('saasshop.amounts.tolerance', 0.01); @endphp
        @if(((int) ($summaryStats['reconcile_mismatch_orders'] ?? 0)) > 0)
            <div class="card governance-block mt-10">
                <div class="muted text-danger governance-block-title"><strong>对账不一致治理提示</strong></div>
                <div class="muted governance-block-body">
                    提示：存在「回执总额 vs 已付金额」不一致订单。
                    <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'reconcile_mismatch' => '1']) !!}">查看对账不一致订单</a>
                    （建议先逐单核对回执轨迹与订单金额，再决定是否补回执/修正订单金额口径）。
                </div>
            </div>
        @elseif(abs($delta) >= $tol)
            <div class="card governance-block mt-10">
                <div class="muted text-danger governance-block-title"><strong>对账差额提示</strong></div>
                <div class="muted governance-block-body">
                    差额超过容差（tol={{ number_format($tol, 2) }}），可能存在回执金额与订单已付金额不一致。
                </div>
            </div>
        @else
            <div class="muted muted-xs">差额在容差范围内（tol={{ number_format($tol, 2) }}，当前订阅维度）</div>
        @endif
    </div>

    <div class="card">
        <h3>BMPA 成功 / 失败</h3>
        <div class="num-md">
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'bmpa_success_only' => '1']) !!}">{{ $summaryStats['bmpa_success_orders'] ?? 0 }}</a>
            <span class="muted"> / </span>
            <a class="link" href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id, 'bmpa_failed_only' => '1']) !!}">{{ $summaryStats['bmpa_failed_orders'] ?? 0 }}</a>
        </div>
        <div class="muted muted-xs">点击跳转：该订阅下「BMPA成功 / BMPA失败」订单集合</div>
    </div>

    <div class="card">
        <h3>BMPA 失败原因Top3</h3>
        @php
            $bmpaFailedReasonStats = $bmpaFailedReasonStats ?? [];
            // 避免 URL 过长/特殊字符破坏 query：原因过长则不生成 keyword 链接
            // 与列表页/仪表盘/订单详情保持一致：由 config 统一控制阈值。
            $FAILED_REASON_KEYWORD_MAX_LEN = (int) config('saasshop.platform_orders.sync_error_keyword_link_max_len', 200);
        @endphp
        @if(count($bmpaFailedReasonStats) > 0)
            <div class="muted mt-6">
                @foreach($bmpaFailedReasonStats as $item)
                    @php
                        $reason = (string) ($item['reason'] ?? '');
                        $reasonUrl = '';
                        if ($reason !== '' && mb_strlen($reason) <= $FAILED_REASON_KEYWORD_MAX_LEN) {
                            $reasonUrl = $makePlatformOrderUrl([
                                'site_subscription_id' => $subscription->id,
                                'bmpa_failed_only' => '1',
                                'bmpa_error_keyword' => $reason,
                            ]);
                        }
                    @endphp
                    <div>
                        @if($reasonUrl)
                            <a class="link" href="{!! $reasonUrl !!}">{{ $reason }}</a>
                        @else
                            <span>{{ $reason }}</span>
                            <span class="muted muted-xs">（原因过长，请复制到筛选框）</span>
                        @endif
                        <span class="muted">（{{ $item['count'] }}）</span>
                    </div>
                @endforeach
            </div>
        @else
            <div class="muted">暂无 BMPA 失败原因聚合数据</div>
        @endif
    </div>

    <div class="card">
        <h3>同步失败原因Top3</h3>
        @php $failedReasonStats = $failedReasonStats ?? []; @endphp
        @if(count($failedReasonStats) > 0)
            <div class="muted mt-6">
                @foreach($failedReasonStats as $item)
                    @php
                        $reason = (string) ($item['reason'] ?? '');
                        $reasonUrl = '';
                        if ($reason !== '' && mb_strlen($reason) <= $FAILED_REASON_KEYWORD_MAX_LEN) {
                            $reasonUrl = $makePlatformOrderUrl([
                                'site_subscription_id' => $subscription->id,
                                'sync_status' => 'failed',
                                'sync_error_keyword' => $reason,
                            ]);
                        }
                    @endphp
                    <div>
                        @if($reasonUrl)
                            <a class="link" href="{!! $reasonUrl !!}">{{ $reason }}</a>
                        @else
                            <span>{{ $reason }}</span>
                            <span class="muted muted-xs">（原因过长，请复制到筛选框）</span>
                        @endif
                        <span class="muted">（{{ $item['count'] }}）</span>
                    </div>
                @endforeach
            </div>
        @else
            <div class="muted">暂无同步失败原因聚合数据</div>
        @endif
    </div>
</div>

<div class="card list-card">
    <div class="list-card-header">
        <div>
            <h3 class="list-card-title">关联平台订单（{{ $platformOrders->total() }}）</h3>

            <div class="mt-10">
        <span class="muted">同步状态筛选：</span>
        @php
            $cur = $summaryStats['current_order_sync_status'] ?? '';

            // 重要：这里的筛选链接需要保留 back，否则点击后会丢失“返回上一页（保留上下文）”能力。
            // 同时：href 中会包含多个 query 参数，必须使用 `{!! !!}` 原样输出，避免 `&` 被转义为 `&amp;`。
            // $safeBackForLinks 已在页头统一按 BackUrl::sanitizeForLinks 计算。

            // 构造“订阅详情页自身”的筛选链接：统一走 BackUrl::currentPathWithQuery，减少手写拼接与口径漂移。
            // 目标：保留 back（安全过滤后）+ 保留其它 query 上下文 + 覆盖/移除 order_sync_status。
            $makeSelfFilterUrl = function (?string $orderSyncStatus) use ($safeBackForLinks) {
                $v = ($orderSyncStatus !== null && $orderSyncStatus !== '') ? $orderSyncStatus : null;

                return \App\Support\BackUrl::currentPathWithQuery([
                    'order_sync_status' => $v,
                ], $safeBackForLinks);
            };
        @endphp

        <a href="{!! $makeSelfFilterUrl(null) !!}" class="muted">全部</a>
        <span class="muted">｜</span>
        <a href="{!! $makeSelfFilterUrl('synced') !!}" class="muted">已同步</a>
        <span class="muted">｜</span>
        <a href="{!! $makeSelfFilterUrl('failed') !!}" class="muted">同步失败</a>
        <span class="muted">｜</span>
        <a href="{!! $makeSelfFilterUrl('unsynced') !!}" class="muted">未同步</a>
        <span class="muted">｜</span>
        <a href="{!! $makeSelfFilterUrl('syncable') !!}" class="muted">可同步</a>
        <span class="muted">｜</span>
        <a href="{!! $makePlatformOrderUrl(['site_subscription_id' => $subscription->id]) !!}" class="muted">在平台订单页打开</a>
        @if($cur)
            <span class="muted">（当前：{{ $cur }}）</span>
        @endif
            </div>
        </div>
    </div>

    <div class="list-card-body">
    <table class="list-card-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>订单号</th>
            <th>订单状态</th>
            <th>支付状态</th>
            <th>应付/已付</th>
            <th>下单时间</th>
            <th>生效时间</th>
            <th>同步状态</th>
            <th>同步时间</th>
            <th>失败原因</th>
            <th>BAS run_id</th>
            <th>BMPA run_id</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        @forelse($platformOrders as $order)
            @php
                $syncedId = (int) data_get($order->meta, 'subscription_activation.subscription_id', 0);
                $syncErr = (string) (data_get($order->meta, 'subscription_activation_error.message') ?? '');
                if ($syncedId > 0) {
                    $syncStatus = '已同步';
                } elseif ($syncErr !== '') {
                    $syncStatus = '同步失败';
                } else {
                    $syncStatus = '未同步';
                }
            @endphp
            <tr>
                <td>{{ $order->id }}</td>
                @php
                    $orderShowUrl = \App\Support\BackUrl::withBack('/admin/platform-orders/' . $order->id, $selfWithoutBack);

                    $basRunId = (string) (data_get($order->meta, 'batch_activation.run_id') ?? '');
                    $bmpaRunId = (string) (data_get($order->meta, 'batch_mark_paid_and_activate.run_id') ?? '');

                    $basBatchUrl = $basRunId !== ''
                        ? \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                            'type' => 'bas',
                            'run_id' => $basRunId,
                        ]), $selfWithoutBack)
                        : '';

                    $bmpaBatchUrl = $bmpaRunId !== ''
                        ? \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                            'type' => 'bmpa',
                            'run_id' => $bmpaRunId,
                        ]), $selfWithoutBack)
                        : '';
                @endphp
                <td><a href="{!! $orderShowUrl !!}">{{ $order->order_no }}</a></td>
                <td>{{ $order->status }}</td>
                <td>{{ $order->payment_status }}</td>
                <td>¥{{ number_format((float) $order->payable_amount, 2) }} / ¥{{ number_format((float) $order->paid_amount, 2) }}</td>
                <td>{{ optional($order->placed_at)->format('Y-m-d H:i:s') ?: '-' }}</td>
                <td>{{ optional($order->activated_at)->format('Y-m-d H:i:s') ?: '-' }}</td>
                <td>
                    {{ $syncStatus }}
                </td>
                <td>{{ data_get($order->meta, 'subscription_activation.synced_at') ?: '-' }}</td>
                <td>
                    @if($syncStatus === '同步失败')
                        <span class="text-danger">{{ mb_substr($syncErr, 0, 60) }}</span>
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td>
                    @if($basBatchUrl !== '')
                        <a class="link" href="{!! $basBatchUrl !!}">{{ $basRunId }}</a>
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td>
                    @if($bmpaBatchUrl !== '')
                        <a class="link" href="{!! $bmpaBatchUrl !!}">{{ $bmpaRunId }}</a>
                    @else
                        <span class="muted">-</span>
                    @endif
                </td>
                <td>
                    <a href="{!! $orderShowUrl !!}">详情</a>
                </td>
            </tr>
        @empty
            <tr>
                <td colspan="13" class="muted table-empty">暂无关联平台订单。</td>
            </tr>
        @endforelse
        </tbody>
    </table>

    {{ $platformOrders->links('pagination.admin') }}
    </div>
</div>
@endsection
