<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Student;
use App\Services\KnowledgeMasteryService;
use App\Services\MasteryCalculator;
use Illuminate\Support\Facades\DB;

class StudentKnowledgeGraph extends Component
{
    public $selectedStudentId = null;
    public $selectedStudent = null;
    public $knowledgePoints = [];
    public $dependencies = [];
    public $masteryData = [];
    public $statistics = [];
    public $learningPath = [];
    public $isLoading = false;

    public $students = [];

    protected $rules = [
        'selectedStudentId' => 'required|exists:students,student_id',
    ];

    public function mount()
    {
        $this->loadStudents();
    }

    public function updatedSelectedStudentId($value)
    {
        if ($value) {
            $this->loadStudentData($value);
        } else {
            $this->resetData();
        }
    }

    public function loadStudents()
    {
        $query = DB::table('students')
            ->select('student_id', 'name', 'grade', 'class_name')
            ->orderBy('grade')
            ->orderBy('class_name')
            ->orderBy('name');

        // 如果是老师，只加载自己的学生
        $currentUser = auth()->user();
        if ($currentUser?->isTeacher() ?? false) {
            $teacherId = $currentUser->teacher?->teacher_id;
            if ($teacherId) {
                $query->where('teacher_id', $teacherId);
            }
        }

        $this->students = $query
            ->get()
            ->map(function ($student) {
                return [
                    'id' => $student->student_id,
                    'label' => "{$student->name} ({$student->grade}-{$student->class_name})",
                ];
            })
            ->toArray();
    }

    public function loadStudentData($studentId)
    {
        $this->isLoading = true;

        try {
            // 获取学生信息
            $this->selectedStudent = DB::table('students')
                ->where('student_id', $studentId)
                ->first();

            // 使用本地的KnowledgeMasteryService获取知识图谱数据
            $this->fetchKnowledgeGraphData($studentId);

        } catch (\Exception $e) {
            session()->flash('error', '加载数据失败：' . $e->getMessage());
            \Log::error('加载学生知识图谱失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage(),
            ]);
        }

        $this->isLoading = false;
    }

    private function fetchKnowledgeGraphData($studentId)
    {
        try {
            // 使用本地的KnowledgeMasteryService
            $masteryService = app(KnowledgeMasteryService::class);
            $masteryCalculator = app(MasteryCalculator::class);

            // 获取掌握度概览
            $overview = $masteryCalculator->getStudentMasteryOverview($studentId);

            // 获取图谱数据
            $graphResult = $masteryService->getGraph($studentId);

            // 设置掌握度数据
            $this->masteryData = $graphResult['success'] ? $graphResult['data'] : [
                'nodes' => [],
                'edges' => [],
            ];

            // 设置统计信息
            $this->statistics = [
                'total_knowledge_points' => $overview['total_knowledge_points'] ?? 0,
                'average_mastery' => $overview['average_mastery_level'] ?? 0,
                'mastered_count' => $overview['mastered_knowledge_points'] ?? 0,
                'good_count' => $overview['good_knowledge_points'] ?? 0,
                'weak_count' => $overview['weak_knowledge_points'] ?? 0,
            ];

            // 构建学习路径（基于薄弱点）
            $this->buildLearningPath($overview);

            // 构建知识点数据（用于兼容性）
            $this->buildKnowledgePointsData($overview);

        } catch (\Exception $e) {
            \Log::error('获取知识图谱数据失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage(),
            ]);

            // 使用空数据作为fallback
            $this->masteryData = [
                'nodes' => [],
                'edges' => [],
            ];
            $this->statistics = [];
        }
    }

    /**
     * 构建学习路径
     */
    private function buildLearningPath(array $overview)
    {
        $this->learningPath = [];

        // 从薄弱点生成学习建议
        foreach ($overview['weak_knowledge_points_list'] ?? [] as $weakPoint) {
            $this->learningPath[] = [
                'kp_code' => $weakPoint->kp_code ?? '',
                'current_mastery' => floatval($weakPoint->mastery_level ?? 0),
                'target_mastery' => 0.7,
                'priority' => 'high',
                'estimated_hours' => 2,
                'recommendation' => '重点练习此知识点',
            ];
        }
    }

    /**
     * 构建知识点数据（用于兼容性）
     */
    private function buildKnowledgePointsData(array $overview)
    {
        $this->knowledgePoints = [];

        foreach ($overview['details'] ?? [] as $detail) {
            $kpCode = $detail->kp_code ?? '';
            $mastery = floatval($detail->mastery_level ?? 0);

            $this->knowledgePoints[$kpCode] = [
                'name' => $kpCode,
                'mastery' => $mastery,
                'color' => $this->getMasteryColor($mastery),
                'size' => $this->getMasterySize($mastery),
            ];
        }
    }

    private function getMasteryColor($mastery)
    {
        if ($mastery >= 0.8) return '#10b981'; // 绿色 - 优秀
        if ($mastery >= 0.6) return '#3b82f6'; // 蓝色 - 良好
        if ($mastery >= 0.4) return '#f59e0b'; // 黄色 - 中等
        if ($mastery >= 0.2) return '#f97316'; // 橙色 - 待提高
        return '#ef4444'; // 红色 - 薄弱
    }

    private function getMasterySize($mastery)
    {
        return max(10, $mastery * 40); // 最小10px，最大40px
    }

    private function resetData()
    {
        $this->selectedStudent = null;
        $this->knowledgePoints = [];
        $this->dependencies = [];
        $this->masteryData = [];
        $this->statistics = [];
        $this->learningPath = [];
    }

    public function render()
    {
        return view('livewire.student-knowledge-graph');
    }
}
