<?php

namespace App\Filament\Resources\PreQuestionCandidateResource\Pages;

use App\Filament\Resources\PreQuestionCandidateResource;
use App\Models\PreQuestionCandidate;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;

class ListPreQuestionCandidates extends ListRecords
{
    protected static string $resource = PreQuestionCandidateResource::class;
    protected string $view = 'filament.resources.pre-question-candidate-resource.pages.list-pre-question-candidates';

    public array $paperTree = [];

    public array $summaryStats = [];

    protected function canCreate(): bool
    {
        return false;
    }

    protected function getTableQuery(): Builder
    {
        $query = PreQuestionCandidate::query();

        $importId = request()->input('import_id');
        $user = auth()->user();
        $isAdmin = $user && in_array($user->role, ['super_admin', 'admin'], true);

        if (!empty($importId)) {
            $query->where('import_id', (int) $importId);
        } elseif (!$isAdmin) {
            // 非管理员必须通过 import_id 进入，否则不展示任何数据
            $query->whereRaw('1=0');
        }

        // 默认隐藏被新解析覆盖的记录（可通过筛选器查看）
        if (!request()->has('tableFilters.status.value')) {
            $query->where('status', '!=', PreQuestionCandidate::STATUS_SUPERSEDED);
        }

        return $query;
    }

    public function mount(): void
    {
        parent::mount();

        $importId = request()->input('import_id');
        $query = PreQuestionCandidate::query()
            ->with(['sourcePaper', 'part'])
            ->when($importId, fn ($q) => $q->where('import_id', (int) $importId));

        $records = $query->get();

        $this->summaryStats = [
            'total' => $records->count(),
            'accepted' => $records->where('status', PreQuestionCandidate::STATUS_ACCEPTED)->count(),
            'reviewed' => $records->where('status', PreQuestionCandidate::STATUS_REVIEWED)->count(),
            'pending' => $records->where('status', PreQuestionCandidate::STATUS_PENDING)->count(),
            'rejected' => $records->where('status', PreQuestionCandidate::STATUS_REJECTED)->count(),
        ];

        $tree = [];
        foreach ($records as $record) {
            $paperId = $record->sourcePaper?->id ?? 0;
            $partId = $record->part?->id ?? 0;
            $paperTitle = $record->sourcePaper?->title ?? '未命名卷子';
            $partTitle = $record->part?->title ?? '未标注区块';

            $tree[$paperId]['title'] = $paperTitle;
            $tree[$paperId]['parts'][$partId]['title'] = $partTitle;
            $tree[$paperId]['parts'][$partId]['count'] = ($tree[$paperId]['parts'][$partId]['count'] ?? 0) + 1;
        }

        $this->paperTree = array_values(array_map(function ($paper) {
            $parts = $paper['parts'] ?? [];
            $paper['parts'] = array_values($parts);
            return $paper;
        }, $tree));
    }
}
