<?php

namespace App\Livewire\UploadExam;

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\On;
use Filament\Notifications\Notification;
use App\Jobs\ProcessOCRRecord;
use Illuminate\Support\Facades\Storage;

class UploadForm extends Component
{
    use WithFileUploads;

    public ?string $teacherId = null;
    public ?string $studentId = null;
    public $uploadedImages = [];
    public bool $isUploading = false;

    public function mount($teacherId = null, $studentId = null)
    {
        $this->teacherId = $teacherId;
        $this->studentId = $studentId;
    }

    public function handleSubmit()
    {
        // 验证图片
        if (empty($this->uploadedImages)) {
            Notification::make()
                ->title('请上传试卷图片')
                ->danger()
                ->send();
            return;
        }

        $this->isUploading = true;

        try {
            // 保存图片
            $savedImages = [];
            foreach ($this->uploadedImages as $image) {
                $path = $image->store('exam-papers', 'public');
                $savedImages[] = [
                    'path' => $path,
                    'original_name' => $image->getClientOriginalName(),
                    'size' => $image->getSize(),
                ];
            }

            // 创建 OCR 记录（使用正确的字段名）
            $ocrRecord = \App\Models\OCRRecord::create([
                'user_id' => $this->studentId,
                'paper_title' => '待OCR识别',
                'paper_type' => null, // OCR识别
                'file_path' => $savedImages[0]['path'], // 只存储第一张图片的路径
                'image_count' => count($savedImages),
                'status' => 'processing',
            ]);

            // 派发 OCR 处理任务
            ProcessOCRRecord::dispatch($ocrRecord->id);

            Notification::make()
                ->title('上传成功')
                ->body('图片已上传,正在进行 OCR 识别...')
                ->success()
                ->send();

            // 立即跳转到 OCR 详情页,不等待识别完成
            $this->redirect('/admin/ocr-record-view/' . $ocrRecord->id);

        } catch (\Exception $e) {
            Notification::make()
                ->title('上传失败')
                ->body($e->getMessage())
                ->danger()
                ->send();
        } finally {
            $this->isUploading = false;
        }
    }

    public function resetForm()
    {
        $this->uploadedImages = [];
        $this->currentOcrRecordId = null;
        $this->ocrStatus = null;
    }

    public function removeImage($index)
    {
        unset($this->uploadedImages[$index]);
        $this->uploadedImages = array_values($this->uploadedImages);
    }

    public function render()
    {
        return view('livewire.upload-exam.upload-form');
    }
}
