<?php

namespace App\Filament\Actions;

use App\Models\SopTemplate;
use App\Services\SopTemplateService;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Response;

class ExportSopTemplateAction extends Action
{
    public static function getDefaultName(): ?string
    {
        return 'export';
    }

    protected function setUp(): void
    {
        parent::setUp();

        $this->label('导出模板');

        $this->icon('heroicon-o-arrow-down-tray');

        $this->color('info');

        $this->action(function (SopTemplate $record) {
            $service = app(SopTemplateService::class);
            $json = $service->exportToJson($record);

            $fileName = sprintf(
                'sop_template_%s_%s.json',
                $record->id,
                now()->format('YmdHis')
            );

            Notification::make()
                ->title('导出成功')
                ->body('SOP 模板已成功导出')
                ->success()
                ->send();

            return Response::streamDownload(function () use ($json) {
                echo $json;
            }, $fileName, [
                'Content-Type' => 'application/json',
            ]);
        });
    }
}
