<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ $paper->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: 2cm;
        }
        body {
            font-family: "SimSun", "Songti SC", serif; /* 宋体，适合试卷 */
            line-height: 1.6;
            color: #000;
            background: #fff;
        }
        .header {
            text-align: center;
            margin-bottom: 2rem;
            border-bottom: 2px solid #000;
            padding-bottom: 1rem;
        }
        .school-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .paper-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .seal-line {
            position: absolute;
            left: -1.5cm;
            top: 0;
            bottom: 0;
            width: 1cm;
            border-right: 1px dashed #999;
            writing-mode: vertical-rl;
            text-align: center;
            font-size: 12px;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .section-title {
            font-size: 16px;
            font-weight: bold;
            margin-top: 20px;
            margin-bottom: 10px;
        }
        .question {
            margin-bottom: 15px;
            page-break-inside: avoid;
        }
        .question-content {
            font-size: 14px;
            margin-bottom: 8px;
            display: flex;
            align-items: baseline;
        }
        .omr-marker {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 1px solid #000;
            border-radius: 50%;
            margin-right: 10px;
            position: relative;
            top: 4px;
        }
        .options {
            display: block;
            margin-left: 35px; /* 对齐题目内容 */
            margin-top: 10px;
        }
        .options-grid-4 {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px 12px;
            margin-left: 35px;
            margin-top: 10px;
        }
        .options-grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px 20px;
            margin-left: 35px;
            margin-top: 10px;
        }
        .option {
            width: 100%;
            font-size: 14px;
            line-height: 1.5;
            word-wrap: break-word;
            display: flex;
            align-items: flex-start;
        }
        .option-inline {
            display: inline-flex;
            align-items: baseline;
            margin-right: 20px;
        }
        .option-compact {
            font-size: 13px;
            line-height: 1.4;
        }
        .fill-line {
            display: inline-block;
            border-bottom: 1px solid #000;
            width: 100px;
            text-align: center;
        }
        .answer-space {
            height: 150px; /* 解答题留白 */
            border: 1px dashed #eee;
            margin-top: 10px;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                -webkit-print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>
    <div class="seal-line">
        装&nbsp;&nbsp;&nbsp;&nbsp;订&nbsp;&nbsp;&nbsp;&nbsp;线&nbsp;&nbsp;&nbsp;&nbsp;内&nbsp;&nbsp;&nbsp;&nbsp;不&nbsp;&nbsp;&nbsp;&nbsp;要&nbsp;&nbsp;&nbsp;&nbsp;答&nbsp;&nbsp;&nbsp;&nbsp;题
    </div>

    <div class="header">
        <div class="school-name">数学智能测试卷</div>
        <div class="paper-title">{{ $paper->paper_name ?? '未命名试卷' }}</div>
        <div class="info-row">
            <span>老师：{{ $teacher['name'] ?? '________' }}</span>
            <span>年级：{{ $student['grade'] ?? '________' }}</span>
            <span>姓名：{{ $student['name'] ?? '________' }}</span>
            <span>得分：________</span>
        </div>
    </div>

    <!-- 一、选择题 -->
    <div class="section-title">一、选择题
        @if(count($questions['choice']) > 0)
            @php
                $choiceTotal = array_sum(array_map(fn($q) => $q->score ?? 5, $questions['choice']));
            @endphp
            （本大题共 {{ count($questions['choice']) }} 小题，共 {{ $choiceTotal }} 分）
        @else
            （本大题共 0 小题，共 0 分）
        @endif
    </div>
    @if(count($questions['choice']) > 0)
        @foreach($questions['choice'] as $index => $q)
            @php
                $questionNumber = $index + 1; // 选择题从1开始编号

                // 清理和预处理题干内容：移除题号前缀
                $cleanContent = preg_replace('/^\d+[\.\、]\s*/', '', $q->content);
                $cleanContent = trim($cleanContent);

                // 优先使用控制器传递的选项
                $options = $q->options ?? [];

                // 如果没有从控制器获取到选项，尝试从内容提取
                if (empty($options)) {
                    // 支持多种选项格式：A. / A、/ A：/ A．
                    $pattern = '/([A-D])[\.、：．:]\s*(.+?)(?=\s*[A-D][\.、：．:]|$)/su';
                    if (preg_match_all($pattern, $cleanContent, $matches, PREG_SET_ORDER)) {
                        foreach ($matches as $match) {
                            $optionText = trim($match[2]);
                            if (!empty($optionText)) {
                                $options[] = $optionText;
                            }
                        }
                    }
                }

                // 提取纯题干（选项前的部分）
                $stemLine = $cleanContent;
                if (!empty($options)) {
                    // 找到第一个选项标记的位置
                    if (preg_match('/^(.+?)(?=[A-D][\.、：．:])/su', $cleanContent, $stemMatch)) {
                        $stemLine = trim($stemMatch[1]);
                    }
                }

                // 移除题干末尾可能的括号
                $stemLine = preg_replace('/（）\s*$/', '', $stemLine);
                $stemLine = trim($stemLine);
            @endphp
            <div class="question">
                <div class="question-content">
                    <span class="omr-marker"></span>
                    <span class="font-bold" style="margin-right: 8px;">{{ $questionNumber }}.</span>
                    <span style="margin-left: 4px;">({{ $q->score ?? 5 }}分) @math($stemLine)</span>
                </div>

                @if(!empty($options))
                    @php
                        // 确保有4个选项（A、B、C、D）
                        $standardOptions = ['A', 'B', 'C', 'D'];
                        $displayOptions = [];
                        foreach ($standardOptions as $idx => $letter) {
                            if (isset($options[$idx]) && !empty($options[$idx])) {
                                $displayOptions[$letter] = $options[$idx];
                            } else {
                                // 补充缺失的选项
                                $displayOptions[$letter] = '（待补充选项' . $letter . '）';
                            }
                        }

                        // 计算选项长度，决定布局
                        $maxOptionLength = 0;
                        $totalOptionLength = 0;
                        foreach ($displayOptions as $letter => $option) {
                            $text = strip_tags($option);
                            $length = mb_strlen($text);
                            $maxOptionLength = max($maxOptionLength, $length);
                            $totalOptionLength += $length;
                        }

                        // 三种布局选择：
                        // 1. 一行4列：极短选项（单个选项≤10字符）
                        // 2. 一行2列：短选项（单个选项≤25字符）
                        // 3. 垂直布局：长选项（单个选项>25字符）
                        if ($maxOptionLength <= 10) {
                            $layoutType = 'inline-4';
                            $maxOptionLength = 12; // 给一点余量
                        } elseif ($maxOptionLength <= 25) {
                            $layoutType = 'grid-2';
                            $maxOptionLength = 30; // 给一点余量
                        } else {
                            $layoutType = 'vertical';
                        }
                    @endphp

                    @if($layoutType === 'inline-4')
                        {{-- 极短选项：一行4列布局 --}}
                        <div style="margin-left: 35px; margin-top: 10px;">
                            <span style="font-size: 14px;">
                                @foreach($displayOptions as $letter => $option)
                                    <span class="option-inline option-compact">
                                        <span style="font-weight: bold; margin-right: 4px;">{{ $letter }}.</span>
                                        <span>@math($option)</span>
                                    </span>
                                @endforeach
                            </span>
                        </div>
                    @elseif($layoutType === 'grid-2')
                        {{-- 短选项：一行2列布局 --}}
                        <div class="options-grid-2">
                            @foreach($displayOptions as $letter => $option)
                                <div class="option">
                                    <span style="font-weight: bold; margin-right: 8px;">{{ $letter }}.</span>
                                    <span>@math($option)</span>
                                </div>
                            @endforeach
                        </div>
                    @else
                        {{-- 长选项：垂直布局 --}}
                        <div class="options">
                            @foreach($displayOptions as $letter => $option)
                                <div class="option">
                                    <span style="font-weight: bold; margin-right: 8px;">{{ $letter }}.</span>
                                    <span>@math($option)</span>
                                </div>
                            @endforeach
                        </div>
                    @endif
                @else
                    {{-- 如果没有任何选项，显示占位符 --}}
                    <div class="options-grid-2">
                        <div class="option" style="font-style: italic; color: #999;">
                            <span style="font-weight: bold; margin-right: 8px;">A.</span>
                            <span>（待补充选项A）</span>
                        </div>
                        <div class="option" style="font-style: italic; color: #999;">
                            <span style="font-weight: bold; margin-right: 8px;">B.</span>
                            <span>（待补充选项B）</span>
                        </div>
                        <div class="option" style="font-style: italic; color: #999;">
                            <span style="font-weight: bold; margin-right: 8px;">C.</span>
                            <span>（待补充选项C）</span>
                        </div>
                        <div class="option" style="font-style: italic; color: #999;">
                            <span style="font-weight: bold; margin-right: 8px;">D.</span>
                            <span>（待补充选项D）</span>
                        </div>
                    </div>
                @endif
            </div>
        @endforeach
    @else
        <div class="question">
            <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
                该题型正在生成中或暂无题目，请稍后刷新页面查看
            </div>
        </div>
    @endif

    <!-- 二、填空题 -->
    <div class="section-title">二、填空题
        @if(count($questions['fill']) > 0)
            @php
                $fillTotal = array_sum(array_map(fn($q) => $q->score ?? 5, $questions['fill']));
            @endphp
            （本大题共 {{ count($questions['fill']) }} 小题，共 {{ $fillTotal }} 分）
        @else
            （本大题共 0 小题，共 0 分）
        @endif
    </div>
    @if(count($questions['fill']) > 0)
        @foreach($questions['fill'] as $index => $q)
            @php
                $questionNumber = count($questions['choice']) + $index + 1; // 填空题接着选择题编号
            @endphp
            <div class="question">
                <div class="question-content">
                    <span class="omr-marker"></span>
                    <span class="font-bold" style="margin-right: 8px;">{{ $questionNumber }}.</span>
                    <span style="margin-left: 4px;">({{ $q->score ?? 5 }}分) @math(str_replace('__________', '<span class="fill-line"></span>', $q->content))</span>
                </div>
            </div>
        @endforeach
    @else
        <div class="question">
            <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
                该题型正在生成中或暂无题目，请稍后刷新页面查看
            </div>
        </div>
    @endif

    <!-- 三、解答题 -->
    <div class="section-title">三、解答题
        @if(count($questions['answer']) > 0)
            （本大题共 {{ count($questions['answer']) }} 小题，共 {{ array_sum(array_column($questions['answer'], 'score')) }} 分。解答应写出文字说明、证明过程或演算步骤）
        @else
            （本大题共 0 小题，共 0 分）
        @endif
    </div>
    @if(count($questions['answer']) > 0)
        @foreach($questions['answer'] as $index => $q)
            @php
                $questionNumber = count($questions['choice']) + count($questions['fill']) + $index + 1; // 解答题接着前面所有题型编号
            @endphp
            <div class="question">
                <div class="question-content">
                    <span class="omr-marker"></span>
                    <span class="font-bold" style="margin-right: 8px;">{{ $questionNumber }}.</span>
                    <span style="margin-left: 4px;">({{ $q->score ?? 10 }}分) @math($q->content)</span>
                </div>
                <div class="answer-space"></div>
            </div>
        @endforeach
    @else
        <div class="question">
            <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
                该题型正在生成中或暂无题目，请稍后刷新页面查看
            </div>
        </div>
    @endif

    <!-- 试卷总分统计 -->
    @php
        $totalChoiceScore = array_sum(array_map(fn($q) => $q->score ?? 5, $questions['choice']));
        $totalFillScore = array_sum(array_map(fn($q) => $q->score ?? 5, $questions['fill']));
        $totalAnswerScore = array_sum(array_map(fn($q) => $q->score ?? 10, $questions['answer']));
        $grandTotal = $totalChoiceScore + $totalFillScore + $totalAnswerScore;
    @endphp
    <div style="margin-top: 30px; padding: 15px; border-top: 2px solid #000; text-align: right; font-size: 14px;">
        <strong>试卷总分：{{ $grandTotal }} 分</strong>
        （选择题 {{ $totalChoiceScore }} 分 + 填空题 {{ $totalFillScore }} 分 + 解答题 {{ $totalAnswerScore }} 分）
    </div>

    {{-- 参考答案（仅在开启时显示） --}}
    @if($includeAnswer)
        <div style="page-break-before: always; margin-top: 40px;">
            <div style="text-align: center; font-size: 22px; font-weight: bold; margin-bottom: 30px; border-bottom: 2px solid #000; padding-bottom: 10px;">
                参考答案
            </div>
            <div style="font-size: 14px; margin-bottom: 20px; text-align: center; color: #666;">
                {{ $paper->paper_name ?? '未命名试卷' }}
            </div>

            {{-- 选择题答案 --}}
            @if(count($questions['choice']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">一、选择题</div>
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; font-size: 14px;">
                        @foreach($questions['choice'] as $index => $q)
                            <div style="padding: 8px; background: #f5f5f5; border-radius: 4px;">
                                <span style="font-weight: bold;">{{ $index + 1 }}.</span>
                                @if(!empty($q->answer))
                                    <span style="margin-left: 8px; font-weight: bold; color: #d32f2f;">
                                        @php
                                            // 提取答案中的选项字母
                                            $answerText = $q->answer;
                                            $letter = '';
                                            if (preg_match('/([A-D])/i', $answerText, $match)) {
                                                $letter = strtoupper($match[1]);
                                            } elseif (preg_match('/答案[：:]\s*([A-D])/i', $answerText, $match)) {
                                                $letter = strtoupper($match[1]);
                                            }
                                            echo $letter ?: '（待补充）';
                                        @endphp
                                    </span>
                                @else
                                    <span style="margin-left: 8px; color: #999; font-style: italic;">（待补充）</span>
                                @endif
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif

            {{-- 填空题答案 --}}
            @if(count($questions['fill']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">二、填空题</div>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; font-size: 14px;">
                        @foreach($questions['fill'] as $index => $q)
                            <div style="padding: 8px; background: #f5f5f5; border-radius: 4px;">
                                <span style="font-weight: bold;">{{ count($questions['choice']) + $index + 1 }}.</span>
                                <span style="margin-left: 8px;">
                                    @if(!empty($q->answer))
                                        @math($q->answer)
                                    @else
                                        <span style="color: #999; font-style: italic;">（待补充）</span>
                                    @endif
                                </span>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif

            {{-- 解答题答案 --}}
            @if(count($questions['answer']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 15px;">三、解答题</div>
                    <div style="space-y: 15px;">
                        @foreach($questions['answer'] as $index => $q)
                            @php
                                $questionNumber = count($questions['choice']) + count($questions['fill']) + $index + 1;
                            @endphp
                            <div style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 4px; border-left: 4px solid #4163ff;">
                                <div style="font-weight: bold; font-size: 15px; margin-bottom: 10px;">
                                    {{ $questionNumber }}. ({{ $q->score ?? 10 }}分)
                                </div>
                                @if(!empty($q->answer))
                                    <div style="font-size: 14px; line-height: 1.8;">
                                        @math($q->answer)
                                    </div>
                                @else
                                    <div style="font-size: 14px; color: #999; font-style: italic;">
                                        （答案待补充或请参考标准答案）
                                    </div>
                                @endif
                                @if(!empty($q->solution))
                                    <div style="margin-top: 10px; font-size: 13px; color: #666; padding-top: 10px; border-top: 1px dashed #ddd;">
                                        <strong>解析：</strong> @math($q->solution)
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif
        </div>
    @endif

    <div class="no-print" style="position: fixed; bottom: 20px; right: 20px;">
        <button onclick="window.print()" style="padding: 10px 20px; background: #4163ff; color: white; border: none; border-radius: 5px; cursor: pointer;">打印试卷</button>
    </div>

    <!-- KaTeX JavaScript 库 -->
    <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() {
            console.log('试卷公式渲染器启动');

            // 配置 KaTeX 自动渲染
            function renderMath() {
                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,
                        macros: {
                            "\\f": "#1f(#2)"
                        }
                    });
                    console.log('数学公式渲染完成');
                } catch (e) {
                    console.warn('公式渲染警告:', e);
                }
            }

            // 页面加载后渲染
            renderMath();

            // 如果页面是动态加载的，等待一段时间后再次渲染
            setTimeout(renderMath, 500);
            setTimeout(renderMath, 1000);

            // 添加到全局，必要时手动调用
            window.renderExamMath = renderMath;
        });
    </script>
</body>
</html>
