<?php

namespace App\Filament\Widgets;

use App\Models\Document;
use App\Models\Group;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class KnowledgeBaseStatsWidget extends BaseWidget
{
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        // 统计文档数据
        $totalDocuments = Document::count();
        $completedDocuments = Document::where('conversion_status', 'completed')->count();
        $failedDocuments = Document::where('conversion_status', 'failed')->count();
        $processingDocuments = Document::whereIn('conversion_status', ['pending', 'processing'])->count();
        
        // 统计分组数据
        $totalGroups = Group::count();
        
        // 计算转换成功率
        $conversionRate = $totalDocuments > 0 
            ? round(($completedDocuments / $totalDocuments) * 100, 1) 
            : 0;

        return [
            Stat::make('文档总数', $totalDocuments)
                ->description('知识库中的文档总数')
                ->descriptionIcon('heroicon-m-document-text')
                ->color('primary')
                ->chart([7, 12, 15, 18, 22, 25, $totalDocuments]),
            
            Stat::make('转换完成', $completedDocuments)
                ->description("成功率: {$conversionRate}%")
                ->descriptionIcon('heroicon-m-check-circle')
                ->color('success')
                ->chart([5, 10, 12, 15, 18, 20, $completedDocuments]),
            
            Stat::make('转换失败', $failedDocuments)
                ->description('需要重新处理')
                ->descriptionIcon('heroicon-m-x-circle')
                ->color('danger')
                ->url(route('filament.admin.resources.documents.index', ['tableFilters[conversion_status][value]' => 'failed'])),
            
            Stat::make('处理中', $processingDocuments)
                ->description('等待转换或转换中')
                ->descriptionIcon('heroicon-m-arrow-path')
                ->color('warning'),
            
            Stat::make('知识库分组', $totalGroups)
                ->description('专用知识库数量')
                ->descriptionIcon('heroicon-m-folder')
                ->color('info')
                ->url(route('filament.admin.resources.groups.index')),
        ];
    }
}
