<?php

namespace App\Filament\Resources\DocumentResource\Pages;

use App\Filament\Resources\DocumentResource;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class EditDocument extends EditRecord
{
    protected static string $resource = DocumentResource::class;

    private ?string $previousFilePath = null;

    protected function getHeaderActions(): array
    {
        return [
            Actions\ViewAction::make()
                ->label('查看'),
            Actions\DeleteAction::make()
                ->label('删除'),
        ];
    }

    protected function mutateFormDataBeforeFill(array $data): array
    {
        $this->previousFilePath = $data['file_path'] ?? null;

        if (isset($data['file_path'])) {
            $data['file'] = $data['file_path'];
        }

        return $data;
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        $currentFile = $data['file'] ?? null;

        // 检测文件是否变更：与填充时记录的原始路径比较
        if ($currentFile && $currentFile !== $this->previousFilePath) {
            // 删除旧文件
            if ($this->previousFilePath && Storage::disk('local')->exists($this->previousFilePath)) {
                Storage::disk('local')->delete($this->previousFilePath);
            }
            if ($this->record->markdown_path && Storage::disk('markdown')->exists($this->record->markdown_path)) {
                Storage::disk('markdown')->delete($this->record->markdown_path);
            }

            $data['file_path'] = $currentFile;
            $data['file_name'] = $data['file_name'] ?? basename($currentFile);
            $data['file_size'] = Storage::disk('local')->size($currentFile);
            $data['mime_type'] = Storage::disk('local')->mimeType($currentFile);

            // 重置转换状态，触发重新转换
            $data['conversion_status'] = 'pending';
            $data['markdown_path'] = null;
            $data['conversion_error'] = null;
        }

        unset($data['file']);

        return $data;
    }

    protected function afterSave(): void
    {
        // 刷新模型以获取最新数据库状态
        $this->record->refresh();

        if ($this->record->conversion_status === 'pending') {
            $conversionService = app(\App\Services\DocumentConversionService::class);
            $conversionService->queueConversion($this->record);
        }
    }

    protected function getSavedNotification(): ?Notification
    {
        return Notification::make()
            ->success()
            ->title('文档更新成功')
            ->body('文档信息已成功更新。');
    }
}
