<?php

namespace Kylin\LawCase\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

/**
 * 报表导出 Job
 *
 * 异步生成案件报表并存储到文件系统。
 */
class ExportReport implements ShouldQueue
{
    use InteractsWithQueue, Queueable;

    public int $tries = 3;
    public int $timeout = 300;

    public function __construct(
        public string $reportType,
        public array $filters,
        public int $userId
    ) {}

    public function handle(): void
    {
        Log::info("报表导出: 类型={$this->reportType}, 用户={$this->userId}");

        $data = match ($this->reportType) {
            'case_statistics' => $this->exportCaseStatistics(),
            'fee_report' => $this->exportFeeReport(),
            default => [],
        };

        $fileName = "reports/{$this->reportType}_" . now()->format('YmdHis') . '.json';
        Storage::put($fileName, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        Log::info("报表导出完成: {$fileName}");
    }

    private function exportCaseStatistics(): array
    {
        return \Kylin\LawCase\Models\CaseModel::selectRaw('case_status, count(*) as count')
            ->groupBy('case_status')
            ->pluck('count', 'case_status')
            ->toArray();
    }

    private function exportFeeReport(): array
    {
        return \Kylin\LawCase\Models\Fee::selectRaw('approval_status, count(*) as count, sum(amount) as total')
            ->groupBy('approval_status')
            ->get()
            ->toArray();
    }
}
