<?php

namespace App\Filament\Pages;

use App\Services\KnowledgeGraphService;
use App\Services\KnowledgeMasteryService;
use App\Services\MasteryCalculator;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;

class StudentAnalysis extends Page
{
    protected static ?string $title = '学生掌握度分析';
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';
    protected static ?string $navigationLabel = '学生分析';
    protected static string|UnitEnum|null $navigationGroup = '其他';
    protected static ?int $navigationSort = 24;

    protected string $view = 'filament.pages.student-analysis-simple';

    /**
     * 禁用导航显示（与"学生仪表板"功能重复）
     */
    public static function shouldRegisterNavigation(): bool
    {
        return false;
    }

    // 当前选中的学生
    public ?string $selectedStudentId = null;
    public array $studentInfo = [];
    public array $masteryData = [];
    public array $weaknesses = [];
    public array $skills = [];
    public array $learningPath = [];
    public array $knowledgePointHierarchy = []; // 【新增】父子知识点层级关系

    /**
     * 获取所有学生列表
     */
    public function students(): array
    {
        return \App\Models\Student::all()->toArray();
    }

    public function updatedSelectedStudentId($value)
    {
        if ($value) {
            $this->loadAnalysisData();
        } else {
            $this->reset(['studentInfo', 'masteryData', 'weaknesses', 'skills', 'learningPath']);
        }
    }

    public function loadAnalysisData()
    {
        if (!$this->selectedStudentId) {
            return;
        }

        // 使用本地的KnowledgeMasteryService
        $masteryService = app(KnowledgeMasteryService::class);
        $masteryCalculator = app(MasteryCalculator::class);

        // 1. 获取学生掌握度数据
        $stats = $masteryService->getStats($this->selectedStudentId);
        $this->studentInfo = $stats['success'] ? $stats['data'] : [];

        // 2. 获取掌握度概览
        $overview = $masteryCalculator->getStudentMasteryOverview($this->selectedStudentId);

        // 3. 获取薄弱点列表（掌握度 < 0.5）
        $this->weaknesses = array_filter($overview['details'] ?? [], function($item) {
            return floatval($item->mastery_level ?? 0) < 0.5;
        });

        // 4. 获取技能熟练度（从掌握度数据转换）
        $this->skills = $this->getSkillsData($overview);

        // 5. 获取学习路径建议（基于薄弱点）
        $this->learningPath = $this->generateLearningPath($this->weaknesses);

        // 6. 获取知识点掌握度详情
        $this->masteryData = $overview['details'] ?? [];

        // 7. 【新增】获取父子知识点层级关系
        $this->knowledgePointHierarchy = $this->getKnowledgePointHierarchy($this->selectedStudentId);
    }

    /**
     * 从掌握度数据转换技能数据
     */
    private function getSkillsData(array $overview): array
    {
        $skills = [];
        foreach ($overview['details'] ?? [] as $detail) {
            $skills[] = [
                'skill_name' => $detail->kp_code,
                'proficiency' => floatval($detail->mastery_level ?? 0),
                'mastery_level' => floatval($detail->mastery_level ?? 0),
            ];
        }
        return $skills;
    }

    /**
     * 基于薄弱点生成学习路径
     */
    private function generateLearningPath(array $weaknesses): array
    {
        $path = [];
        foreach (array_slice($weaknesses, 0, 5) as $weakness) {
            $path[] = [
                'kp_code' => $weakness->kp_code ?? '',
                'recommendation' => '建议重点练习此知识点',
                'priority' => 'high',
                'estimated_hours' => 2,
            ];
        }
        return $path;
    }

    /**
     * 【新增】获取父子知识点层级关系
     */
    private function getKnowledgePointHierarchy(string $studentId): array
    {
        try {
            // 使用MasteryCalculator的getStudentMasteryOverviewWithHierarchy方法
            $masteryCalculator = app(MasteryCalculator::class);
            $hierarchyData = $masteryCalculator->getStudentMasteryOverviewWithHierarchy($studentId);

            // 构建父子关系数据
            $hierarchy = [
                'parent_mastery_levels' => $hierarchyData['parent_mastery_levels'] ?? [],
                'child_knowledge_points' => [], // 每个父节点下的子知识点
            ];

            // 获取所有知识点及其父节点信息
            $allKnowledgePoints = \DB::connection('mysql')
                ->table('knowledge_points as kp')
                ->leftJoin('student_knowledge_mastery as skm', function($join) use ($studentId) {
                    $join->on('kp.kp_code', '=', 'skm.kp_code')
                         ->where('skm.student_id', '=', $studentId);
                })
                ->select([
                    'kp.kp_code',
                    'kp.cn_name as kp_name',
                    'kp.parent_kp_code',
                    'kp.level',
                    'skm.mastery_level',
                    'skm.confidence_level',
                    'skm.total_attempts',
                    'skm.correct_attempts',
                ])
                ->get();

            // 按父节点分组
            foreach ($allKnowledgePoints as $kp) {
                $parentCode = $kp->parent_kp_code ?: 'ROOT'; // 根节点标记

                if (!isset($hierarchy['child_knowledge_points'][$parentCode])) {
                    $hierarchy['child_knowledge_points'][$parentCode] = [];
                }

                $hierarchy['child_knowledge_points'][$parentCode][] = [
                    'kp_code' => $kp->kp_code,
                    'kp_name' => $kp->kp_name ?? $kp->kp_code,
                    'level' => $kp->level ?? 1,
                    'mastery_level' => floatval($kp->mastery_level ?? 0),
                    'confidence_level' => floatval($kp->confidence_level ?? 0),
                    'total_attempts' => intval($kp->total_attempts ?? 0),
                    'correct_attempts' => intval($kp->correct_attempts ?? 0),
                ];
            }

            return $hierarchy;

        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('获取知识点层级关系失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return [
                'parent_mastery_levels' => [],
                'child_knowledge_points' => []
            ];
        }
    }

    private function getMasteryDetails(string $studentId): array
    {
        try {
            // 从MySQL直接查询学生掌握度详情
            $db = app('db');
            $db->connection('remote_mysql');

            $masteryRecords = \Illuminate\Support\Facades\DB::connection('remote_mysql')
                ->table('student_mastery as sm')
                ->join('knowledge_points as kp', 'sm.kp', '=', 'kp.kp')
                ->where('sm.student_id', $studentId)
                ->select([
                    'sm.kp as kp_code',
                    'kp.cn_name as kp_name',
                    'sm.mastery',
                    'sm.stability',
                    'sm.update_time'
                ])
                ->orderBy('sm.mastery', 'asc')
                ->limit(50)
                ->get()
                ->toArray();

            return array_map(function ($record) {
                return [
                    'kp_code' => $record->kp_code,
                    'kp_name' => $record->kp_name,
                    'mastery' => (float) $record->mastery,
                    'stability' => (float) $record->stability,
                    'update_time' => $record->update_time,
                    'mastery_level' => $this->getMasteryLevel((float) $record->mastery),
                    'weakness_score' => 1.0 - (float) $record->mastery
                ];
            }, $masteryRecords);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('获取掌握度详情失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    private function getMasteryLevel(float $mastery): string
    {
        if ($mastery >= 0.9) return '优秀';
        if ($mastery >= 0.8) return '良好';
        if ($mastery >= 0.7) return '中等';
        if ($mastery >= 0.6) return '及格';
        return '需提升';
    }

    public function getMasteryColor(float $mastery): string
    {
        if ($mastery >= 0.9) return '#10b981'; // emerald-500
        if ($mastery >= 0.8) return '#34d399'; // emerald-400
        if ($mastery >= 0.7) return '#fbbf24'; // amber-400
        if ($mastery >= 0.6) return '#fb923c'; // orange-400
        return '#ef4444'; // red-500
    }

    public function getMasteryBgColor(float $mastery): string
    {
        if ($mastery >= 0.9) return 'bg-emerald-100';
        if ($mastery >= 0.8) return 'bg-emerald-50';
        if ($mastery >= 0.7) return 'bg-amber-100';
        if ($mastery >= 0.6) return 'bg-orange-100';
        return 'bg-red-100';
    }

    public function generateStudyPlan()
    {
        if (!$this->selectedStudentId || empty($this->weaknesses)) {
            return;
        }

        // TODO: 调用LearningAnalytics服务生成学习计划
        // 这里可以调用专门的API来生成个性化学习计划

        return redirect()->route('filament.admin.auth.learning-plan', [
            'student_id' => $this->selectedStudentId
        ]);
    }

    public function exportAnalysis()
    {
        if (!$this->selectedStudentId) {
            return;
        }

        // TODO: 导出分析报告为PDF或Excel
        // 可以调用专门的导出服务
    }
}
