@extends('merchant_admin.layouts.app')

@section('title', '商家商品管理')
@section('page_title', '商家商品管理')

@section('content')
<div class="card mb-20">
    <p class="muted muted-tight">当前商品列表已按登录商家过滤，新增、编辑、删除商品都会限制在当前商家作用域内。</p>
    <p class="muted">当前已接入缓存：商品列表使用 {{ $cacheMeta['store'] }}，TTL {{ $cacheMeta['ttl'] }}；商品变更后会自动失效。</p>
    @php
        $exportQuery = http_build_query(array_filter($filters, fn ($value) => $value !== null && $value !== ''));
    @endphp
    <div class="card my-16">
        <h3 class="mt-0">批量导入商品</h3>
        <p class="muted">先下载模板，按模板填写后上传 CSV。商家模板不需要填写 `merchant_id`，系统会自动归属到当前登录商家。</p>
        <div class="card-link-list mb-12">
            <a href="/merchant-admin/products/import-template">下载导入模板</a>
            <a href="{{ '/merchant-admin/products/export' . ($exportQuery ? ('?' . $exportQuery) : '') }}">导出当前筛选结果 CSV</a>
            <a href="/merchant-admin/products/import-histories">查看独立导入历史页</a>
        </div>
        @if(session('import_result'))
            @php $importResult = session('import_result'); @endphp
            <div class="card section-dark mb-12">
                <div><strong>导入结果：</strong>成功 {{ $importResult['success'] ?? 0 }} 条，失败 {{ $importResult['failed'] ?? 0 }} 条。</div>
                @if(!empty($importResult['messages']))
                    <div class="muted mt-8">失败原因预览：</div>
                    <ul class="list-indent">@foreach($importResult['messages'] as $message)<li>{{ $message }}</li>@endforeach</ul>
                @endif
                @if(!empty($importResult['failure_file']))
                    <div class="mt-10"><a href="/merchant-admin/products/import-failures/{{ $importResult['failure_file'] }}">下载失败明细 CSV</a></div>
                @endif
            </div>
        @endif
        <form method="post" action="/merchant-admin/products/import" enctype="multipart/form-data">@csrf <div class="actions"><input type="file" name="import_file" accept=".csv,text/csv"><button type="submit">开始导入</button></div></form>

        <div class="mt-16">
            <div class="actions-spread mb-10">
                <div><h4 class="mb-6">导入历史摘要</h4><div class="muted">商品页仅保留摘要与最近 5 条记录；完整筛选、分页与复盘请前往独立导入历史页。</div></div>
                <a href="/merchant-admin/products/import-histories">进入完整导入历史页</a>
            </div>
            <div class="grid-4 mb-12">
                <div class="stat-box"><div class="muted">累计导入批次</div><strong class="num-sm">{{ $importHistoryStats['total_imports'] ?? 0 }}</strong></div>
                <div class="stat-box"><div class="muted">累计成功商品</div><strong class="num-sm">{{ $importHistoryStats['total_success'] ?? 0 }}</strong></div>
                <div class="stat-box"><div class="muted">累计失败商品</div><strong class="num-sm">{{ $importHistoryStats['total_failed'] ?? 0 }}</strong></div>
                <div class="stat-box"><div class="muted">含失败批次</div><strong class="num-sm">{{ $importHistoryStats['warning_imports'] ?? 0 }}</strong></div>
            </div>
            <table>
                <thead><tr><th>ID</th><th>导入时间</th><th>上传文件</th><th>结果</th><th>失败明细</th></tr></thead>
                <tbody>
                @forelse($importHistories->take(5) as $history)
                    <tr>
                        <td>{{ $history->id }}</td><td>{{ $history->imported_at?->format('Y-m-d H:i:s') }}</td><td>{{ $history->file_name }}</td><td>@if(($history->failed_count ?? 0) > 0)<span class="result-warning">部分失败（{{ $history->failed_count }}）</span>@else<span class="result-success">成功</span>@endif</td>
                        <td>@if($history->failure_file && ($history->failure_file_available ?? false))<a href="/merchant-admin/products/import-failures/{{ $history->failure_file }}">下载</a>@elseif($history->failure_file)<span class="muted">已过保留期</span>@else<span class="muted">无</span>@endif</td>
                    </tr>
                @empty
                    <tr><td colspan="5" class="muted">暂无导入记录</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>
    <h3>商品分类</h3>
    <table class="mb-20">
        <thead><tr><th>ID</th><th>分类名称</th><th>Slug</th><th>状态</th><th>排序</th><th>说明</th></tr></thead>
        <tbody>
        @forelse($categories as $category)
            <tr><td>{{ $category->id }}</td><td>{{ $category->name }}</td><td>{{ $category->slug }}</td><td>{{ $category->status }}</td><td>{{ $category->sort }}</td><td>{{ $category->description }}</td></tr>
        @empty
            <tr><td colspan="6" class="muted">暂无分类</td></tr>
        @endforelse
        </tbody>
    </table>

    <h3>筛选条件</h3>
    <form method="get" action="/merchant-admin/products" class="mb-20">
        <div class="grid-4">
            <select name="category_id"><option value="">全部分类</option>@foreach($categories as $category)<option value="{{ $category->id }}" @selected($filters['category_id'] === (string) $category->id)>{{ $category->name }}</option>@endforeach</select>
            <select name="status"><option value="">全部状态</option>@foreach($filterOptions['statuses'] as $status)<option value="{{ $statusLabels[$status] ?? $status }}" @selected($filters['status'] === $status)>{{ $statusLabels[$status] ?? $status }}</option>@endforeach</select>
            <input name="keyword" placeholder="标题 / slug / SKU" value="{{ $filters['keyword'] }}">
            <input type="number" step="0.01" min="0" name="min_price" placeholder="最低价格" value="{{ $filters['min_price'] }}">
            <input type="number" step="0.01" min="0" name="max_price" placeholder="最高价格" value="{{ $filters['max_price'] }}">
            <input type="number" min="0" name="min_stock" placeholder="最低库存" value="{{ $filters['min_stock'] }}">
            <input type="number" min="0" name="max_stock" placeholder="最高库存" value="{{ $filters['max_stock'] }}">
            <select name="sort">@foreach($filterOptions['sortOptions'] as $sortValue => $sortLabel)<option value="{{ $sortValue }}" @selected(($filters['sort'] ?? 'latest') === $sortValue)>{{ $sortLabel }}</option>@endforeach</select>
        </div>
        <div class="mt-12 actions"><button type="submit">筛选</button><a href="/merchant-admin/products">重置</a></div>
    </form>

    <div class="card section-dark my-20"><h3 class="mt-0">当前筛选摘要</h3><div class="grid-4">@foreach($activeFilterSummary as $summaryLabel => $summaryValue)<div class="summary-box"><div class="muted">{{ $summaryLabel }}</div><strong class="num-md">{{ $summaryValue }}</strong></div>@endforeach</div></div>

    <div class="card my-20"><h3 class="mt-0">商品运营汇总</h3><div class="grid-4"><div class="stat-box"><div class="muted">商品总数</div><strong class="num-md">{{ $summaryStats['total_products'] ?? 0 }}</strong></div><div class="stat-box"><div class="muted">总库存</div><strong class="num-md">{{ $summaryStats['total_stock'] ?? 0 }}</strong></div><div class="stat-box"><div class="muted">总货值</div><strong class="num-md">¥{{ number_format($summaryStats['total_stock_value'] ?? 0, 2) }}</strong></div><div class="stat-box"><div class="muted">平均售价</div><strong class="num-md">¥{{ number_format($summaryStats['average_price'] ?? 0, 2) }}</strong></div></div></div>

    <div class="card section-dark card-spaced">
        <h3 class="mt-0">运营关注项</h3>
        <div class="grid-3">
            <div class="focus-box">
                <div class="muted">商品盘面</div>
                <strong class="text-md">{{ $operationsFocus['headline'] ?? '当前商家商品运营信息已就绪。' }}</strong>
                <div class="muted mt-8">建议动作</div>
                <div class="inline-links mt-6">
                    @foreach(($operationsFocus['actions'] ?? []) as $action)
                        <a href="{{ $action['url'] }}">{{ $action['label'] }}</a>
                    @endforeach
                </div>
            </div>
            <div class="focus-box">
                <div class="muted">当前信号</div>
                <div class="grid-3 mt-8">
                    @foreach(($operationsFocus['signals'] ?? []) as $label => $value)
                        <div class="summary-box"><div class="muted">{{ $label }}</div><strong class="num-sm">{{ $value }}</strong></div>
                    @endforeach
                </div>
            </div>
            <div class="focus-box">
                <div class="muted">工作台导航</div>
                <div class="inline-links mt-8">
                    @foreach(($operationsFocus['workbench'] ?? []) as $label => $url)
                        <a href="{{ $url }}">{{ $label }}</a>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    <div class="card section-dark my-20">
        <h3 class="mt-0">商品状态统计</h3>
        @php
            $productBaseQuery = [
                'category_id' => $filters['category_id'] ?: null,
                'keyword' => $filters['keyword'] ?: null,
                'min_price' => $filters['min_price'] ?: null,
                'max_price' => $filters['max_price'] ?: null,
                'min_stock' => $filters['min_stock'] ?: null,
                'max_stock' => $filters['max_stock'] ?: null,
                'sort' => $filters['sort'] ?: 'latest',
            ];
        @endphp
        <div class="grid-4">
            <a href="{{ '/merchant-admin/products?' . http_build_query(array_filter($productBaseQuery, fn ($value) => $value !== null && $value !== '')) }}" class="status-link {{ $filters['status'] === '' ? 'is-active-dark' : '' }}"><div class="muted">全部</div><strong class="num-md">{{ $statusStats['all'] ?? 0 }}</strong></a>
            @foreach($filterOptions['statuses'] as $status)
                <a href="{{ '/merchant-admin/products?' . http_build_query(array_filter(array_merge($productBaseQuery, ['status' => $status]), fn ($value) => $value !== null && $value !== '')) }}" class="status-link {{ $filters['status'] === $status ? 'is-active-dark' : '' }}"><div class="muted">{{ $statusLabels[$status] ?? $status }}</div><strong class="num-md">{{ $statusStats[$status] ?? 0 }}</strong></a>
            @endforeach
        </div>
    </div>

    <h3>新增商品</h3>
    <form method="post" action="/merchant-admin/products">
        @csrf
        <div class="grid-3">
            <input name="title" placeholder="商品标题" value="{{ old('title') }}">
            <input name="slug" placeholder="slug" value="{{ old('slug') }}">
            <input name="sku" placeholder="SKU" value="{{ old('sku') }}">
            <select name="category_id"><option value="">选择分类（可留空）</option>@foreach($categories as $category)<option value="{{ $category->id }}" @selected((string) old('category_id') === (string) $category->id)>{{ $category->name }}</option>@endforeach</select>
            <input name="price" placeholder="价格" value="{{ old('price') }}">
            <input name="stock" placeholder="库存" value="{{ old('stock') }}">
            <input name="summary" placeholder="简介" value="{{ old('summary') }}">
        </div>
        <div class="mt-12"><button type="submit">创建商品</button></div>
    </form>
</div>

<div class="card">
    <h3>商品列表</h3>
    <form id="merchant-batch-form" method="post" action="/merchant-admin/products/batch" onsubmit="return confirm('确认执行本次批量操作？');">
        @csrf
        @php
            // return_url：用于批量操作后回到当前列表（保留筛选上下文）。
            // 说明：不使用 request()->fullUrl()（可能包含域名），避免被后端“仅允许站内相对路径”规则拦截。
            // 同时：剔除 return_url 本身，避免出现嵌套导致 URL 膨胀。
            $currentQuery = request()->query();
            unset($currentQuery['return_url']);
            $selfWithoutReturn = '/' . ltrim(request()->path(), '/');
            if (count($currentQuery) > 0) {
                $selfWithoutReturn .= '?' . \Illuminate\Support\Arr::query($currentQuery);
            }
        @endphp
        <input type="hidden" name="return_url" value="{{ $selfWithoutReturn }}">
        <div class="actions mb-12">
            <select name="action"><option value="change_status">批量改状态</option><option value="change_category">批量改分类</option></select>
            <select name="status"><option value="">选择状态（用于批量改状态）</option>@foreach($filterOptions['statuses'] as $status)<option value="{{ $statusLabels[$status] ?? $status }}">{{ $statusLabels[$status] ?? $status }}</option>@endforeach</select>
            <select name="category_id"><option value="">清空分类 / 不指定（用于批量改分类）</option>@foreach($categories as $category)<option value="{{ $category->id }}">{{ $category->name }}</option>@endforeach</select>
            <button type="submit">执行批量操作</button>
        </div>
    </form>
    <p class="muted muted-tight">批量操作只会作用于当前登录商家可见商品，越权或已删除数据会被拦截。</p>
    <table>
        <thead><tr><th><input type="checkbox" data-check-all="merchant-products"></th><th>ID</th><th>标题</th><th>分类</th><th>SKU</th><th>售价/原价</th><th>库存</th><th>创建时间</th><th>更新时间</th><th>状态</th><th>操作</th></tr></thead>
        <tbody>
        @foreach($products as $product)
            <tr>
                <td><input type="checkbox" name="product_ids[]" value="{{ $product->id }}" data-check-item="merchant-products" form="merchant-batch-form"></td>
                <td>{{ $product->id }}</td>
                <td><form method="post" action="/merchant-admin/products/{{ $product->id }}" class="actions">@csrf <input name="title" value="{{ $product->title }}"></td>
                <td><select name="category_id"><option value="">未分类</option>@foreach($categories as $category)<option value="{{ $category->id }}" @selected($product->category_id === $category->id)>{{ $category->name }}</option>@endforeach</select></td>
                <td><input name="slug" value="{{ $product->slug }}" placeholder="slug" class="w-140 block mb-6"><input name="sku" value="{{ $product->sku }}" placeholder="SKU" class="w-140"></td>
                <td><input name="price" value="{{ $product->price }}" class="w-90 block mb-6"><div class="muted">原价：¥{{ number_format((float) $product->original_price, 2) }}</div></td>
                <td><input name="stock" value="{{ $product->stock }}" class="w-90"></td>
                <td>{{ $product->created_at?->format('Y-m-d H:i') }}</td>
                <td>{{ $product->updated_at?->format('Y-m-d H:i') }}</td>
                <td><select name="status"><option value="draft" @selected($product->status==='draft')>草稿</option><option value="published" @selected($product->status==='published')>已上架</option><option value="offline" @selected($product->status==='offline')>已下架</option></select></td>
                <td><button type="submit">更新</button></form><form method="post" action="/merchant-admin/products/{{ $product->id }}/delete" class="inline" onsubmit="return confirm('确定删除这个商品？');">@csrf <button type="submit">删除</button></form></td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const master = document.querySelector('[data-check-all="merchant-products"]');
        const items = document.querySelectorAll('[data-check-item="merchant-products"]');
        if (!master || !items.length) {
            return;
        }
        master.addEventListener('change', function () {
            items.forEach(function (item) {
                item.checked = master.checked;
            });
        });
    });
</script>

<div class="pagination-wrap">{{ $products->links() }}</div>
@endsection
