@php
    // 【参考试卷和判卷格式】学情报告以3开头 + 12位paper_id数字部分
    $rawPaperId = $paper['id'] ?? $paper['paper_id'] ?? 'unknown';
    // 从 paper_id 提取12位数字部分（格式: paper_xxxxxxxxxxxx）
    if (preg_match('/paper_(\d{12})/', $rawPaperId, $matches)) {
        $paperIdNum = $matches[1];
    } else {
        // 兼容旧格式，取数字部分或生成哈希
        $paperIdNum = preg_replace('/[^0-9]/', '', $rawPaperId);
        $paperIdNum = str_pad(substr($paperIdNum, 0, 12), 12, '0', STR_PAD_LEFT);
    }
    $reportCode = '3' . $paperIdNum; // 学情报告识别码：3 + 12位数字
    $averageMastery = isset($mastery['average']) ? number_format($mastery['average'] * 100, 1) . '%' : '无数据';

    // 【修复】从insights中获取AI分析结果（而不是从analysis_data）
    $questionAnalysis = $insights ?? [];
@endphp
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>学情报告 - {{ $paper['name'] ?? '试卷' }}</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
    <style>
        @page {
            size: A4;
            margin: 1.5cm 1.5cm 2cm 1.5cm;
            @top-left {
                content: "知了数学";
                font-size: 10px;
                color: #666;
            }
            @top-right {
                content: "{{ $reportCode }}";
                font-size: 10px;
                color: #666;
            }
            @bottom-left {
                content: "{{ $reportCode }}";
                font-size: 10px;
                color: #666;
            }
            @bottom-right {
                content: counter(page) "/" counter(pages);
                font-size: 10px;
                color: #666;
            }
        }
        * { box-sizing: border-box; }
        body {
            font-family: "SimSun", "Songti SC", serif;
            margin: 0;
            padding: 0;
            color: #000;
            background: #fff;
            font-size: 12px;
            line-height: 1.6;
        }
        h1, h2, h3 { margin: 0; color: #000; }
        .card { background: #fff; border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px 16px; margin-bottom: 12px; box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04); }
        .header { text-align: center; margin-bottom: 1rem; border-bottom: 2px solid #000; padding-bottom: 0.5rem; }
        .school-name { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
        .paper-title { font-size: 20px; font-weight: bold; margin-bottom: 15px; }
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
        .tag { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 12px; color: #374151; background: #e5e7eb; }
        .section-title { font-size: 16px; margin-bottom: 10px; display: flex; align-items: center; gap: 8px; }
        .pill { padding: 4px 10px; border-radius: 999px; font-size: 12px; }
        .pill.green { background: #ecfdf3; color: #15803d; }
        .pill.amber { background: #fef3c7; color: #b45309; }
        .pill.red { background: #fef2f2; color: #b91c1c; }
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th, td { padding: 8px 10px; border-bottom: 1px solid #e5e7eb; text-align: left; vertical-align: top; }
        th { background: #f3f4f6; color: #111827; }
        .muted { color: #6b7280; font-size: 12px; }
        .progress-wrap { background: #f3f4f6; border-radius: 999px; overflow: hidden; height: 10px; }
        .progress-bar { height: 100%; background: linear-gradient(90deg, #4f46e5, #10b981); }
        .recommend-card { border: 1px dashed #cbd5e1; border-radius: 10px; padding: 10px 12px; margin-bottom: 8px; background: #f8fafc; }
    </style>
</head>
<body>
    <div class="page">
        <div class="header">
            <h1 class="paper-title">学情分析报告</h1>
            <div style="margin-top: 10px; font-size: 14px;">
                试卷：{{ $paper['name'] ?? '-' }} | 学生：{{ $student['name'] ?? '-' }} | 年级：{{ $student['grade'] ?? '-' }}
            </div>
            <div style="margin-top: 6px; font-size: 14px;">
                题目数：{{ is_array($questions ?? null) ? count($questions) : ($paper['total_questions'] ?? '-') }}
            </div>
        </div>

    <div class="card">
        <div class="section-title">知识点掌握度</div>
        @php
            // 【修复】过滤掉K-GENERAL等通用知识点，只显示有值的知识点
            $filteredMasteryItems = [];
            if (!empty($mastery['items'])) {
                foreach ($mastery['items'] as $item) {
                    $kpCode = $item['kp_code'] ?? '';
                    $masteryLevel = $item['mastery_level'] ?? 0;

                    // 过滤条件：不是通用知识点，且掌握度>0
                    if (!in_array($kpCode, ['K-GENERAL', 'GENERAL', 'DEFAULT']) && $masteryLevel > 0) {
                        $filteredMasteryItems[] = $item;
                    }
                }
            }
        @endphp

        @if(!empty($filteredMasteryItems))
            @foreach($filteredMasteryItems as $item)
                @php
                    $pct = min(100, max(0, ($item['mastery_level'] ?? 0) * 100));
                    $barColor = $pct >= 80 ? '#10b981' : ($pct >= 60 ? '#f59e0b' : '#ef4444');
                    $delta = $item['mastery_change'] ?? null;
                    // 只有当有变化值时才显示变化信息
                    $changeText = '';
                    if ($delta !== null && $delta !== '' && abs($delta) > 0.001) {
                        $changeText = ($delta > 0 ? '↑ ' : '↓ ') . number_format(abs($delta) * 100, 1) . '%';
                    }
                @endphp
                <div style="margin-bottom:12px; padding: 8px; border: 1px solid #e5e7eb; border-radius: 6px;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 6px;">
                        <div style="font-weight: 600; font-size: 14px;">{{ $item['kp_name'] ?? $item['kp_code'] ?? '未知知识点' }}</div>
                        <div style="font-weight: 600; color: {{ $barColor }}; font-size: 14px;">
                            {{ number_format($pct, 1) }}%
                            <span style="margin-left: 8px; color: #666; font-size: 12px;">{{ $changeText }}</span>
                        </div>
                    </div>
                    <div class="progress-wrap" style="height: 12px;">
                        <div class="progress-bar" style="width: {{ $pct }}%; background: {{ $barColor }};"></div>
                    </div>
                </div>
            @endforeach
        @else
            <div class="muted">暂无有效掌握度数据（已过滤通用知识点和零值）</div>
        @endif
    </div>

    <div class="card">
        <div class="section-title">📊 知识点层级掌握度分析</div>
        @php
            $parentMasteryLevels = $parent_mastery_levels ?? [];
            $hasParentMastery = !empty($parentMasteryLevels);
        @endphp

        @if($hasParentMastery)
            @foreach($parentMasteryLevels as $parentData)
                @php
                    $pct = $parentData['mastery_percentage'] ?? 0;
                    $barColor = $pct >= 80 ? '#10b981' : ($pct >= 60 ? '#f59e0b' : '#ef4444');
                    $parentName = $parentData['kp_name'] ?? $parentData['kp_code'];
                    $children = $parentData['children'] ?? [];
                    $level = $parentData['level'] ?? 1;
                    $delta = $parentData['mastery_change'] ?? null;
                    // 只有当有变化值时才显示变化信息
                    $changeText = '';
                    if ($delta !== null && $delta !== '' && abs($delta) > 0.001) {
                        $changeText = ($delta > 0 ? '↑ ' : '↓ ') . number_format(abs($delta) * 100, 1) . '%';
                    }
                @endphp
                <div style="margin-bottom: 14px; padding: 10px; border: 1px solid #e0f2fe; border-radius: 6px; background: #f8fafc;">
                    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom: 8px;">
                        <div style="font-weight: 700; font-size: 15px; color: #0f172a;">
                            【第{{ $level }}级】{{ $parentName }}
                            <span style="margin-left: 8px; font-size: 11px; color: #64748b; font-weight: 400;">
                                ({{ $parentData['kp_code'] }})
                            </span>
                        </div>
                        <div style="font-weight: 700; color: {{ $barColor }}; font-size: 15px;">
                            {{ number_format($pct, 1) }}%
                            @if(!empty($changeText))
                                <span style="margin-left: 8px; color: #666; font-size: 12px;">{{ $changeText }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="progress-wrap" style="height: 12px; margin-bottom: 8px;">
                        <div class="progress-bar" style="width: {{ $pct }}%; background: {{ $barColor }};"></div>
                    </div>
                    @if(!empty($children))
                        <div style="font-size: 12px; color: #475569;">
                            <strong>包含子知识点（{{ count($children) }}个）：</strong>
                            @foreach($children as $index => $child)
                                @if($index < 8)
                                    <span style="display:inline-block; margin: 2px 4px; padding: 2px 6px; background: #e0f2fe; border-radius: 3px; font-size: 11px;">
                                        {{ $child['kp_name'] }}
                                    </span>
                                @endif
                            @endforeach
                            @if(count($children) > 8)
                                <span style="color: #64748b; font-style: italic;">...等{{ count($children) }}个知识点</span>
                            @endif
                        </div>
                    @else
                        <div style="font-size: 12px; color: #64748b;">
                            <em>无直接子知识点或子知识点掌握度为0</em>
                        </div>
                    @endif
                </div>
            @endforeach

            <div style="margin-top: 12px; padding: 8px; background: #fefce8; border-left: 4px solid #eab308; border-radius: 4px;">
                <div style="font-size: 12px; color: #854d0e; line-height: 1.6;">
                    <strong>学习建议：</strong>
                    建议重点关注掌握度较低的知识点，通过专项练习提升整体学习水平。优先练习掌握度低于60%的知识点。
                </div>
            </div>
        @else
            <div class="muted">暂无父节点掌握度数据</div>
            <div style="margin-top: 8px; font-size: 12px; color: #64748b;">
                当前分析主要基于具体知识点掌握度。完整的层级掌握度分析需要在系统中建立完整的知识点层级关系。
            </div>
        @endif
    </div>

    <div class="card">
        <div class="section-title">题目列表</div>
        @php
            $insightMap = [];
            foreach (($question_insights ?? []) as $insight) {
                $no = $insight['question_number'] ?? $insight['question_id'] ?? null;
                if ($no !== null) {
                    $insightMap[$no] = $insight;
                }
            }
        @endphp
        @foreach($questions as $q)
            @php
                // 【修复】从题目数据中获取学生答案、正确答案和判分结果
                $studentAnswer = $q['student_answer'] ?? $q['student_answer'] ?? null;
                $correctAnswer = $q['answer'] ?? $q['correct_answer'] ?? null;
                $isCorrect = $q['is_correct'] ?? null;  // 1=正确，0=错误，null=未判

                // 如果未判分但有学生答案和正确答案，自动比较判断
                if ($isCorrect === null && !empty($studentAnswer) && !empty($correctAnswer)) {
                    $isCorrect = (trim($studentAnswer) === trim($correctAnswer)) ? 1 : 0;
                }

                // 判分状态显示逻辑
                $showStatus = false;
                $statusText = '';
                $statusColor = '';
                if (!empty($studentAnswer)) {
                    // 学生有答题，显示判分结果
                    $showStatus = true;
                    if ($isCorrect === 1) {
                        $statusText = '正确';
                        $statusColor = '#10b981';
                    } elseif ($isCorrect === 0) {
                        $statusText = '错误';
                        $statusColor = '#ef4444';
                    }
                }
                // 没答题的不显示状态

                $insight = $insightMap[$q['question_number']] ?? ($insightMap[$q['display_number'] ?? null] ?? []);
                // 【修复】得分显示：答错显示实际得分，答对显示满分
                $fullScore = $insight['full_score'] ?? ($q['score'] ?? null);
                if ($isCorrect === 1) {
                    // 答对了，显示满分
                    $score = $fullScore;
                } elseif ($isCorrect === 0) {
                    // 答错了，显示实际得分（可能为0分或其他分数）
                    $score = $q['score_obtained'] ?? 0;
                } else {
                    // 未判分或未答题，不显示得分
                    $score = null;
                }
                $analysisRaw = $insight['analysis']
                    ?? $insight['thinking_process']
                    ?? $insight['feedback']
                    ?? $insight['suggestions']
                    ?? $insight['reason']
                    ?? ($insight['correct_solution'] ?? null);
                // 若有下一步建议，追加
                if (empty($analysisRaw) && !empty($insight['next_steps'])) {
                    $analysisRaw = '后续建议：' . (is_array($insight['next_steps']) ? implode('；', $insight['next_steps']) : $insight['next_steps']);
                }
                $analysis = is_array($analysisRaw) ? json_encode($analysisRaw, JSON_UNESCAPED_UNICODE) : $analysisRaw;
                if ($analysis === null || $analysis === '') {
                    $analysis = '暂无解题思路，待补充';
                }
                $stepsRaw = $insight['steps'] ?? $insight['solution_steps'] ?? $insight['analysis_steps'] ?? null;
                $steps = [];
                if (is_array($stepsRaw)) {
                    $steps = $stepsRaw;
                } elseif (is_string($stepsRaw) && trim($stepsRaw) !== '') {
                    $steps = preg_split('/[\r\n]+/', trim($stepsRaw));
                }
                $typeMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
                $typeLabel = $typeMap[$q['question_type'] ?? ''] ?? ($q['question_type'] ?? '题型未标注');
                $questionText = is_string($q['question_text']) ? $q['question_text'] : json_encode($q['question_text'], JSON_UNESCAPED_UNICODE);
                $solution = $q['solution'] ?? null;
            @endphp
            <div style="border:1px solid #e5e7eb; border-radius:8px; padding:8px 12px; margin-bottom:8px; background:#fff; page-break-inside: avoid;">
                <div style="display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:4px;">
                    <div style="display:flex; align-items:center; gap:8px; font-weight:600;">
                        <span class="tag">题号 {{ $q['display_number'] ?? $q['question_number'] }}</span>
                        @php
                            $kpName = $q['knowledge_point_name'] ?? $q['knowledge_point'] ?? null;
                            if (!empty($kpName) && $kpName !== '-' && $kpName !== '未标注') {
                                echo '<span class="tag" style="background: #eef2ff; color:#4338ca;">' . e($kpName) . '</span>';
                            }
                        @endphp
                        @if($showStatus)
                            <span class="tag" style="background: {{ $statusColor }}; color:#fff;">{{ $statusText }}</span>
                        @endif
                    </div>
                    @if($score !== null && $fullScore !== null)
                        <div class="muted">得分 {{ $score }} / {{ $fullScore }}</div>
                    @endif
                </div>

                {{-- 【新增】学生答案显示（如果有） --}}
                @if(!empty($studentAnswer))
                    <div style="margin-bottom:6px; padding:6px; background:#fef2f2; border-left:3px solid #ef4444; border-radius:4px;">
                        <div style="font-weight:600; font-size:12px; color:#111827; margin-bottom:3px;">学生答案</div>
                        <div class="math-content" style="font-size:12px; line-height:1.5; color:#374151;">
                            {!! nl2br(e($studentAnswer)) !!}
                        </div>
                    </div>
                @endif

                <div class="math-content" style="margin-bottom:6px; font-size:12px;">{!! $questionText !!}</div>
                <div class="muted" style="margin-bottom:6px; font-size:12px;">题型：{{ $typeLabel }}</div>

                {{-- 【修复】正确答案显示 --}}
                @if(!empty($correctAnswer))
                    <div style="margin-bottom:6px; padding:6px; background:#f0fdf4; border-left:3px solid #10b981; border-radius:4px;">
                        <div style="font-weight:600; font-size:12px; color:#111827; margin-bottom:3px;">正确答案</div>
                        <div class="math-content" style="font-size:12px; line-height:1.5; color:#374151;">
                            {!! nl2br(e($correctAnswer)) !!}
                        </div>
                    </div>
                @endif

                {{-- 【修改】解题思路显示（优先显示solution，其次显示analysis） --}}
                @if(!empty($solution))
                    <div style="margin-top:6px; padding:6px; background:#eff6ff; border-left:3px solid #3b82f6; border-radius:4px;">
                        <div style="font-weight:600; font-size:12px; color:#111827; margin-bottom:4px;">解题思路</div>
                        <div class="math-content" style="font-size:12px; line-height:1.5; color:#374151;">
                            {!! is_array($solution) ? json_encode($solution, JSON_UNESCAPED_UNICODE) : nl2br(e($solution)) !!}
                        </div>
                    </div>
                @elseif(!empty($analysis) && $analysis !== '暂无解题思路记录')
                    <div style="margin-top:6px; padding:6px; background:#eff6ff; border-left:3px solid #3b82f6; border-radius:4px;">
                        <div style="font-weight:600; font-size:12px; color:#111827; margin-bottom:4px;">解题思路</div>
                        <div style="font-size:12px; line-height:1.5; color:#374151;">{!! nl2br(e($analysis)) !!}</div>
                    </div>
                @endif

                {{-- 解题步骤（如果有） --}}
                @if(!empty($steps))
                    <div style="margin-top:6px; font-size:12px;">
                        <div style="font-weight:600; margin-bottom:3px;">解题步骤</div>
                        <ol style="margin:0; padding-left:18px;">
                            @foreach($steps as $s)
                                <li style="margin-bottom:2px;">{!! nl2br(e(is_array($s) ? json_encode($s, JSON_UNESCAPED_UNICODE) : $s)) !!}</li>
                            @endforeach
                        </ol>
                    </div>
                @endif
            </div>
        @endforeach
    </div>
    </div> {{-- 闭合page div --}}

    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            try {
                renderMathInElement(document.body, {
                    delimiters: [
                        {left: "$$", right: "$$", display: true},
                        {left: "$", right: "$", display: false},
                        {left: "\\(", right: "\\)", display: false},
                        {left: "\\[", right: "\\]", display: true}
                    ],
                    throwOnError: false,
                    strict: false,
                    trust: true
                });
            } catch (e) {}
        });
    </script>
</body>
</html>
