<?php

namespace App\View\Components\ExamAnalysis;

use Illuminate\View\Component;
use App\Services\QuestionBankService;
use App\Services\KnowledgeGraphService;

class SimilarQuestions extends Component
{
    public array $similarQuestions = [];
    public array $knowledgePoint = [];

    public function __construct(
        public ?string $kpCode = null,
        public ?array $currentQuestion = null
    ) {
        if ($kpCode && $currentQuestion) {
            $this->knowledgePoint = $currentQuestion['knowledge_point'] ?? [];
            $this->similarQuestions = $this->getSimilarQuestions($kpCode);
        }
    }

    /**
     * 获取相似题目
     */
    protected function getSimilarQuestions(string $kpCode): array
    {
        $questions = [];

        try {
            // 1. 根据知识点从题库获取相似题目
            $questionBankService = app(QuestionBankService::class);

            // 确定难度：如果当前题目答错，推荐简单或同等难度的题目
            $difficulty = 'all';
            if (isset($this->currentQuestion['is_correct']) && !$this->currentQuestion['is_correct']) {
                $difficulty = 'easy'; // 推荐简单题目
            }

            // 调用题库API获取相似题目
            $response = $questionBankService->filterQuestions([
                'kp_codes' => $kpCode,
                'difficulty' => $difficulty,
                'per_page' => 5,
                'exclude_id' => $this->currentQuestion['question_bank_id'] ?? null
            ]);

            if (isset($response['data']) && !empty($response['data'])) {
                foreach ($response['data'] as $index => $q) {
                    $questions[] = [
                        'id' => $q['id'] ?? $q['question_id'] ?? uniqid(),
                        'title' => $q['stem'] ?? $q['content'] ?? '题目内容',
                        'difficulty' => $this->getDifficultyLabel($q['difficulty'] ?? 'medium'),
                        'difficulty_color' => $this->getDifficultyColor($q['difficulty'] ?? 'medium'),
                        'estimated_time' => $this->getEstimatedTime($q['difficulty'] ?? 'medium'),
                        'question_type' => $q['question_type'] ?? '选择题',
                        'score' => $q['score'] ?? 5,
                        'knowledge_point' => $this->knowledgePoint['name'] ?? $kpCode,
                    ];
                }
            }

            // 2. 如果题库没有足够的相似题目，使用推荐算法生成
            if (count($questions) < 2) {
                $questions = array_merge($questions, $this->generateRecommendedQuestions($kpCode));
            }
        } catch (\Exception $e) {
            \Log::error('获取相似题目失败', [
                'kp_code' => $kpCode,
                'error' => $e->getMessage()
            ]);

            // 返回默认推荐题目
            $questions = $this->getDefaultRecommendations($kpCode);
        }

        return array_slice($questions, 0, 3); // 最多返回3道题
    }

    /**
     * 生成推荐题目
     */
    protected function generateRecommendedQuestions(string $kpCode): array
    {
        // 基于知识点生成推荐题目的描述
        $recommendations = [];

        $kpName = $this->knowledgePoint['name'] ?? $kpCode;

        // 根据掌握程度推荐不同类型的题目
        if (isset($this->currentQuestion['is_correct']) && !$this->currentQuestion['is_correct']) {
            // 答错的题目，推荐基础练习
            $recommendations[] = [
                'id' => 'rec_1',
                'title' => "{$kpName}基础练习题 - 巩固核心概念",
                'difficulty' => '简单',
                'difficulty_color' => 'green',
                'estimated_time' => '3分钟',
                'question_type' => '基础题',
                'score' => 3,
                'knowledge_point' => $kpName,
            ];

            $recommendations[] = [
                'id' => 'rec_2',
                'title' => "{$kpName}变式练习题 - 提升解题能力",
                'difficulty' => '中等',
                'difficulty_color' => 'blue',
                'estimated_time' => '5分钟',
                'question_type' => '变式题',
                'score' => 5,
                'knowledge_point' => $kpName,
            ];
        } else {
            // 答对的题目，推荐提高练习
            $recommendations[] = [
                'id' => 'rec_3',
                'title' => "{$kpName}提高题 - 挑战更高难度",
                'difficulty' => '较难',
                'difficulty_color' => 'red',
                'estimated_time' => '8分钟',
                'question_type' => '提高题',
                'score' => 8,
                'knowledge_point' => $kpName,
            ];
        }

        return $recommendations;
    }

    /**
     * 获取默认推荐
     */
    protected function getDefaultRecommendations(string $kpCode): array
    {
        return [
            [
                'id' => 'default_1',
                'title' => '相关知识点基础练习',
                'difficulty' => '简单',
                'difficulty_color' => 'green',
                'estimated_time' => '3分钟',
                'question_type' => '基础题',
                'score' => 3,
                'knowledge_point' => $this->knowledgePoint['name'] ?? $kpCode,
            ],
            [
                'id' => 'default_2',
                'title' => '相关知识点综合练习',
                'difficulty' => '中等',
                'difficulty_color' => 'blue',
                'estimated_time' => '5分钟',
                'question_type' => '综合题',
                'score' => 5,
                'knowledge_point' => $this->knowledgePoint['name'] ?? $kpCode,
            ],
        ];
    }

    /**
     * 获取难度标签
     */
    protected function getDifficultyLabel(string $difficulty): string
    {
        return match($difficulty) {
            'easy' => '简单',
            'medium' => '中等',
            'hard' => '较难',
            default => '中等',
        };
    }

    /**
     * 获取难度颜色
     */
    protected function getDifficultyColor(string $difficulty): string
    {
        return match($difficulty) {
            'easy' => 'green',
            'medium' => 'blue',
            'hard' => 'red',
            default => 'blue',
        };
    }

    /**
     * 获取预计完成时间
     */
    protected function getEstimatedTime(string $difficulty): string
    {
        return match($difficulty) {
            'easy' => '3分钟',
            'medium' => '5分钟',
            'hard' => '8分钟',
            default => '5分钟',
        };
    }

    public function render()
    {
        return view('components.exam-analysis.similar-questions');
    }
}