<?php

namespace App\Livewire\UploadExam;

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

class UploadForm extends Component
{
    use WithFileUploads;

    public ?string $teacherId = null;
    public ?string $studentId = null;
    public ?string $selectedPaperId = null;
    public ?string $mode = 'ocr'; // 'ocr' 或 'chatgpt'
    public $uploadedImages = [];
    public bool $isUploading = false;

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

    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(),
                ];
            }

            // 获取图片URL
            $imageUrl = asset('storage/' . $savedImages[0]['path']);

            // 根据模式处理
            if ($this->mode === 'chatgpt') {
                // ChatGPT模式：直接调用ChatGPT分析
                $this->handleChatGPTAnalysis($imageUrl);
            } else {
                // OCR模式：保持原有逻辑
                $this->handleOCRProcessing($savedImages);
            }

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

    /**
     * 处理OCR识别
     */
    private function handleOCRProcessing(array $savedImages)
    {
        // 获取试卷名称
        $paperTitle = '待OCR识别';
        if ($this->selectedPaperId) {
            $paper = \App\Models\Paper::where('paper_id', $this->selectedPaperId)->first();
            if ($paper) {
                $paperTitle = $paper->paper_name;
            }
        }

        // 创建 OCR 记录
        $ocrRecord = \App\Models\OCRRecord::create([
            'user_id' => $this->studentId,
            'student_id' => $this->studentId,
            'paper_title' => $paperTitle,
            'paper_type' => null,
            'file_path' => $savedImages[0]['path'],
            'image_count' => count($savedImages),
            'status' => 'processing',
            'analysis_id' => $this->selectedPaperId,
        ]);

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

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

        // 跳转
        if ($this->selectedPaperId && str_starts_with($this->selectedPaperId, 'paper_')) {
            $this->redirect('/admin/ocr-paper-analysis/' . $ocrRecord->id);
        } else {
            $this->redirect('/admin/ocr-record-view/' . $ocrRecord->id);
        }
    }

    /**
     * 处理ChatGPT分析
     */
    private function handleChatGPTAnalysis(string $imageUrl)
    {
        if (!$this->selectedPaperId) {
            throw new \Exception('请先选择试卷');
        }

        // 调用ChatGPT分析
        $chatGPTService = app(ChatGPTAnalysisService::class);
        $result = $chatGPTService->analyzeExamPaper($this->selectedPaperId, $imageUrl);

        if ($result['success']) {
            // 保存分析结果
            $saved = $chatGPTService->saveAnalysisResult($this->selectedPaperId, $result['data']);

            if ($saved) {
                Notification::make()
                    ->title('ChatGPT分析完成')
                    ->body('已成功分析 ' . count($result['data']['questions'] ?? []) . ' 道题目')
                    ->success()
                    ->send();

                // 跳转到分析页面
                $this->redirect('/admin/exam-analysis?paperId=' . $this->selectedPaperId);
            } else {
                throw new \Exception('分析结果保存失败');
            }
        } else {
            throw new \Exception($result['error'] ?? 'ChatGPT分析失败');
        }
    }

    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');
    }
}
