{% extends "layout.html" %}

{% block page_title %}录入新题目{% endblock %}

{% block content %}

<!-- LaTeX 实时预览气泡 -->
<div id="latex-preview-bubble" class="fixed right-8 top-24 w-[420px] max-h-[75vh] bg-white rounded-2xl shadow-2xl border border-gray-200 z-50 overflow-hidden flex flex-col" style="box-shadow: 0 20px 60px rgba(0,0,0,0.15);">
    <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white px-4 py-3 flex items-center justify-between">
        <span class="text-sm font-bold">题目预览</span>
        <button type="button" onclick="hidePreviewBubble()" class="text-white hover:text-gray-200 text-xl leading-none w-6 h-6 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
    </div>
    <div id="latex-preview-content" class="flex-1 p-6 overflow-y-auto bg-gray-50 text-base leading-relaxed" style="min-height: 200px;">
        <p class="text-sm text-gray-400 text-center">题目预览</p>
    </div>
</div>

<form id="add-form" class="grid grid-cols-1 gap-4">
    <div class="apple-card p-6 space-y-4">
        <div class="border-b border-gray-100 pb-3 mb-3">
            <div class="flex items-center gap-3 flex-wrap">
                <h2 class="text-xl font-bold">录入新题目</h2>
            </div>
                <!-- 层级信息标签 -->
                {% if chapter_label or section_label or subsection_label %}
                <div class="flex items-center gap-2 flex-wrap">
                    {% if chapter_label %}
                    <div class="flex items-center gap-1.5">
                        <span class="bg-gradient-to-r from-slate-600 to-slate-700 text-white px-2 py-0.5 rounded text-xs font-bold">章</span>
                        <span class="text-xs text-gray-700">{{ chapter_label }}</span>
                    </div>
                    {% endif %}
                    {% if section_label %}
                    <span class="text-gray-300 text-xs">›</span>
                    <div class="flex items-center gap-1.5">
                        <span class="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-2 py-0.5 rounded text-xs font-bold">节</span>
                        <span class="text-xs text-gray-600">{{ section_label }}</span>
                    </div>
                    {% endif %}
                    {% if subsection_label %}
                    <span class="text-gray-300 text-xs">›</span>
                    <div class="flex items-center gap-1.5">
                        <span class="bg-gray-200 text-gray-700 px-2 py-0.5 rounded text-xs font-bold">小节</span>
                        <span class="text-xs text-gray-600">{{ subsection_label }}</span>
                    </div>
                    {% endif %}
                </div>
                {% endif %}
            </div>
            <p class="text-gray-400 text-xs mt-1">填写题目信息，保存后自动生成题号并创建新题目</p>
        </div>

        <!-- JSON输入框（永久显示） -->
        <div id="json-input-section" class="mb-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
            <label class="block text-sm font-bold text-gray-700 mb-2">JSON输入（实时双向同步）</label>
            <textarea id="json-input" 
                      class="w-full h-48 p-3 border border-gray-300 rounded-lg font-mono text-xs focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none"
                      placeholder='{"number": "", "stem": "", "options": {"A": "", "B": "", "C": "", "D": ""}, "answer": "", "question_type": "", "solution": "", "difficulty": ""}'
                      oninput="handleJsonInputChange()"></textarea>
            <p class="text-xs text-gray-500 mt-2">修改JSON自动同步到表单，修改表单字段自动同步到JSON</p>
        </div>

        <!-- 题型和难度选择 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
                <select name="question_type" id="question-type-select" class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
                    <option value="choice" selected>选择题</option>
                    <option value="fill">填空题</option>
                    <option value="answer">解答题</option>
                </select>
            </div>
            <!-- 难度选择 -->
            <div id="difficulty-section" class="space-y-1">
                <div class="flex items-center gap-2">
                    <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
                    <button type="button" id="evaluate-difficulty-btn" onclick="evaluateDifficulty()" class="btn-apple bg-gradient-to-r from-purple-500 to-indigo-600 text-white hover:from-purple-600 hover:to-indigo-700 text-xs py-1 px-2 shadow-md whitespace-nowrap">
                        <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                        </svg>
                        难度评价
                    </button>
                </div>
                <select name="difficulty" id="difficulty-select" class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
                    <option value="">请选择难度</option>
                    <option value="0.2">筑基</option>
                    <option value="0.4">提分</option>
                    <option value="0.7">培优</option>
                </select>
            </div>
        </div>

        <!-- 题干编辑 -->
        <div class="space-y-2">
            <div class="flex items-center justify-between">
                <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
                <button 
                    type="button" 
                    id="upload-image-btn" 
                    class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit"
                    onclick="triggerStemImageUpload()"
                >
                    上传图片
                </button>
            </div>
            <textarea 
                id="stem-textarea" 
                name="stem" 
                required
                class="w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm" 
                placeholder="请输入题干内容或拖拽图片..."
                ondrop="handleStemDrop(event)"
                ondragover="handleStemDragOver(event)"
                ondragleave="handleStemDragLeave(event)"
            ></textarea>
            <div id="upload-status" class="mt-1 text-xs hidden"></div>
        </div>

        <!-- 选项编辑 -->
        <div id="options-section" class="space-y-2">
            <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
            
            <!-- 选项输入区域 - 2列布局 -->
            <div class="grid grid-cols-2 gap-3" id="options-container">
                <!-- 选项A -->
                <div class="option-item" data-option="A">
                    <label class="text-xs font-medium text-gray-600 mb-1 block">选项 A</label>
                    <div class="flex gap-1.5">
                        <textarea 
                            name="option_A" 
                            id="option-A-input"
                            class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
                            placeholder="输入选项A的内容或拖拽图片..."
                            oninput="updateOptionsPreview()"
                            ondrop="handleOptionDrop(event, 'A')"
                            ondragover="handleOptionDragOver(event)"
                            ondragleave="handleOptionDragLeave(event)"
                        ></textarea>
                        <button 
                            type="button" 
                            class="option-upload-btn btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start"
                            onclick="uploadOptionImage('A')"
                        >
                            上传图片
                        </button>
                    </div>
                </div>
                
                <!-- 选项B -->
                <div class="option-item" data-option="B">
                    <label class="text-xs font-medium text-gray-600 mb-1 block">选项 B</label>
                    <div class="flex gap-1.5">
                        <textarea 
                            name="option_B" 
                            id="option-B-input"
                            class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
                            placeholder="输入选项B的内容或拖拽图片..."
                            oninput="updateOptionsPreview()"
                            ondrop="handleOptionDrop(event, 'B')"
                            ondragover="handleOptionDragOver(event)"
                            ondragleave="handleOptionDragLeave(event)"
                        ></textarea>
                        <button 
                            type="button" 
                            class="option-upload-btn btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start"
                            onclick="uploadOptionImage('B')"
                        >
                            上传图片
                        </button>
                    </div>
                </div>
                
                <!-- 选项C -->
                <div class="option-item" data-option="C">
                    <label class="text-xs font-medium text-gray-600 mb-1 block">选项 C</label>
                    <div class="flex gap-1.5">
                        <textarea 
                            name="option_C" 
                            id="option-C-input"
                            class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
                            placeholder="输入选项C的内容或拖拽图片..."
                            oninput="updateOptionsPreview()"
                            ondrop="handleOptionDrop(event, 'C')"
                            ondragover="handleOptionDragOver(event)"
                            ondragleave="handleOptionDragLeave(event)"
                        ></textarea>
                        <button 
                            type="button" 
                            class="option-upload-btn btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start"
                            onclick="uploadOptionImage('C')"
                        >
                            上传图片
                        </button>
                    </div>
                </div>
                
                <!-- 选项D -->
                <div class="option-item" data-option="D">
                    <label class="text-xs font-medium text-gray-600 mb-1 block">选项 D</label>
                    <div class="flex gap-1.5">
                        <textarea 
                            name="option_D" 
                            id="option-D-input"
                            class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
                            placeholder="输入选项D的内容或拖拽图片..."
                            oninput="updateOptionsPreview()"
                            ondrop="handleOptionDrop(event, 'D')"
                            ondragover="handleOptionDragOver(event)"
                            ondragleave="handleOptionDragLeave(event)"
                        ></textarea>
                        <button 
                            type="button" 
                            class="option-upload-btn btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start"
                            onclick="uploadOptionImage('D')"
                        >
                            上传图片
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 选项预览（可编辑） -->
            <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
                <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式，可直接编辑)</label>
                <textarea 
                    id="options-preview" 
                    class="w-full text-xs text-gray-700 font-mono bg-white p-2 rounded border border-gray-100 min-h-[80px] focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all resize-y"
                    placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'
                    oninput="syncOptionsFromPreview()"
                >{}</textarea>
                <input type="hidden" name="options" id="options-json-input">
            </div>
        </div>

        <!-- 答案 -->
        <div class="space-y-1">
            <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
            <input type="text" name="answer" id="answer-input" class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm" placeholder="例如: A">
        </div>

        <!-- 解析 -->
        <div class="space-y-2">
            <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
            <textarea 
                id="solution-textarea"
                name="solution" 
                class="w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm" 
                placeholder="请输入解析内容或拖拽图片..."
                ondrop="handleSolutionDrop(event)"
                ondragover="handleSolutionDragOver(event)"
                ondragleave="handleSolutionDragLeave(event)"
            ></textarea>
        </div>

        <!-- 隐藏字段：用于提交层级信息 -->
        {% if chapter_label %}
        <input type="hidden" name="chapter" id="chapter-input" value="{{ chapter_label }}">
        {% endif %}
        {% if section_label %}
        <input type="hidden" name="section" id="section-input" value="{{ section_label }}">
        {% endif %}
        {% if subsection_label %}
        <input type="hidden" name="subsection" id="subsection-input" value="{{ subsection_label }}">
        {% endif %}

        <!-- 保存按钮 -->
        <div class="pt-4 flex justify-end space-x-2">
            <button type="button" onclick="window.history.back()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 text-sm py-2 px-4">取消</button>
            <button type="submit" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 shadow-lg shadow-blue-200 text-sm py-2 px-4">保存并创建 <span class="text-xs opacity-75 ml-1">(Alt+R)</span></button>
        </div>
    </div>
</form>

<script>
// 工具函数：保留两位小数
function round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

// LaTeX 实时预览功能
let previewUpdateTimer = null;
let currentPreviewElement = null;

function showPreviewBubble(element, label) {
    const bubble = document.getElementById('latex-preview-bubble');
    const content = document.getElementById('latex-preview-content');
    
    if (!bubble || !content) return;
    
    // 更新标题
    const title = bubble.querySelector('.bg-gradient-to-r span');
    if (title) {
        title.textContent = label || '实时预览';
    }
    
    currentPreviewElement = element;
    bubble.classList.remove('hidden');
    updatePreviewContent(element.value || '');
}

function hidePreviewBubble() {
    const bubble = document.getElementById('latex-preview-bubble');
    if (bubble) {
        bubble.classList.add('hidden');
    }
    currentPreviewElement = null;
}

function updatePreviewContent(text) {
    const content = document.getElementById('latex-preview-content');
    if (!content) return;
    
    if (!text || !text.trim()) {
        content.innerHTML = '<p class="text-sm text-gray-400 text-center">聚焦输入框查看预览</p>';
        return;
    }
    
    // 将文本内容转换为 HTML，保留换行和基本格式
    let html = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\n/g, '<br>');
    
    // 处理图片标签
    html = html.replace(/&lt;image\s+src="([^"]+)"\s*\/?&gt;/gi, '<img src="$1" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">');
    
    content.innerHTML = html;
    
    // 等待 KaTeX 加载完成后渲染数学公式
    if (window.renderMathInElement) {
        try {
            window.renderMathInElement(content, {
                delimiters: [
                    {left: "$$", right: "$$", display: true},
                    {left: "$", right: "$", display: false},
                    {left: "\\(", right: "\\)", display: false},
                    {left: "\\[", right: "\\]", display: true}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('LaTeX 渲染失败:', e);
        }
    } else {
        // 如果 KaTeX 还没加载，等待一下再试
        setTimeout(() => {
            if (window.renderMathInElement) {
                try {
                    window.renderMathInElement(content, {
                        delimiters: [
                            {left: "$$", right: "$$", display: true},
                            {left: "$", right: "$", display: false},
                            {left: "\\(", right: "\\)", display: false},
                            {left: "\\[", right: "\\]", display: true}
                        ],
                        throwOnError: false
                    });
                } catch (e) {
                    console.warn('LaTeX 渲染失败:', e);
                }
            }
        }, 100);
    }
}

function setupPreviewForElement(elementId, label) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    element.addEventListener('focus', function() {
        showPreviewBubble(this, label);
        updatePreviewContent(this.value || '');
    });
    
    element.addEventListener('input', function() {
        if (currentPreviewElement === this) {
            // 防抖处理，避免频繁更新
            clearTimeout(previewUpdateTimer);
            previewUpdateTimer = setTimeout(() => {
                updatePreviewContent(this.value || '');
            }, 300);
        }
    });
    
    element.addEventListener('blur', function() {
        // 不自动隐藏，保持预览气泡显示，直到用户点击其他预览或关闭按钮
        // 移除自动隐藏逻辑，让预览气泡一直显示
    });
}

// 更新选项预览气泡内容（显示4个选项的渲染）
function updateOptionsPreviewBubble() {
    const previewTextarea = document.getElementById('options-preview');
    const bubble = document.getElementById('latex-preview-bubble');
    const content = document.getElementById('latex-preview-content');
    
    if (!previewTextarea || !bubble || !content) return;
    
    const jsonStr = previewTextarea.value.trim();
    
    if (!jsonStr || jsonStr === '{}') {
        content.innerHTML = '<p class="text-sm text-gray-400 text-center">暂无选项内容</p>';
        return;
    }
    
    try {
        const optionsObj = JSON.parse(jsonStr);
        const optionKeys = ['A', 'B', 'C', 'D'];
        
        let html = '<div class="space-y-4">';
        
        optionKeys.forEach(key => {
            const optionText = optionsObj[key] || '';
            html += `<div class="border-b border-gray-200 pb-3 last:border-0 last:pb-0">`;
            html += `<div class="text-xs font-bold text-gray-500 mb-2">选项 ${key}</div>`;
            
            if (!optionText || !optionText.trim()) {
                html += `<p class="text-xs text-gray-400">暂无内容</p>`;
            } else {
                // 将文本内容转换为 HTML，保留换行和基本格式
                let optionHtml = optionText
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/\n/g, '<br>');
                
                // 处理图片标签
                optionHtml = optionHtml.replace(/&lt;image\s+src="([^"]+)"\s*\/?&gt;/gi, '<img src="$1" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">');
                
                html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
            }
            
            html += `</div>`;
        });
        
        html += '</div>';
        content.innerHTML = html;
        
        // 等待 KaTeX 加载完成后渲染数学公式
        if (window.renderMathInElement) {
            try {
                window.renderMathInElement(content, {
                    delimiters: [
                        {left: "$$", right: "$$", display: true},
                        {left: "$", right: "$", display: false},
                        {left: "\\(", right: "\\)", display: false},
                        {left: "\\[", right: "\\]", display: true}
                    ],
                    throwOnError: false
                });
            } catch (e) {
                console.warn('LaTeX 渲染失败:', e);
            }
        } else {
            // 如果 KaTeX 还没加载，等待一下再试
            setTimeout(() => {
                if (window.renderMathInElement) {
                    try {
                        window.renderMathInElement(content, {
                            delimiters: [
                                {left: "$$", right: "$$", display: true},
                                {left: "$", right: "$", display: false},
                                {left: "\\(", right: "\\)", display: false},
                                {left: "\\[", right: "\\]", display: true}
                            ],
                            throwOnError: false
                        });
                    } catch (e) {
                        console.warn('LaTeX 渲染失败:', e);
                    }
                }
            }, 100);
        }
    } catch (error) {
        content.innerHTML = '<p class="text-sm text-red-400 text-center">JSON 格式错误，请检查输入</p>';
    }
}

// 设置选项预览输入框的预览功能
function setupOptionsPreviewTextarea() {
    const optionsPreviewTextarea = document.getElementById('options-preview');
    if (!optionsPreviewTextarea) return;
    
    optionsPreviewTextarea.addEventListener('focus', function() {
        showPreviewBubble(this, '选项预览');
        updateOptionsPreviewBubble();
    });
    
    optionsPreviewTextarea.addEventListener('input', function() {
        if (currentPreviewElement === this) {
            // 防抖处理，避免频繁更新
            clearTimeout(previewUpdateTimer);
            previewUpdateTimer = setTimeout(() => {
                updateOptionsPreviewBubble();
            }, 300);
        }
    });
    
    optionsPreviewTextarea.addEventListener('blur', function() {
        // 不自动隐藏，保持预览气泡显示
    });
}

    // 根据题型显示/隐藏选项相关内容
    function toggleOptionsVisibility(questionType) {
        const optionsSection = document.getElementById('options-section');
        const difficultySection = document.getElementById('difficulty-section');
        
        if (optionsSection) {
            if (questionType === 'choice') {
                optionsSection.style.display = 'block';
            } else {
                optionsSection.style.display = 'none';
            }
        }
        
        // 难度选择框：所有题型都显示
        if (difficultySection) {
            difficultySection.style.display = 'block';
        }
    }

// 难度评价函数
async function evaluateDifficulty() {
    const btn = document.getElementById('evaluate-difficulty-btn');
    const difficultySelect = document.getElementById('difficulty-select');
    
    if (!btn || !difficultySelect) return;
    
    // 收集题目信息
    const stemTextarea = document.getElementById('stem-textarea');
    const answerInput = document.getElementById('answer-input');
    const solutionTextarea = document.getElementById('solution-textarea');
    const optionsPreview = document.getElementById('options-preview');
    const questionTypeSelect = document.getElementById('question-type-select');
    
    const stem = stemTextarea ? stemTextarea.value.trim() : '';
    
    if (!stem) {
        if (window.customAlert) {
            window.customAlert('请先填写题干内容');
        } else {
            alert('请先填写题干内容');
        }
        return;
    }
    
    // 构建请求数据
    const requestData = {
        stem: stem,
        answer: answerInput ? answerInput.value.trim() : '',
        solution: solutionTextarea ? solutionTextarea.value.trim() : '',
        question_type: questionTypeSelect ? questionTypeSelect.value : ''
    };
    
    // 处理选项
    if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
        try {
            requestData.options = JSON.parse(optionsPreview.value.trim());
        } catch (e) {
            console.warn('选项JSON解析失败:', e);
        }
    }
    
    // 显示加载状态
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<svg class="w-3 h-3 inline-block mr-1 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>评价中...';
    
    try {
        const response = await fetch('/api/score', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });
        
        if (!response.ok) {
            throw new Error(`请求失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 调试：打印完整返回结果
        console.log('难度评价接口返回:', result);
        
        // 处理返回的 difficulty_level（优先使用 data.difficulty_level，兼容旧格式）
        let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
        
        // 映射难度等级到枚举值
        // 可能的返回值：字符串 "筑基"、"提分"、"培优" 或数字 0.2, 0.4, 0.7
        let difficultyValue = '';
        
        if (difficultyLevel !== undefined && difficultyLevel !== null) {
            const levelStr = String(difficultyLevel).trim();
            
            // 字符串匹配
            if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
                difficultyValue = '0.2';
            } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
                difficultyValue = '0.4';
            } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
                difficultyValue = '0.7';
            } else {
                // 尝试转换为数字
                const levelNum = parseFloat(levelStr);
                if (!isNaN(levelNum)) {
                    if (Math.abs(levelNum - 0.2) < 0.1) {
                        difficultyValue = '0.2';
                    } else if (Math.abs(levelNum - 0.4) < 0.1) {
                        difficultyValue = '0.4';
                    } else if (Math.abs(levelNum - 0.7) < 0.1) {
                        difficultyValue = '0.7';
                    }
                }
            }
        }
        
        if (difficultyValue) {
            difficultySelect.value = difficultyValue;
            // 触发change事件以更新预览
            difficultySelect.dispatchEvent(new Event('change', { bubbles: true }));
            // 不显示弹窗，直接完成
        } else {
            // 如果无法识别，打印完整返回结果以便调试
            console.error('无法识别难度等级，完整返回结果:', result);
            if (window.customAlert) {
                window.customAlert('无法识别返回的难度等级。返回数据：' + JSON.stringify(result));
            } else {
                alert('无法识别返回的难度等级。返回数据：' + JSON.stringify(result));
            }
        }
        
    } catch (error) {
        console.error('难度评价失败:', error);
        if (window.customAlert) {
            window.customAlert('难度评价失败: ' + error.message);
        } else {
            alert('难度评价失败: ' + error.message);
        }
    } finally {
        // 恢复按钮
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

// 页面加载时初始化选项预览和题型默认值
document.addEventListener('DOMContentLoaded', function() {
    updateOptionsPreview();
    
    // 读取保存的题型选择，如果没有则默认为"choice"（选择题）
    const savedQuestionType = localStorage.getItem('default_question_type') || 'choice';
    const questionTypeSelect = document.getElementById('question-type-select');
    if (questionTypeSelect) {
        questionTypeSelect.value = savedQuestionType;
        
        // 监听题型变化，保存用户选择并控制选项显示
        questionTypeSelect.addEventListener('change', function() {
            const selectedType = this.value;
            if (selectedType) {
                localStorage.setItem('default_question_type', selectedType);
            }
            toggleOptionsVisibility(selectedType);
        });
        
        // 初始化时根据题型显示/隐藏选项
        toggleOptionsVisibility(questionTypeSelect.value);
    }
    
    // Alt+R 快捷键：保存并创建
    document.addEventListener('keydown', function(e) {
        if (e.altKey && (e.key === 'r' || e.key === 'R')) {
            e.preventDefault();
            const submitBtn = document.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.click();
            }
        }
    });
    
    // 设置 LaTeX 实时预览
    setupPreviewForElement('stem-textarea', '题干预览');
    setupPreviewForElement('solution-textarea', '解析预览');
    setupPreviewForElement('option-A-input', '选项 A 预览');
    setupPreviewForElement('option-B-input', '选项 B 预览');
    setupPreviewForElement('option-C-input', '选项 C 预览');
    setupPreviewForElement('option-D-input', '选项 D 预览');
    setupPreviewForElement('option-E-input', '选项 E 预览');
    setupPreviewForElement('option-F-input', '选项 F 预览');
    setupPreviewForElement('answer-input', '正确答案预览');
    
    // 设置选项预览输入框的预览功能（在右侧气泡显示4个选项）
    setupOptionsPreviewTextarea();
    
    // 为所有输入框添加粘贴图片功能
    setupPasteImageForAllInputs();
    
    // 初始化JSON输入框
    initJsonInput();
    
    // 设置表单字段变化时同步到JSON
    setupFormToJsonSync();
    
    // 默认显示完整预览
    updateFullPreview();
    
    // 保持预览气泡一直显示，不自动关闭
    // 移除鼠标离开时的自动关闭逻辑
});

// JSON输入框相关功能
function toggleJsonInput() {
    const jsonSection = document.getElementById('json-input-section');
    const toggleText = document.getElementById('json-toggle-text');
    
    if (jsonSection.classList.contains('hidden')) {
        jsonSection.classList.remove('hidden');
        toggleText.textContent = '隐藏JSON输入';
        syncToJson(); // 显示时同步当前表单数据到JSON
    } else {
        jsonSection.classList.add('hidden');
        toggleText.textContent = '显示JSON输入';
    }
}

function initJsonInput() {
    const jsonInput = document.getElementById('json-input');
    const defaultJson = {
        number: "",
        stem: "",
        options: {
            A: "",
            B: "",
            C: "",
            D: ""
        },
        answer: "",
        question_type: "",
        solution: "",
        difficulty: ""
    };
    jsonInput.value = JSON.stringify(defaultJson, null, 2);
}

function syncFromJson() {
    const jsonInput = document.getElementById('json-input');
    const jsonText = jsonInput.value.trim();
    
    if (!jsonText) {
        return;
    }
    
    try {
        isSyncingFromJson = true; // 标记正在从JSON同步，防止循环
        
        const data = JSON.parse(jsonText);
        
        // 填充题干
        const stemTextarea = document.getElementById('stem-textarea');
        if (stemTextarea && data.stem !== undefined) {
            stemTextarea.value = data.stem || '';
            // 触发input事件以更新预览
            stemTextarea.dispatchEvent(new Event('input', { bubbles: true }));
        }
        
        // 填充题型
        const questionTypeSelect = document.getElementById('question-type-select');
        if (questionTypeSelect && data.question_type !== undefined) {
            const mappedType = mapQuestionTypeForJson(data.question_type);
            questionTypeSelect.value = mappedType || 'choice';
            // 触发题型变化事件
            questionTypeSelect.dispatchEvent(new Event('change'));
        }
        
        // 填充难度
        const difficultySelect = document.getElementById('difficulty-select');
        if (difficultySelect && data.difficulty !== undefined) {
            difficultySelect.value = data.difficulty || '';
        }
        
        // 填充选项
        if (data.options && typeof data.options === 'object') {
            ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
                const optionInput = document.getElementById(`option-${key}-input`);
                if (optionInput && data.options[key] !== undefined) {
                    optionInput.value = data.options[key] || '';
                    optionInput.dispatchEvent(new Event('input', { bubbles: true }));
                }
            });
            // 更新选项预览
            updateOptionsPreview();
        }
        
        // 填充答案
        const answerInput = document.getElementById('answer-input');
        if (answerInput && data.answer !== undefined) {
            answerInput.value = data.answer || '';
            answerInput.dispatchEvent(new Event('input', { bubbles: true }));
        }
        
        // 填充解析
        const solutionTextarea = document.getElementById('solution-textarea');
        if (solutionTextarea && data.solution !== undefined) {
            solutionTextarea.value = data.solution || '';
            solutionTextarea.dispatchEvent(new Event('input', { bubbles: true }));
        }
        
        // 更新预览区域
        updateFullPreview();
        
    } catch (error) {
        // JSON格式错误时不显示错误，只标记输入框
        console.warn('JSON格式错误：', error);
    } finally {
        isSyncingFromJson = false;
    }
}

function syncToJson() {
    const jsonInput = document.getElementById('json-input');
    
    // 收集表单数据
    const stemTextarea = document.getElementById('stem-textarea');
    const questionTypeSelect = document.getElementById('question-type-select');
    const difficultySelect = document.getElementById('difficulty-select');
    const answerInput = document.getElementById('answer-input');
    const solutionTextarea = document.getElementById('solution-textarea');
    
    const optionsObj = {};
    ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
        const optionInput = document.getElementById(`option-${key}-input`);
        if (optionInput && optionInput.value.trim()) {
            optionsObj[key] = optionInput.value.trim();
        }
    });
    
    // 映射题型（英文转中文）
    const questionTypeMap = {
        'choice': '选择题',
        'fill': '填空题',
        'answer': '解答题'
    };
    
    const jsonData = {
        number: "",
        stem: stemTextarea ? stemTextarea.value : "",
        options: Object.keys(optionsObj).length > 0 ? optionsObj : { A: "", B: "", C: "", D: "" },
        answer: answerInput ? answerInput.value : "",
        question_type: questionTypeSelect && questionTypeSelect.value ? (questionTypeMap[questionTypeSelect.value] || '') : '',
        solution: solutionTextarea ? solutionTextarea.value : "",
        difficulty: difficultySelect ? difficultySelect.value : ""
    };
    
    jsonInput.value = JSON.stringify(jsonData, null, 2);
}

let jsonSyncTimer = null;
let isSyncingFromJson = false; // 防止循环同步

function handleJsonInputChange() {
    const jsonInput = document.getElementById('json-input');
    const jsonText = jsonInput.value.trim();
    
    // 实时验证JSON格式
    if (jsonText) {
        try {
            JSON.parse(jsonText);
            jsonInput.classList.remove('border-red-500');
            jsonInput.classList.add('border-gray-300');
            
            // 防抖处理，避免频繁同步
            clearTimeout(jsonSyncTimer);
            jsonSyncTimer = setTimeout(() => {
                if (!isSyncingFromJson) {
                    syncFromJson();
                    updateFullPreview();
                }
            }, 500); // 500ms延迟
        } catch (e) {
            jsonInput.classList.remove('border-gray-300');
            jsonInput.classList.add('border-red-500');
        }
    }
}

function mapQuestionTypeForJson(type) {
    const typeMap = {
        '选择题': 'choice',
        '填空题': 'fill',
        '解答题': 'answer',
        'choice': 'choice',
        'fill': 'fill',
        'answer': 'answer'
    };
    return typeMap[type] || 'choice';
}

let formSyncTimer = null;

function setupFormToJsonSync() {
    // 监听所有表单字段的变化，自动同步到JSON（防抖处理）
    const fieldsToWatch = [
        { id: 'stem-textarea', event: 'input' },
        { id: 'answer-input', event: 'input' },
        { id: 'solution-textarea', event: 'input' },
        { id: 'question-type-select', event: 'change' },
        { id: 'difficulty-select', event: 'change' }
    ];
    
    fieldsToWatch.forEach(field => {
        const element = document.getElementById(field.id);
        if (element) {
            element.addEventListener(field.event, function() {
                if (!isSyncingFromJson) {
                    clearTimeout(formSyncTimer);
                    formSyncTimer = setTimeout(() => {
                        syncToJson();
                        updateFullPreview();
                    }, 300);
                }
            });
        }
    });
    
    // 监听选项输入框变化
    ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
        const optionInput = document.getElementById(`option-${key}-input`);
        if (optionInput) {
            optionInput.addEventListener('input', function() {
                if (!isSyncingFromJson) {
                    clearTimeout(formSyncTimer);
                    formSyncTimer = setTimeout(() => {
                        syncToJson();
                        updateFullPreview();
                    }, 300);
                }
            });
        }
    });
    
    // 监听选项预览变化
    const optionsPreview = document.getElementById('options-preview');
    if (optionsPreview) {
        optionsPreview.addEventListener('input', function() {
            if (!isSyncingFromJson) {
                clearTimeout(formSyncTimer);
                formSyncTimer = setTimeout(() => {
                    syncToJson();
                    updateFullPreview();
                }, 300);
            }
        });
    }
}

// 更新完整预览（题干、选项、解析）
function updateFullPreview() {
    const previewContent = document.getElementById('latex-preview-content');
    if (!previewContent) return;
    
    const bubble = document.getElementById('latex-preview-bubble');
    if (!bubble) return;
    
    // 收集所有数据
    const stemTextarea = document.getElementById('stem-textarea');
    const answerInput = document.getElementById('answer-input');
    const solutionTextarea = document.getElementById('solution-textarea');
    const optionsPreview = document.getElementById('options-preview');
    const questionTypeSelect = document.getElementById('question-type-select');
    
    let html = '<div class="space-y-6">';
    
    // 题干预览
    html += '<div class="border-b border-gray-200 pb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
    const stem = stemTextarea ? stemTextarea.value : '';
    if (stem) {
        let stemHtml = stem
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        stemHtml = stemHtml.replace(/&lt;image\s+src="([^"]+)"\s*\/?&gt;/gi, '<img src="$1" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">');
        html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
    } else {
        html += '<p class="text-xs text-gray-400">暂无内容</p>';
    }
    html += '</div>';
    
    // 选项预览（仅选择题）
    if (questionTypeSelect && questionTypeSelect.value === 'choice') {
        html += '<div class="border-b border-gray-200 pb-4">';
        html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
        
        if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
            try {
                const optionsObj = JSON.parse(optionsPreview.value.trim());
                ['A', 'B', 'C', 'D'].forEach(key => {
                    const optionText = optionsObj[key] || '';
                    html += `<div class="mb-3">`;
                    html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
                    if (optionText) {
                        let optionHtml = optionText
                            .replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(/\n/g, '<br>');
                        optionHtml = optionHtml.replace(/&lt;image\s+src="([^"]+)"\s*\/?&gt;/gi, '<img src="$1" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">');
                        html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
                    } else {
                        html += '<p class="text-xs text-gray-400">暂无内容</p>';
                    }
                    html += `</div>`;
                });
            } catch (e) {
                html += '<p class="text-xs text-red-400">选项JSON格式错误</p>';
            }
        } else {
            html += '<p class="text-xs text-gray-400">暂无选项</p>';
        }
        html += '</div>';
    }
    
    // 答案预览
    html += '<div class="border-b border-gray-200 pb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
    const answer = answerInput ? answerInput.value : '';
    if (answer) {
        html += `<div class="text-sm font-bold text-blue-600">${answer}</div>`;
    } else {
        html += '<p class="text-xs text-gray-400">暂无答案</p>';
    }
    html += '</div>';
    
    // 解析预览
    html += '<div>';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
    const solution = solutionTextarea ? solutionTextarea.value : '';
    if (solution) {
        let solutionHtml = solution
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        solutionHtml = solutionHtml.replace(/&lt;image\s+src="([^"]+)"\s*\/?&gt;/gi, '<img src="$1" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">');
        html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
    } else {
        html += '<p class="text-xs text-gray-400">暂无解析</p>';
    }
    html += '</div>';
    
    html += '</div>';
    
    previewContent.innerHTML = html;
    
    // 渲染LaTeX
    if (window.renderMathInElement) {
        try {
            window.renderMathInElement(previewContent, {
                delimiters: [
                    {left: "$$", right: "$$", display: true},
                    {left: "$", right: "$", display: false},
                    {left: "\\(", right: "\\)", display: false},
                    {left: "\\[", right: "\\]", display: true}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('LaTeX 渲染失败:', e);
        }
    }
    
    // 显示预览气泡
    bubble.classList.remove('hidden');
}

document.getElementById('add-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    // 构建提交数据（question_code 由后端自动生成）
    const data = {};
    const fields = ['stem', 'answer', 'solution', 'question_type', 
                    'chapter', 'section', 'subsection', 'difficulty'];
    
    fields.forEach(field => {
        const value = formData.get(field);
        if (value && value.trim()) {
            // 处理difficulty字段：转换为浮点数，保留两位小数
            if (field === 'difficulty') {
                const difficultyValue = parseFloat(value);
                if (!isNaN(difficultyValue)) {
                    data[field] = round(difficultyValue, 2);
                }
            } else {
                data[field] = value.trim();
            }
        }
    });
    
    // 如果难度为空，不提交difficulty字段
    if (!data.difficulty || data.difficulty === '') {
        delete data.difficulty;
    }
    
    // 添加 kp_code（从URL参数获取）
    const urlParams = new URLSearchParams(window.location.search);
    const kpCode = urlParams.get('kp_code');
    if (kpCode) {
        data.kp_code = kpCode;
    }
    
    // 添加 create_by（从localStorage获取用户姓名）
    const userName = localStorage.getItem('user_name');
    if (userName && userName.trim()) {
        data.create_by = userName.trim();
    }
    
    // 处理选项：优先使用预览区域的JSON，如果预览区域为空或无效，则从输入框收集
    const previewTextarea = document.getElementById('options-preview');
    const jsonInput = document.getElementById('options-json-input');
    
    let optionsJson = '';
    if (previewTextarea && previewTextarea.value.trim() && previewTextarea.value.trim() !== '{}') {
        try {
            // 验证预览区域的JSON是否有效
            const parsed = JSON.parse(previewTextarea.value.trim());
            optionsJson = JSON.stringify(parsed);
        } catch (e) {
            // JSON无效，从输入框收集
            const optionsObj = {};
            const optionKeys = ['A', 'B', 'C', 'D', 'E', 'F'];
            optionKeys.forEach(key => {
                const input = document.getElementById(`option-${key}-input`);
                if (input && input.value && input.value.trim()) {
                    optionsObj[key] = input.value.trim();
                }
            });
            if (Object.keys(optionsObj).length > 0) {
                optionsJson = JSON.stringify(optionsObj);
            }
        }
    } else {
        // 预览区域为空，从输入框收集
        const optionsObj = {};
        const optionKeys = ['A', 'B', 'C', 'D', 'E', 'F'];
        optionKeys.forEach(key => {
            const input = document.getElementById(`option-${key}-input`);
            if (input && input.value && input.value.trim()) {
                optionsObj[key] = input.value.trim();
            }
        });
        if (Object.keys(optionsObj).length > 0) {
            optionsJson = JSON.stringify(optionsObj);
        }
    }
    
    if (optionsJson) {
        data.options = optionsJson;
    }
    
    // 验证必填项（仅题干）
    if (!data.stem || !data.stem.trim()) {
        const message = '请填写题干';
        if (window.customAlert) {
            window.customAlert(message);
        } else {
            alert(message);
        }
        return;
    }
    
    const res = await fetch('/create_question', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    
    const result = await res.json();
    if(result.success) {
        // 直接跳转到题目详情页，不显示弹窗
        window.location.href = '/detail/' + result.question_code;
    } else {
        if (window.customAlert) {
            window.customAlert('创建失败: ' + result.error);
        } else {
            alert('创建失败: ' + result.error);
        }
    }
});

// 更新选项预览（从输入框同步到预览区域）
function updateOptionsPreview() {
    const optionsObj = {};
    const optionKeys = ['A', 'B', 'C', 'D', 'E', 'F'];
    
    optionKeys.forEach(key => {
        const input = document.getElementById(`option-${key}-input`);
        if (input && input.value && input.value.trim()) {
            optionsObj[key] = input.value.trim();
        }
    });
    
    const preview = document.getElementById('options-preview');
    const jsonInput = document.getElementById('options-json-input');
    
    if (Object.keys(optionsObj).length > 0) {
        const jsonStr = JSON.stringify(optionsObj, null, 2);
        preview.value = jsonStr;
        jsonInput.value = JSON.stringify(optionsObj);
    } else {
        preview.value = '{}';
        jsonInput.value = '';
    }
}

// 从预览区域同步到选项输入框（当用户直接编辑预览时）
function syncOptionsFromPreview() {
    const preview = document.getElementById('options-preview');
    const jsonInput = document.getElementById('options-json-input');
    
    try {
        const jsonStr = preview.value.trim();
        if (!jsonStr || jsonStr === '{}') {
            // 清空所有选项输入框
            ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
                const input = document.getElementById(`option-${key}-input`);
                if (input) {
                    input.value = '';
                }
            });
            jsonInput.value = '';
            // 如果预览气泡正在显示，更新它
            if (currentPreviewElement === preview) {
                updateOptionsPreviewBubble();
            }
            return;
        }
        
        const optionsObj = JSON.parse(jsonStr);
        jsonInput.value = JSON.stringify(optionsObj);
        
        // 同步到各个选项输入框
        ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
            const input = document.getElementById(`option-${key}-input`);
            if (input) {
                input.value = optionsObj[key] || '';
            }
        });
        
        // 如果预览气泡正在显示，更新它
        if (currentPreviewElement === preview) {
            updateOptionsPreviewBubble();
        }
    } catch (error) {
        // JSON 解析失败，不更新输入框，保持预览区域的内容
        console.warn('选项预览 JSON 格式错误:', error);
        // 如果预览气泡正在显示，显示错误信息
        if (currentPreviewElement === preview) {
            const content = document.getElementById('latex-preview-content');
            if (content) {
                content.innerHTML = '<p class="text-sm text-red-400 text-center">JSON 格式错误，请检查输入</p>';
            }
        }
    }
}

// 选项输入框拖拽处理
function handleOptionDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.add('border-blue-500', 'bg-blue-50');
}

function handleOptionDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.remove('border-blue-500', 'bg-blue-50');
}

async function handleOptionDrop(e, optionKey) {
    e.preventDefault();
    e.stopPropagation();
    const textarea = e.currentTarget;
    textarea.classList.remove('border-blue-500', 'bg-blue-50');
    
    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
        const file = files[0];
        if (file.type.startsWith('image/')) {
            // 直接上传图片
            await uploadOptionImageFile(file, optionKey);
        } else {
            if (window.customAlert) {
                window.customAlert('请拖拽图片文件！');
            } else {
                alert('请拖拽图片文件！');
            }
        }
    }
}

// 上传选项图片（通过文件选择）
async function uploadOptionImage(optionKey) {
    // 创建隐藏的文件输入框
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.style.display = 'none';
    
    fileInput.onchange = async (e) => {
        const file = e.target.files[0];
        if (!file) return;
        
        if (!file.type.startsWith('image/')) {
            if (window.customAlert) {
                window.customAlert('请选择图片文件！');
            } else {
                alert('请选择图片文件！');
            }
            return;
        }
        
        await uploadOptionImageFile(file, optionKey);
    };
    
    document.body.appendChild(fileInput);
    fileInput.click();
}

// 通用的选项图片上传函数
async function uploadOptionImageFile(file, optionKey) {
    const optionInput = document.getElementById(`option-${optionKey}-input`);
    const uploadBtn = document.querySelector(`[onclick="uploadOptionImage('${optionKey}')"]`);
    
    // 显示上传中状态
    let originalText = '';
    if (uploadBtn) {
        originalText = uploadBtn.textContent;
        uploadBtn.disabled = true;
        uploadBtn.textContent = '上传中...';
    }
    
    // 在输入框中显示上传中提示
    const originalPlaceholder = optionInput.placeholder;
    optionInput.placeholder = '正在上传图片...';
    optionInput.style.opacity = '0.6';
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 检查返回结果，提取URL
        let imageUrl = null;
        if (typeof result === 'string') {
            imageUrl = result;
        } else if (result.url) {
            imageUrl = result.url;
        } else if (result.data && result.data.url) {
            imageUrl = result.data.url;
        } else if (result.data && typeof result.data === 'string') {
            imageUrl = result.data;
        } else {
            const resultStr = JSON.stringify(result);
            const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
            if (urlMatch) {
                imageUrl = urlMatch[0];
            }
        }
        
        if (!imageUrl) {
            throw new Error('接口返回格式异常，未找到图片URL。返回结果：' + JSON.stringify(result));
        }
        
        // 构建 image 标签
        const imageTag = `<image src="${imageUrl}"/>`;
        
        // 获取当前光标位置
        const cursorPos = optionInput.selectionStart;
        const textBefore = optionInput.value.substring(0, cursorPos);
        const textAfter = optionInput.value.substring(cursorPos);
        
        // 插入 image 标签
        optionInput.value = textBefore + imageTag + textAfter;
        
        // 设置光标位置到插入内容之后
        const newCursorPos = cursorPos + imageTag.length;
        optionInput.setSelectionRange(newCursorPos, newCursorPos);
        optionInput.focus();
        
        // 更新选项预览JSON
        updateOptionsPreview();
        
        // 如果选项预览输入框正在显示预览气泡，更新预览气泡
        const optionsPreviewTextarea = document.getElementById('options-preview');
        if (currentPreviewElement === optionsPreviewTextarea) {
            updateOptionsPreviewBubble();
        }
            
            // 图片已插入，无需弹窗提示
        
    } catch (error) {
        console.error('上传失败:', error);
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        if (uploadBtn) {
            uploadBtn.disabled = false;
            uploadBtn.textContent = originalText;
        }
        optionInput.placeholder = originalPlaceholder;
        optionInput.style.opacity = '1';
    }
}

// 触发题干图片上传
function triggerStemImageUpload() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.style.display = 'none';
    fileInput.onchange = async (e) => {
        const file = e.target.files[0];
        if (file) {
            await uploadStemImageFile(file);
        }
    };
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
}

// 题干拖拽处理函数
function handleStemDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.add('border-blue-500', 'bg-blue-50');
}

function handleStemDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.remove('border-blue-500', 'bg-blue-50');
}

async function handleStemDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    const textarea = e.currentTarget;
    textarea.classList.remove('border-blue-500', 'bg-blue-50');
    
    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
        const file = files[0];
        if (file.type.startsWith('image/')) {
            // 直接上传图片到题干
            await uploadStemImageFile(file);
        } else {
            if (window.customAlert) {
                window.customAlert('请拖拽图片文件！');
            } else {
                alert('请拖拽图片文件！');
            }
        }
    }
}

// 解析拖拽处理函数
function handleSolutionDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.add('border-blue-500', 'bg-blue-50');
}

function handleSolutionDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    e.currentTarget.classList.remove('border-blue-500', 'bg-blue-50');
}

async function handleSolutionDrop(e) {
    e.preventDefault();
    e.stopPropagation();
    const textarea = e.currentTarget;
    textarea.classList.remove('border-blue-500', 'bg-blue-50');
    
    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
        const file = files[0];
        if (file.type.startsWith('image/')) {
            // 直接上传图片到解析
            await uploadSolutionImageFile(file);
        } else {
            if (window.customAlert) {
                window.customAlert('请拖拽图片文件！');
            } else {
                alert('请拖拽图片文件！');
            }
        }
    }
}

// 题干图片上传函数
async function uploadStemImageFile(file) {
    const stemTextarea = document.getElementById('stem-textarea');
    const statusDiv = document.getElementById('upload-status');
    
    // 显示上传中状态
    const originalPlaceholder = stemTextarea.placeholder;
    stemTextarea.placeholder = '正在上传图片...';
    stemTextarea.style.opacity = '0.6';
    
    if (statusDiv) {
        statusDiv.classList.remove('hidden');
        statusDiv.textContent = '正在上传图片...';
        statusDiv.className = 'mt-2 text-sm text-blue-600';
    }
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 检查返回结果，提取URL
        let imageUrl = null;
        if (typeof result === 'string') {
            imageUrl = result;
        } else if (result.url) {
            imageUrl = result.url;
        } else if (result.data && result.data.url) {
            imageUrl = result.data.url;
        } else if (result.data && typeof result.data === 'string') {
            imageUrl = result.data;
        } else {
            const resultStr = JSON.stringify(result);
            const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
            if (urlMatch) {
                imageUrl = urlMatch[0];
            }
        }
        
        if (!imageUrl) {
            throw new Error('接口返回格式异常，未找到图片URL。返回结果：' + JSON.stringify(result));
        }
        
        // 构建 image 标签
        const imageTag = `<image src="${imageUrl}"/>`;
        
        // 在预览区域显示图片
        const previewDiv = document.getElementById('stem-image-preview');
        if (previewDiv) {
            previewDiv.innerHTML = `<img src="${imageUrl}" alt="预览图片" class="w-full h-full object-contain rounded-lg" style="max-height: 100%; max-width: 100%;">`;
        }
        
        // 获取当前光标位置
        const cursorPos = stemTextarea.selectionStart;
        const textBefore = stemTextarea.value.substring(0, cursorPos);
        const textAfter = stemTextarea.value.substring(cursorPos);
        
        // 插入 image 标签
        stemTextarea.value = textBefore + imageTag + textAfter;
        
        // 设置光标位置到插入内容之后
        const newCursorPos = cursorPos + imageTag.length;
        stemTextarea.setSelectionRange(newCursorPos, newCursorPos);
        stemTextarea.focus();
        
        // 如果预览气泡正在显示，更新预览内容
        if (currentPreviewElement === stemTextarea) {
            updatePreviewContent(stemTextarea.value);
        }
        
        // 显示成功消息
        if (statusDiv) {
            statusDiv.textContent = '图片上传成功！已插入到题干中。';
            statusDiv.className = 'mt-2 text-sm text-green-600';
            setTimeout(() => {
                statusDiv.classList.add('hidden');
            }, 1500);
        }
        
    } catch (error) {
        console.error('上传失败:', error);
        if (statusDiv) {
            statusDiv.textContent = '上传失败: ' + error.message;
            statusDiv.className = 'mt-2 text-sm text-red-600';
        }
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        stemTextarea.placeholder = originalPlaceholder;
        stemTextarea.style.opacity = '1';
    }
}

// 解析图片上传函数
async function uploadSolutionImageFile(file) {
    const solutionTextarea = document.getElementById('solution-textarea');
    await uploadImageToInput(file, solutionTextarea);
}

// 通用图片上传函数：上传图片并插入到指定输入框
async function uploadImageToInput(file, inputElement) {
    if (!inputElement || !file) {
        return;
    }
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
        if (window.customAlert) {
            window.customAlert('请选择图片文件！');
        } else {
            alert('请选择图片文件！');
        }
        return;
    }
    
    // 显示上传中状态
    const originalPlaceholder = inputElement.placeholder || '';
    const originalOpacity = inputElement.style.opacity || '1';
    inputElement.placeholder = '正在上传图片...';
    inputElement.style.opacity = '0.6';
    inputElement.disabled = true;
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 检查返回结果，提取URL
        let imageUrl = null;
        if (typeof result === 'string') {
            imageUrl = result;
        } else if (result.url) {
            imageUrl = result.url;
        } else if (result.data && result.data.url) {
            imageUrl = result.data.url;
        } else if (result.data && typeof result.data === 'string') {
            imageUrl = result.data;
        } else {
            const resultStr = JSON.stringify(result);
            const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
            if (urlMatch) {
                imageUrl = urlMatch[0];
            }
        }
        
        if (!imageUrl) {
            throw new Error('接口返回格式异常，未找到图片URL。返回结果：' + JSON.stringify(result));
        }
        
        // 构建 image 标签
        const imageTag = `<image src="${imageUrl}"/>`;
        
        // 获取当前光标位置
        const cursorPos = inputElement.selectionStart || inputElement.value.length;
        const textBefore = inputElement.value.substring(0, cursorPos);
        const textAfter = inputElement.value.substring(cursorPos);
        
        // 插入 image 标签
        inputElement.value = textBefore + imageTag + textAfter;
        
        // 设置光标位置到插入内容之后
        const newCursorPos = cursorPos + imageTag.length;
        if (inputElement.setSelectionRange) {
            inputElement.setSelectionRange(newCursorPos, newCursorPos);
        }
        inputElement.focus();
        
        // 触发input事件，更新预览
        inputElement.dispatchEvent(new Event('input', { bubbles: true }));
        
        // 如果预览气泡正在显示，更新预览内容
        if (currentPreviewElement === inputElement) {
            updatePreviewContent(inputElement.value);
        }
        
        // 如果是选项输入框，更新选项预览
        if (inputElement.id && inputElement.id.startsWith('option-')) {
            updateOptionsPreview();
        }
        
    } catch (error) {
        console.error('上传失败:', error);
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        inputElement.placeholder = originalPlaceholder;
        inputElement.style.opacity = originalOpacity;
        inputElement.disabled = false;
    }
}

// 为所有输入框设置粘贴图片功能
function setupPasteImageForAllInputs() {
    // 获取所有文本输入框和文本域
    const allInputs = document.querySelectorAll('textarea, input[type="text"]');
    
    allInputs.forEach(input => {
        // 添加粘贴事件监听
        input.addEventListener('paste', async function(e) {
            const clipboardData = e.clipboardData || window.clipboardData;
            if (!clipboardData) {
                return;
            }
            
            // 检查是否有图片数据
            const items = clipboardData.items;
            if (!items) {
                return;
            }
            
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                
                // 如果是图片类型
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault(); // 阻止默认粘贴行为
                    
                    const file = item.getAsFile();
                    if (file) {
                        // 上传图片并插入到当前输入框
                        await uploadImageToInput(file, input);
                    }
                    break;
                }
            }
        });
    });
}

// 拖拽处理函数（用于上传区域）
function handleDragOver(e) {
    e.preventDefault();
    e.stopPropagation();
    const uploadArea = document.getElementById('upload-area');
    uploadArea.classList.add('border-blue-500', 'bg-blue-100');
}

function handleDragLeave(e) {
    e.preventDefault();
    e.stopPropagation();
    const uploadArea = document.getElementById('upload-area');
    uploadArea.classList.remove('border-blue-500', 'bg-blue-100');
}


function handleFileSelect(e) {
    const file = e.target.files[0];
    if (file) {
        // 文件选择后不自动上传，需要点击提交按钮
    }
}

// 上传图片函数
async function uploadImage(fileParam = null) {
    const fileInput = document.getElementById('image-upload');
    const uploadBtn = document.getElementById('upload-image-btn');
    const statusDiv = document.getElementById('upload-status');
    const stemTextarea = document.getElementById('stem-textarea');
    
    // 获取文件：优先使用传入的参数，否则从 input 获取
    let file = fileParam;
    if (!file) {
        // 检查是否选择了文件
        if (!fileInput.files || fileInput.files.length === 0) {
            if (window.customAlert) {
                window.customAlert('请先选择图片文件！');
            } else {
                alert('请先选择图片文件！');
            }
            return;
        }
        file = fileInput.files[0];
    }
    
    // 检查文件类型
    if (!file || !file.type.startsWith('image/')) {
        if (window.customAlert) {
            window.customAlert('请选择图片文件！');
        } else {
            alert('请选择图片文件！');
        }
        return;
    }
    
    // 创建 FormData
    const formData = new FormData();
    formData.append('file', file);
    
    // 禁用按钮，显示上传中
    uploadBtn.disabled = true;
    uploadBtn.textContent = '上传中...';
    statusDiv.classList.remove('hidden');
    statusDiv.textContent = '正在上传图片...';
    statusDiv.className = 'mt-2 text-sm text-blue-600';
    
    try {
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        // 检查返回结果，可能的结构：{url: "..."} 或 {data: {url: "..."}} 或直接是字符串
        let imageUrl = null;
        if (typeof result === 'string') {
            imageUrl = result;
        } else if (result.url) {
            imageUrl = result.url;
        } else if (result.data && result.data.url) {
            imageUrl = result.data.url;
        } else if (result.data && typeof result.data === 'string') {
            imageUrl = result.data;
        } else {
            // 尝试从结果中提取 URL
            const resultStr = JSON.stringify(result);
            const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
            if (urlMatch) {
                imageUrl = urlMatch[0];
            }
        }
        
        if (!imageUrl) {
            throw new Error('接口返回格式异常，未找到图片URL。返回结果：' + JSON.stringify(result));
        }
        
        // 构建 image 标签
        const imageTag = `<image src="${imageUrl}"/>`;
        
        // 获取当前光标位置
        const cursorPos = stemTextarea.selectionStart;
        const textBefore = stemTextarea.value.substring(0, cursorPos);
        const textAfter = stemTextarea.value.substring(cursorPos);
        
        // 插入 image 标签
        stemTextarea.value = textBefore + imageTag + textAfter;
        
        // 设置光标位置到插入内容之后
        const newCursorPos = cursorPos + imageTag.length;
        stemTextarea.setSelectionRange(newCursorPos, newCursorPos);
        stemTextarea.focus();
        
        // 如果预览气泡正在显示，更新预览内容
        if (currentPreviewElement === stemTextarea) {
            updatePreviewContent(stemTextarea.value);
        }
        
        // 显示成功消息（短暂显示后自动隐藏）
        statusDiv.textContent = '图片上传成功！已插入到题干中。';
        statusDiv.className = 'mt-2 text-sm text-green-600';
        
        // 清空文件选择
        if (fileInput) {
            fileInput.value = '';
        }
        
        // 1.5秒后隐藏状态消息（不阻塞用户操作）
        setTimeout(() => {
            statusDiv.classList.add('hidden');
        }, 1500);
        
    } catch (error) {
        console.error('上传失败:', error);
        statusDiv.textContent = '上传失败: ' + error.message;
        statusDiv.className = 'mt-2 text-sm text-red-600';
        
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        // 恢复按钮
        uploadBtn.disabled = false;
        uploadBtn.textContent = '提交';
    }
}

</script>
{% endblock %}

