{% extends "layout.html" %}

{% block page_title %}题目管理{% endblock %}

{% block content %}
{% set is_audit_mode = is_audit_mode|default(false) %}
<div class="flex gap-6">
    <!-- 左侧目录索引 -->
    <div class="w-96 flex-shrink-0">
        <div class="apple-card p-6 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
            <div class="flex items-center justify-between mb-6 pb-3 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-800">{% if is_audit_mode %}未审核知识点{% else %}知识点目录{% endif %}</h2>
            </div>
            <nav class="space-y-1">
                {% macro render_kp_node(node, level) %}
                <div class="kp-node-item mb-1" data-kp-code="{{ node.kp_code }}" data-level="{{ level }}">
                    <div class="flex items-center gap-1 group">
                        {% if node.children|length > 0 %}
                        <button 
                            onclick="toggleKpNode('{{ node.kp_code }}'); event.stopPropagation();"
                            class="w-6 h-6 rounded flex items-center justify-center text-gray-500 hover:text-blue-600 hover:bg-blue-50 transition-all flex-shrink-0 kp-expand-btn"
                            data-expanded="{% if level == 0 %}true{% else %}false{% endif %}"
                            data-kp-code="{{ node.kp_code }}">
                            {% if level == 0 %}
                            <i class="ri-subtract-line text-sm"></i>
                            {% else %}
                            <i class="ri-add-line text-sm"></i>
                            {% endif %}
                        </button>
                        {% else %}
                        <div class="w-6 h-6 flex items-center justify-center flex-shrink-0">
                            <div class="w-1.5 h-1.5 rounded-full bg-gray-400"></div>
                    </div>
                        {% endif %}
                        <a href="javascript:void(0)" 
                           onclick="loadQuestionsByKp('{{ node.kp_code }}', '{{ node.name }}', this); return false;"
                           data-kp-code="{{ node.kp_code }}"
                           data-kp-name="{{ node.name }}"
                           class="flex-1 block px-3 py-2 rounded-lg hover:bg-gradient-to-r hover:from-blue-50 hover:to-indigo-50 transition-all border-l-2 border-transparent hover:border-blue-400 kp-link">
                            <div class="flex items-center gap-2 flex-nowrap">
                                {% if level == 0 %}
                                <span class="bg-gradient-to-r from-slate-600 to-slate-700 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">章</span>
                                {% elif level == 1 %}
                                <span class="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">节</span>
                                {% else %}
                                <span class="bg-gray-200 text-gray-700 px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0">小节</span>
                                {% endif %}
                                <span class="text-sm {% if level == 0 %}font-bold text-gray-800{% elif level == 1 %}font-semibold text-gray-800{% else %}font-normal text-gray-600{% endif %} group-hover:text-blue-600 transition-colors flex-1 min-w-0 truncate">{{ node.name }}</span>
                                {% set total_count = node.total_question_count|default(node.question_count|default(0)) %}
                                {% if total_count > 0 %}
                                <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0 ml-1">{{ total_count }}</span>
                                {% endif %}
                            </div>
                        </a>
                        </div>
                    {% if node.children|length > 0 %}
                    <div class="kp-children ml-8 mt-1 {% if level >= 1 %}hidden{% endif %}" id="kp-children-{{ node.kp_code }}" data-level="{{ level }}">
                        {% for child in node.children %}
                            {{ render_kp_node(child, level + 1) }}
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>
                {% endmacro %}
                
                <!-- 其他题目节点 -->
                <div class="kp-node-item mb-2 pb-2 border-b border-gray-200" data-kp-code="null" data-level="-1">
                    <a href="javascript:void(0)" 
                       onclick="loadQuestionsByKp('null', '其他题目', this); return false;"
                       data-kp-code="null"
                       data-kp-name="其他题目"
                       class="flex-1 block px-3 py-2 rounded-lg hover:bg-gradient-to-r hover:from-purple-50 hover:to-pink-50 transition-all border-l-2 border-transparent hover:border-purple-400 kp-link">
                        <div class="flex items-center gap-2 flex-nowrap">
                            <span class="bg-gradient-to-r from-purple-500 to-pink-500 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">其他</span>
                            <span class="text-sm font-bold text-gray-800 group-hover:text-purple-600 transition-colors flex-1 min-w-0 truncate">其他题目</span>
                            {% if other_questions_count|default(0) > 0 %}
                            <span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0 ml-1">{{ other_questions_count }}</span>
                            {% endif %}
                        </div>
                    </a>
                </div>
                
                {% if kp_tree %}
                    {% for root_node in kp_tree %}
                        {{ render_kp_node(root_node, 0) }}
                {% endfor %}
                {% else %}
                    <div class="text-sm text-gray-500 text-center py-8">暂无知识点数据</div>
                {% endif %}
            </nav>
        </div>
    </div>
    
    <!-- 右侧题目列表区域 -->
    <div class="flex-1">
        <!-- 年级筛选栏 -->
        <div class="mb-4 flex items-center gap-3">
            <span class="text-sm font-semibold text-gray-700">年级筛选：</span>
            <div class="flex items-center gap-2">
                <button 
                    id="grade-filter-all"
                    onclick="setGradeFilter(null)"
                    class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-gray-300 bg-white text-gray-700 hover:bg-gray-50 active">
                    全部
                </button>
                <button 
                    id="grade-filter-1"
                    onclick="setGradeFilter(1)"
                    class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-pink-300 bg-white text-pink-700 hover:bg-pink-50">
                    小学
                </button>
                <button 
                    id="grade-filter-2"
                    onclick="setGradeFilter(2)"
                    class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-blue-300 bg-white text-blue-700 hover:bg-blue-50">
                    初中
                </button>
                <button 
                    id="grade-filter-3"
                    onclick="setGradeFilter(3)"
                    class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-purple-300 bg-white text-purple-700 hover:bg-purple-50">
                    高中
                </button>
            </div>
            <span id="grade-filter-indicator" class="text-xs text-gray-500 ml-2 hidden">
                <span id="grade-filter-text"></span>
            </span>
        </div>
        
        <div id="questions-container" class="space-y-4">
            <div class="apple-card p-12 text-center">
                <div class="text-gray-400 mb-4">
                    <i class="ri-file-list-line text-6xl"></i>
                </div>
                <h3 class="text-lg font-bold text-gray-600 mb-2">请选择左侧知识点</h3>
                <p class="text-sm text-gray-500 mb-6">点击知识点查看该知识点下的题目</p>
                <div class="flex items-center justify-center gap-3">
                    <button onclick="showAddQuestionModal(null, null)" 
                            class="btn-apple bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 px-6 py-3 shadow-lg shadow-blue-200 flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                </svg>
                        录入题目
                    </button>
                    <button onclick="showBatchImportModal(null, null)" 
                            class="btn-apple bg-gradient-to-r from-green-600 to-emerald-600 text-white hover:from-green-700 hover:to-emerald-700 px-6 py-3 shadow-lg shadow-green-200 flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                        </svg>
                        批量导入
                            </button>
                        </div>
            </div>
        </div>
    </div>
                </div>

<script>
// 知识点树形数据（从服务器端传递）
const kpTreeData = {{ kp_tree|tojson|safe }};

// 当前选中的年级筛选（null表示全部，1=小学，2=初中，3=高中）
let currentGradeFilter = null;

// 设置年级筛选
function setGradeFilter(grade) {
    currentGradeFilter = grade;
    
    // 更新按钮样式
    document.querySelectorAll('.grade-filter-btn').forEach(btn => {
        btn.classList.remove('active', 'bg-pink-100', 'bg-blue-100', 'bg-purple-100', 'border-pink-500', 'border-blue-500', 'border-purple-500');
        btn.classList.add('border-gray-300', 'bg-white');
    });
    
    // 设置当前选中按钮的样式
    const indicator = document.getElementById('grade-filter-indicator');
    const indicatorText = document.getElementById('grade-filter-text');
    
    if (grade === null) {
        document.getElementById('grade-filter-all').classList.add('active', 'bg-gray-100', 'border-gray-500');
        indicator.classList.add('hidden');
    } else {
        const gradeNames = { 1: '小学', 2: '初中', 3: '高中' };
        const gradeColors = {
            1: { bg: 'bg-pink-100', border: 'border-pink-500' },
            2: { bg: 'bg-blue-100', border: 'border-blue-500' },
            3: { bg: 'bg-purple-100', border: 'border-purple-500' }
        };
        
        const btn = document.getElementById(`grade-filter-${grade}`);
        btn.classList.add('active', gradeColors[grade].bg, gradeColors[grade].border);
        btn.classList.remove('border-gray-300', 'bg-white');
        
        indicator.classList.remove('hidden');
        indicatorText.textContent = `当前筛选：${gradeNames[grade]}`;
    }
    
    // 如果当前有加载的题目列表，重新加载（根据年级筛选）
    if (currentKpCode) {
        loadQuestionsByKp(currentKpCode, currentKpName);
    }
}

// 页面加载时初始化年级筛选按钮样式
document.addEventListener('DOMContentLoaded', function() {
    // 默认选中"全部"
    setGradeFilter(null);
});

// 知识点目录折叠/展开功能
function toggleKpNode(kpCode) {
    const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
    const expandBtn = document.querySelector(`.kp-expand-btn[data-kp-code="${kpCode}"]`);
    
    if (!childrenContainer || !expandBtn) return;
    
    const isExpanded = expandBtn.getAttribute('data-expanded') === 'true';
    const icon = expandBtn.querySelector('i');
    
    if (isExpanded) {
        // 折叠
        childrenContainer.classList.add('hidden');
        expandBtn.setAttribute('data-expanded', 'false');
        if (icon) {
            icon.className = 'ri-add-line text-sm';
        }
    } else {
        // 展开
        childrenContainer.classList.remove('hidden');
        expandBtn.setAttribute('data-expanded', 'true');
        if (icon) {
            icon.className = 'ri-subtract-line text-sm';
        }
    }
}

// 存储当前知识点的代码和名称（用于构建返回链接）
let currentKpCode = null;
let currentKpName = null;

// 加载指定知识点的题目列表（带页码）
function loadQuestionsByKpPage(kpCode, page) {
    // 更新URL参数，但不刷新页面
    const url = new URL(window.location);
    url.searchParams.set('kp_code', kpCode);
    if (page > 1) {
        url.searchParams.set('page', page);
    } else {
        url.searchParams.delete('page');
    }
    window.history.pushState({}, '', url);
    
    // 重新加载题目列表
    const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
    const kpName = kpLink ? (kpLink.getAttribute('data-kp-name') || kpCode) : kpCode;
    loadQuestionsByKp(kpCode, kpName, kpLink, page);
}

// 加载指定知识点的题目列表
function loadQuestionsByKp(kpCode, kpName, linkElement, page = null) {
    const container = document.getElementById('questions-container');
    if (!container) return;
    
    // 保存当前知识点信息
    currentKpCode = kpCode;
    currentKpName = kpName;
    
    // 更新选中状态
    document.querySelectorAll('.kp-link').forEach(link => {
        link.classList.remove('bg-blue-50', 'border-blue-400');
    });
    if (linkElement) {
        linkElement.classList.add('bg-blue-50', 'border-blue-400');
    }
    
    // 显示加载状态
    container.innerHTML = `
        <div class="apple-card p-12 text-center">
            <div class="text-blue-500 mb-4">
                <i class="ri-loader-4-line text-6xl animate-spin"></i>
            </div>
            <p class="text-gray-600">正在加载题目...</p>
        </div>
    `;
    
    // 如果没有指定页码，从URL参数获取
    if (page === null) {
        const urlParams = new URLSearchParams(window.location.search);
        const pageParam = urlParams.get('page');
        page = pageParam ? parseInt(pageParam) : 1;
    }
    
    // 构建请求URL（如果有年级筛选或页码，添加参数）
    let apiUrl = `/api/questions_by_kp/${encodeURIComponent(kpCode)}`;
    const params = [];
    if (currentGradeFilter !== null) {
        params.push(`grade=${currentGradeFilter}`);
    }
    if (page > 1) {
        params.push(`page=${page}`);
    }
    if (params.length > 0) {
        apiUrl += '?' + params.join('&');
    }
    
    // 请求题目列表
    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || '加载失败');
            }
            
            const questions = data.questions || [];
            const kpName = data.kp_name || kpCode;
            
            // 获取统计数据（即使没有题目也要显示）
            const stats = data.stats || {};
            const auditStats = stats.audit || {pass: 0, fail: 0, pending: 0, pass_rate: 0, audit_rate: 0};
            const difficultyStats = stats.difficulty || {jichu: 0, tifen: 0, peiyou: 0, unknown: 0};
            
            // 构建录入题目URL
            const addQuestionUrl = `/add_question?kp_code=${encodeURIComponent(kpCode)}`;
            
            // 渲染题目列表
            let html = '';
            
            // 如果是"其他题目"，只显示按钮，不显示横幅和统计数据
            if (kpCode === 'null' || kpCode === '') {
                html = `
                    <div class="mb-6 flex items-center gap-2 flex-wrap">
                        <button onclick="showAddQuestionModal(null, null)" 
                                class="bg-white text-blue-600 hover:bg-blue-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-blue-200">
                            <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                            </svg>
                            <span>录入题目</span>
                        </button>
                        <button onclick="showBatchImportModal(null, null)" 
                                class="bg-white text-green-600 hover:bg-green-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-green-200">
                            <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                            </svg>
                            <span>批量导入</span>
                        </button>
                    </div>
                `;
            } else {
                // 其他知识点显示完整的横幅和统计数据
                html = `
                <div class="mb-6">
                    <div class="bg-gradient-to-r from-gray-800 via-slate-800 to-gray-900 text-white px-6 py-5 rounded-2xl shadow-lg">
                        <div class="mb-4">
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex-1 min-w-0">
                                    <h2 class="text-xl font-bold mb-2 truncate">${kpName}</h2>
                                    <p class="text-sm text-white/80">共 ${stats.total || questions.length} 道题目</p>
                                </div>
                            </div>
                            <div class="flex items-center gap-2 flex-wrap">
                                <button onclick="showAddQuestionModal('${kpCode}', '${kpName}')" 
                                        class="bg-white text-blue-600 hover:bg-blue-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-blue-200">
                                    <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                                    </svg>
                                    <span>录入题目</span>
                                </button>
                                <button onclick="showBatchImportModal('${kpCode}', '${kpName}')" 
                                        class="bg-white text-green-600 hover:bg-green-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-green-200">
                                    <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                                    </svg>
                                    <span>批量导入</span>
                                </button>
                            </div>
                        </div>
                        
                        <!-- 统计数据 -->
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4 pt-4 border-t border-white/20">
                            <!-- 审核统计 -->
                            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
                                <div class="text-xs text-white/70 mb-1">审核状态</div>
                                <div class="space-y-1">
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">合格</span>
                                        <span class="font-bold text-green-200">${auditStats.pass || 0}</span>
                    </div>
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">不合格</span>
                                        <span class="font-bold text-red-200">${auditStats.fail || 0}</span>
                </div>
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">待审核</span>
                                        <span class="font-bold text-orange-200">${auditStats.pending || 0}</span>
                                    </div>
        </div>
    </div>
    
                            <!-- 难度统计 -->
                            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
                                <div class="text-xs text-white/70 mb-1">难度分布</div>
                                <div class="space-y-1">
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">筑基</span>
                                        <span class="font-bold text-green-200">${difficultyStats.jichu || 0}</span>
                                    </div>
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">提分</span>
                                        <span class="font-bold text-yellow-200">${difficultyStats.tifen || 0}</span>
                                    </div>
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">培优</span>
                                        <span class="font-bold text-orange-200">${difficultyStats.peiyou || 0}</span>
                                    </div>
                                    ${(difficultyStats.unknown || 0) > 0 ? `
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="text-white/90">未设置</span>
                                        <span class="font-bold text-gray-300">${difficultyStats.unknown || 0}</span>
                                    </div>
                                    ` : ''}
                                </div>
                            </div>
            
                            <!-- 审核率 -->
                            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
                                <div class="text-xs text-white/70 mb-1">审核进度</div>
                                <div class="space-y-2">
                                    <div>
                                        <div class="flex items-center justify-between text-xs mb-1">
                                            <span class="text-white/90">审核率</span>
                                            <span class="font-bold text-white">${auditStats.audit_rate || 0}%</span>
                        </div>
                                        <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
                                            <div class="h-full bg-blue-300 rounded-full transition-all" style="width: ${auditStats.audit_rate || 0}%"></div>
                    </div>
                                    </div>
                                    <div>
                                        <div class="flex items-center justify-between text-xs mb-1">
                                            <span class="text-white/90">通过率</span>
                                            <span class="font-bold text-white">${auditStats.pass_rate || 0}%</span>
                                        </div>
                                        <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
                                            <div class="h-full bg-green-300 rounded-full transition-all" style="width: ${auditStats.pass_rate || 0}%"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 题型统计 -->
                            <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
                                <div class="text-xs text-white/70 mb-1">题型分布</div>
                                <div class="space-y-1 max-h-20 overflow-y-auto">
                                    ${Object.keys(stats.question_type || {}).length > 0 ? Object.entries(stats.question_type || {}).map(([type, count]) => {
                                        // 题型映射：英文转中文
                                        const typeMap = {
                                            'choice': '选择题',
                                            'fill': '填空题',
                                            'answer': '解答题',
                                            '选择题': '选择题',
                                            '填空题': '填空题',
                                            '解答题': '解答题'
                                        };
                                        const typeName = typeMap[type] || type;
                                        return `
                                            <div class="flex items-center justify-between text-xs">
                                                <span class="text-white/90 truncate">${typeName}</span>
                                                <span class="font-bold text-white ml-2">${count}</span>
                        </div>
                                        `;
                                    }).join('') : '<div class="text-xs text-white/60">暂无数据</div>'}
                            </div>
                        </div>
                    </div>
                </div>
                `;
            }
            
            html += `<div class="space-y-3 ${kpCode === 'null' || kpCode === '' ? '' : 'mt-6'}">`;
            
            // 如果没有题目，显示提示信息
            if (questions.length === 0) {
                html += `
                    <div class="apple-card p-12 text-center">
                        <div class="text-gray-400 mb-4">
                            <i class="ri-file-list-line text-6xl"></i>
                        </div>
                        <h3 class="text-lg font-bold text-gray-600 mb-2">该知识点下暂无题目</h3>
                        <p class="text-sm text-gray-500 mb-6">点击上方"录入题目"或"批量导入"按钮开始添加题目</p>
                    </div>
                `;
            } else {
                // 获取分页信息（从API返回）
                const pagination = data.pagination || {};
                const currentPage = pagination.page || 1;
                const totalPages = pagination.total_pages || 1;
                const totalCount = pagination.total_count || questions.length;
                const pageSize = pagination.page_size || 20;
                const startIndex = (currentPage - 1) * pageSize;
                const endIndex = Math.min(startIndex + pageSize, totalCount);
                
                // 有题目时，渲染题目列表
                questions.forEach(q => {
                    // 审核状态
                    let auditBadge = '';
                    if (q.audit_reason === '合格') {
                        auditBadge = '<span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">合格</span>';
                    } else if (q.audit_reason === '不合格') {
                        auditBadge = '<span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">不合格</span>';
                    } else {
                        auditBadge = '<span class="bg-orange-100 text-orange-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">待审核</span>';
                    }
                    
                    // 难度标签
                    let difficultyBadge = '';
                    if (q.difficulty !== null && q.difficulty !== undefined) {
                        const diff = parseFloat(q.difficulty);
                        if (diff === 0.2 || Math.abs(diff - 0.2) < 0.1) {
                            difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-green-100 text-green-700 border border-green-200 whitespace-nowrap">筑基</span>';
                        } else if (diff === 0.4 || Math.abs(diff - 0.4) < 0.1) {
                            difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-yellow-100 text-yellow-700 border border-yellow-200 whitespace-nowrap">提分</span>';
                        } else if (diff === 0.7 || Math.abs(diff - 0.7) < 0.1) {
                            difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-orange-100 text-orange-700 border border-orange-200 whitespace-nowrap">培优</span>';
                        }
                    }
                    
                    // 题型标签
                    const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
                    const questionTypeText = typeMap[q.question_type] || q.question_type || '未分类';
                    
                    // 年级标签
                    let gradeBadge = '';
                    if (q.grade !== null && q.grade !== undefined) {
                        const grade = parseInt(q.grade);
                        if (grade === 1) {
                            gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-pink-100 text-pink-700 border border-pink-200 whitespace-nowrap">小学</span>';
                        } else if (grade === 2) {
                            gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700 border border-blue-200 whitespace-nowrap">初中</span>';
                        } else if (grade === 3) {
                            gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700 border border-purple-200 whitespace-nowrap">高中</span>';
                        }
                    }
                    
                    // 题干预览（去除HTML标签，只显示文本）
                    const stemText = (q.stem || '').replace(/<[^>]*>/g, '').substring(0, 150);
                    
                    html += `
                        <a href="/detail/${q.question_code}${currentKpCode ? '?kp_code=' + encodeURIComponent(currentKpCode) : ''}" 
                           class="apple-card p-4 block group hover:shadow-lg transition-all border-l-4 border-transparent hover:border-blue-500">
                            <div class="flex items-center gap-4">
                                <!-- 左侧：题号 -->
                                <div class="flex-shrink-0">
                                    <span class="text-xs font-mono text-gray-500 bg-gray-100 px-3 py-1.5 rounded font-semibold">${q.question_code}</span>
                                </div>
                                
                                <!-- 中间：题干内容 -->
                                <div class="flex-1 min-w-0">
                                    <div class="text-sm text-gray-800 group-hover:text-blue-600 transition-colors line-clamp-1">
                                        ${stemText}${stemText.length >= 150 ? '...' : ''}
                                    </div>
                                </div>

                                <!-- 右侧：标签和操作 -->
                                <div class="flex items-center gap-3 flex-shrink-0">
                                    <span class="text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded">${questionTypeText}</span>
                                    ${gradeBadge}
                                    ${difficultyBadge}
                                    ${auditBadge}
                                    <span class="text-xs text-blue-600 font-medium opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">查看详情 →</span>
                                </div>
                            </div>
                        </a>
                    `;
                });
                
                // 添加翻页控件
                if (totalPages > 1) {
                    html += `
                        <div class="mt-6 flex items-center justify-between">
                            <div class="text-sm text-gray-600">
                                显示第 ${startIndex + 1}-${endIndex} 题，共 ${totalCount} 题
                            </div>
                            <div class="flex items-center gap-2">
                                <button 
                                    onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage - 1})"
                                    ${currentPage === 1 ? 'disabled' : ''}
                                    class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
                                        currentPage === 1 
                                            ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed' 
                                            : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
                                    }">
                                    <i class="ri-arrow-left-s-line"></i> 上一页
                                </button>
                                
                                <div class="flex items-center gap-1">
                                    ${Array.from({length: totalPages}, (_, i) => i + 1).map(page => {
                                        if (page === 1 || page === totalPages || (page >= currentPage - 2 && page <= currentPage + 2)) {
                                            return `
                                                <button 
                                                    onclick="loadQuestionsByKpPage('${kpCode}', ${page})"
                                                    class="px-3 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
                                                        page === currentPage
                                                            ? 'border-blue-500 bg-blue-500 text-white'
                                                            : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
                                                    }">
                                                    ${page}
                                                </button>
                                            `;
                                        } else if (page === currentPage - 3 || page === currentPage + 3) {
                                            return '<span class="px-2 text-gray-400">...</span>';
                                        }
                                        return '';
                                    }).join('')}
                                </div>
                                
                                <button 
                                    onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage + 1})"
                                    ${currentPage === totalPages ? 'disabled' : ''}
                                    class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
                                        currentPage === totalPages 
                                            ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed' 
                                            : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
                                    }">
                                    下一页 <i class="ri-arrow-right-s-line"></i>
                                </button>
                            </div>
                        </div>
                    `;
                }
            }
            
            html += '</div>';
            container.innerHTML = html;
            
            // 渲染数学公式
            if (window.renderMathInElement) {
                container.querySelectorAll('.math-render').forEach(el => {
                    try {
                        window.renderMathInElement(el, {
                            delimiters: [
                                {left: "$$", right: "$$", display: true},
                                {left: "$", right: "$", display: false},
                                {left: "\\(", right: "\\)", display: false},
                                {left: "\\[", right: "\\]", display: true}
                            ],
                            throwOnError: false
                        });
                    } catch (e) {
                        console.warn('数学公式渲染失败:', e);
                    }
                });
            }
        })
        .catch(error => {
            container.innerHTML = `
                <div class="apple-card p-12 text-center">
                    <div class="text-red-400 mb-4">
                        <i class="ri-error-warning-line text-6xl"></i>
                    </div>
                    <h3 class="text-lg font-bold text-gray-600 mb-2">加载失败</h3>
                    <p class="text-sm text-red-500">${error.message || '未知错误'}</p>
                </div>
            `;
        });
}

// 页面加载时，设置进度条宽度和初始化知识点目录
document.addEventListener('DOMContentLoaded', function() {
    // 设置进度条宽度
    document.querySelectorAll('.progress-gradient[data-width]').forEach(function(el) {
        const width = parseFloat(el.getAttribute('data-width')) || 0;
        el.style.width = width + '%';
    });
    
    // 初始化知识点目录：默认展开第一级节点
    const firstLevelNodes = document.querySelectorAll('.kp-node-item[data-level="0"]');
    firstLevelNodes.forEach(node => {
        const kpCode = node.getAttribute('data-kp-code');
        const expandBtn = node.querySelector('.kp-expand-btn');
        if (expandBtn && expandBtn.getAttribute('data-expanded') === 'true') {
            const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
            if (childrenContainer) {
                childrenContainer.classList.remove('hidden');
            }
        }
    });
    
    // 如果 URL 中有锚点（hash），自动滚动到对应知识点
    const hash = window.location.hash;
    if (hash && hash.startsWith('#kp-')) {
        const targetId = hash.substring(1); // 去掉 # 号
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
            // 延迟一下，确保页面完全渲染
            setTimeout(() => {
                targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                // 高亮一下，让用户知道定位到了
                targetElement.style.transition = 'box-shadow 0.3s';
                targetElement.style.boxShadow = '0 0 20px rgba(59, 130, 246, 0.5)';
                setTimeout(() => {
                    targetElement.style.boxShadow = '';
                }, 2000);
            }, 100);
        }
    }
    
    // 如果 URL 中有 kp_code 参数，自动加载对应知识点的题目列表
    const urlParams = new URLSearchParams(window.location.search);
    const kpCode = urlParams.get('kp_code');
    if (kpCode) {
        // 延迟一下，确保页面完全渲染
        setTimeout(() => {
            // 查找对应的知识点链接
            const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
            if (kpLink) {
                // 获取知识点名称（从链接文本或data属性）
                const kpName = kpLink.getAttribute('data-kp-name') || kpLink.textContent.trim() || kpCode;
                
                // 展开父节点（如果需要）
                let parent = kpLink.closest('.kp-node-item');
                while (parent) {
                    const parentKpCode = parent.getAttribute('data-kp-code');
                    if (parentKpCode) {
                        const expandBtn = parent.querySelector('.kp-expand-btn');
                        if (expandBtn && expandBtn.getAttribute('data-expanded') === 'false') {
                            toggleKpNode(parentKpCode);
                        }
                    }
                    parent = parent.parentElement?.closest('.kp-node-item');
                }
                
                // 滚动到知识点链接
                setTimeout(() => {
                    kpLink.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    // 加载题目列表
                    loadQuestionsByKp(kpCode, kpName, kpLink);
                }, 200);
            } else {
                // 如果找不到链接，直接加载题目（可能是通过API获取知识点名称）
                fetch(`/api/questions_by_kp/${encodeURIComponent(kpCode)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const kpName = data.kp_name || kpCode;
                            loadQuestionsByKp(kpCode, kpName, null);
                        }
                    })
                    .catch(error => {
                        console.error('加载知识点信息失败:', error);
                        // 即使失败也尝试加载题目列表
                        loadQuestionsByKp(kpCode, kpCode, null);
                    });
            }
        }, 300);
    }
});

// 显示添加知识点弹窗
function showAddKpModal() {
    const modal = document.createElement('div');
    modal.id = 'add-kp-modal';
    modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
    
    const dialog = document.createElement('div');
    dialog.style.cssText = 'background:white;padding:2rem;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,0.3);max-width:500px;width:90%;';
    
    const title = document.createElement('div');
    title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
    title.textContent = '添加知识点';
    
    // Chapter 选择
    const chapterLabel = document.createElement('label');
    chapterLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
    chapterLabel.textContent = '选择章节 *';
    
    const chapterSelect = document.createElement('select');
    chapterSelect.id = 'add-kp-chapter-select';
    chapterSelect.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
    chapterSelect.innerHTML = '<option value="">请选择章节</option>';
    
    // 填充章节选项（从知识点树形数据中提取）
    function extractChaptersFromTree(tree) {
        const chapters = [];
        tree.forEach(function(node) {
            chapters.push({
                id: node.kp_code,
                label: node.name
            });
        });
        return chapters;
    }
    
    const chapters = extractChaptersFromTree(kpTreeData || []);
    chapters.forEach(function(chapter) {
        const option = document.createElement('option');
        option.value = chapter.id;
        option.textContent = chapter.label;
        chapterSelect.appendChild(option);
    });
    
    // 类型选择
    const typeLabel = document.createElement('label');
    typeLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
    typeLabel.textContent = '添加类型 *';
    
    const typeSelect = document.createElement('select');
    typeSelect.id = 'add-kp-type-select';
    typeSelect.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
    typeSelect.innerHTML = '<option value="">请选择类型</option><option value="section">节 (Section)</option><option value="subsection">小节 (Subsection)</option>';
    
    // Section 选择（仅当添加 subsection 时显示）
    const sectionLabel = document.createElement('label');
    sectionLabel.id = 'add-kp-section-label';
    sectionLabel.style.cssText = 'display:none;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
    sectionLabel.textContent = '选择节 *';
    
    const sectionSelect = document.createElement('select');
    sectionSelect.id = 'add-kp-section-select';
    sectionSelect.style.cssText = 'display:none;width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
    sectionSelect.innerHTML = '<option value="">请选择节</option>';
    
    // 监听类型变化，更新 section 选择框
    typeSelect.addEventListener('change', function() {
        if (this.value === 'subsection') {
            sectionLabel.style.display = 'block';
            sectionSelect.style.display = 'block';
            sectionSelect.required = true;
            updateSectionOptions(chapterSelect.value);
        } else {
            sectionLabel.style.display = 'none';
            sectionSelect.style.display = 'none';
            sectionSelect.required = false;
        }
    });
    
    // 监听章节变化，更新 section 选项
    chapterSelect.addEventListener('change', function() {
        if (typeSelect.value === 'subsection') {
            updateSectionOptions(this.value);
        }
    });
    
    function updateSectionOptions(chapterId) {
        sectionSelect.innerHTML = '<option value="">请选择节</option>';
        if (!chapterId) return;
        
        // 从 kpTreeData 中查找对应章节的子节点（sections）
        function findNodeByCode(tree, code) {
            for (let node of tree) {
                if (node.kp_code === code) {
                    return node;
                }
                if (node.children && node.children.length > 0) {
                    const found = findNodeByCode(node.children, code);
                    if (found) return found;
                }
            }
            return null;
        }
        
        const chapter = findNodeByCode(kpTreeData || [], chapterId);
        if (chapter && chapter.children) {
            chapter.children.forEach(function(section) {
                const option = document.createElement('option');
                option.value = section.kp_code;
                option.textContent = section.name;
                sectionSelect.appendChild(option);
            });
        }
    }
    
    // 名称输入
    const nameLabel = document.createElement('label');
    nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
    nameLabel.textContent = '名称 *';
    
    const nameInput = document.createElement('input');
    nameInput.type = 'text';
    nameInput.id = 'add-kp-name-input';
    nameInput.placeholder = '请输入名称';
    nameInput.required = true;
    nameInput.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
    nameInput.addEventListener('focus', function() {
        this.style.borderColor = '#3b82f6';
    });
    nameInput.addEventListener('blur', function() {
        this.style.borderColor = '#e5e7eb';
    });
    
    // 按钮容器
    const btnContainer = document.createElement('div');
    btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
    
    const cancelBtn = document.createElement('button');
    cancelBtn.style.cssText = 'background:#f3f4f6;color:#374151;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
    cancelBtn.textContent = '取消';
    cancelBtn.addEventListener('mouseenter', function() {
        this.style.background = '#e5e7eb';
    });
    cancelBtn.addEventListener('mouseleave', function() {
        this.style.background = '#f3f4f6';
    });
    
    const confirmBtn = document.createElement('button');
    confirmBtn.style.cssText = 'background:#3b82f6;color:white;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
    confirmBtn.textContent = '确定';
    confirmBtn.addEventListener('mouseenter', function() {
        this.style.background = '#2563eb';
    });
    confirmBtn.addEventListener('mouseleave', function() {
        this.style.background = '#3b82f6';
    });
    
    const handleCancel = () => {
        document.body.removeChild(modal);
    };
    
    const handleConfirm = async () => {
        const chapterId = chapterSelect.value;
        const type = typeSelect.value;
        const sectionId = sectionSelect.value;
        const name = nameInput.value.trim();
        
        if (!chapterId || !type || !name) {
            if (window.customAlert) {
                window.customAlert('请填写所有必填项！');
            } else {
                alert('请填写所有必填项！');
            }
            return;
        }
        
        if (type === 'subsection' && !sectionId) {
            if (window.customAlert) {
                window.customAlert('添加小节时必须选择节！');
            } else {
                alert('添加小节时必须选择节！');
            }
            return;
        }
        
        // 禁用按钮
        confirmBtn.disabled = true;
        confirmBtn.textContent = '添加中...';
        
        try {
            const response = await fetch('/add_kp_node', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    chapter_id: parseInt(chapterId),
                    type: type,
                    section_id: sectionId ? parseInt(sectionId) : null,
                    name: name
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                if (window.customAlert) {
                    window.customAlert('添加成功！页面即将刷新。', () => {
                        window.location.reload();
                    });
                } else {
                    alert('添加成功！');
                    window.location.reload();
                }
            } else {
                if (window.customAlert) {
                    window.customAlert('添加失败: ' + result.error);
                } else {
                    alert('添加失败: ' + result.error);
                }
                confirmBtn.disabled = false;
                confirmBtn.textContent = '确定';
            }
        } catch (error) {
            console.error('添加失败:', error);
            if (window.customAlert) {
                window.customAlert('添加失败: ' + error.message);
            } else {
                alert('添加失败: ' + error.message);
            }
            confirmBtn.disabled = false;
            confirmBtn.textContent = '确定';
        }
    };
    
    cancelBtn.onclick = handleCancel;
    confirmBtn.onclick = handleConfirm;
    
    // 点击背景关闭
    modal.onclick = (e) => {
        if (e.target === modal) {
            handleCancel();
        }
    };
    
    dialog.appendChild(title);
    dialog.appendChild(chapterLabel);
    dialog.appendChild(chapterSelect);
    dialog.appendChild(typeLabel);
    dialog.appendChild(typeSelect);
    dialog.appendChild(sectionLabel);
    dialog.appendChild(sectionSelect);
    dialog.appendChild(nameLabel);
    dialog.appendChild(nameInput);
    btnContainer.appendChild(cancelBtn);
    btnContainer.appendChild(confirmBtn);
    dialog.appendChild(btnContainer);
    modal.appendChild(dialog);
    document.body.appendChild(modal);
    
    // 聚焦第一个输入框
    setTimeout(() => chapterSelect.focus(), 100);
}

// 显示编辑知识点名称弹窗
function showEditKpModal(nodeId, nodeType, currentName) {
    const modal = document.createElement('div');
    modal.id = 'edit-kp-modal';
    modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
    
    const dialog = document.createElement('div');
    dialog.style.cssText = 'background:white;padding:2rem;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,0.3);max-width:500px;width:90%;';
    
    const title = document.createElement('div');
    title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
    const typeName = nodeType === 'chapter' ? '章节' : nodeType === 'section' ? '节' : '小节';
    title.textContent = '编辑' + typeName + '名称';
    
    // 名称输入
    const nameLabel = document.createElement('label');
    nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
    nameLabel.textContent = '名称 *';
    
    const nameInput = document.createElement('input');
    nameInput.type = 'text';
    nameInput.id = 'edit-kp-name-input';
    nameInput.value = currentName;
    nameInput.required = true;
    nameInput.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
    nameInput.addEventListener('focus', function() {
        this.style.borderColor = '#3b82f6';
    });
    nameInput.addEventListener('blur', function() {
        this.style.borderColor = '#e5e7eb';
    });
    
    // 按钮容器
    const btnContainer = document.createElement('div');
    btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
    
    const cancelBtn = document.createElement('button');
    cancelBtn.style.cssText = 'background:#f3f4f6;color:#374151;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
    cancelBtn.textContent = '取消';
    cancelBtn.addEventListener('mouseenter', function() {
        this.style.background = '#e5e7eb';
    });
    cancelBtn.addEventListener('mouseleave', function() {
        this.style.background = '#f3f4f6';
    });
    
    const confirmBtn = document.createElement('button');
    confirmBtn.style.cssText = 'background:#3b82f6;color:white;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
    confirmBtn.textContent = '确定';
    confirmBtn.addEventListener('mouseenter', function() {
        this.style.background = '#2563eb';
    });
    confirmBtn.addEventListener('mouseleave', function() {
        this.style.background = '#3b82f6';
    });
    
    const handleCancel = () => {
        document.body.removeChild(modal);
    };
    
    const handleConfirm = async () => {
        const name = nameInput.value.trim();
        
        if (!name) {
            if (window.customAlert) {
                window.customAlert('请输入名称！');
            } else {
                alert('请输入名称！');
            }
            return;
        }
        
        // 禁用按钮
        confirmBtn.disabled = true;
        confirmBtn.textContent = '保存中...';
        
        try {
            const response = await fetch('/update_kp_node', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    node_id: nodeId,
                    node_type: nodeType,
                    name: name
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                // 更新页面上的显示
                const labelElement = document.getElementById(nodeType + '-label-' + nodeId);
                if (labelElement) {
                    labelElement.textContent = name;
                }
                
                if (window.customAlert) {
                    window.customAlert('修改成功！', () => {
                        document.body.removeChild(modal);
                    });
                } else {
                    alert('修改成功！');
                    document.body.removeChild(modal);
                }
            } else {
                if (window.customAlert) {
                    window.customAlert('修改失败: ' + result.error);
                } else {
                    alert('修改失败: ' + result.error);
                }
                confirmBtn.disabled = false;
                confirmBtn.textContent = '确定';
            }
        } catch (error) {
            console.error('修改失败:', error);
            if (window.customAlert) {
                window.customAlert('修改失败: ' + error.message);
            } else {
                alert('修改失败: ' + error.message);
            }
            confirmBtn.disabled = false;
            confirmBtn.textContent = '确定';
        }
    };
    
    cancelBtn.onclick = handleCancel;
    confirmBtn.onclick = handleConfirm;
    
    // 点击背景关闭
    modal.onclick = (e) => {
        if (e.target === modal) {
            handleCancel();
        }
    };
    
    // Enter 键确认
    nameInput.onkeypress = function(e) {
        if (e.key === 'Enter') {
            handleConfirm();
        }
    };
    
    dialog.appendChild(title);
    dialog.appendChild(nameLabel);
    dialog.appendChild(nameInput);
    btnContainer.appendChild(cancelBtn);
    btnContainer.appendChild(confirmBtn);
    dialog.appendChild(btnContainer);
    modal.appendChild(dialog);
    document.body.appendChild(modal);
    
    // 聚焦输入框并选中所有文本
    setTimeout(() => {
        nameInput.focus();
        nameInput.select();
    }, 100);
}
</script>

<!-- 批量导入模态框 -->
<div id="batch-import-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[95vh] overflow-hidden flex flex-col">
        <div class="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 flex items-center justify-between">
            <h2 class="text-xl font-bold">批量导入题目</h2>
            <button onclick="hideBatchImportModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
        </div>
        <div class="flex-1 overflow-hidden flex flex-col">
            <!-- JSON输入区域 -->
            <div class="p-6 border-b border-gray-200">
                <label class="block text-sm font-bold text-gray-700 mb-2">粘贴JSON数据（每道题以number字段切分）</label>
                <textarea id="batch-json-input" 
                          class="w-full h-32 p-3 border border-gray-300 rounded-lg font-mono text-xs focus:border-green-500 focus:ring-2 focus:ring-green-500/10 outline-none"
                          placeholder='[{"number": "1", "stem": "...", "options": {"A": "...", "B": "..."}, "answer": "A", "question_type": "选择题", "solution": "..."}, ...]'
                          oninput="handleBatchJsonInputChange()"></textarea>
                <p class="text-xs text-gray-500 mt-2">支持数组格式或单个对象格式，每道题必须包含number字段。粘贴后自动填充到下方表单</p>
            </div>
            
            <!-- 题目卡片区域 -->
            <div id="batch-preview" class="hidden flex-1 overflow-hidden flex flex-col">
                <!-- 题目导航 -->
                <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <button id="batch-prev-btn" onclick="switchBatchQuestion(-1)" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-3 py-1.5 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                            </svg>
                        </button>
                        <span class="text-sm font-medium text-gray-700">
                            第 <span id="current-question-index">1</span> / <span id="total-question-count">0</span> 题
                        </span>
                        <button id="batch-next-btn" onclick="switchBatchQuestion(1)" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-3 py-1.5 disabled:opacity-50 disabled:cursor-not-allowed">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                            </svg>
                        </button>
                    </div>
                    <div class="text-xs text-gray-500">题号: <span id="current-question-number">-</span></div>
                </div>
                
                <!-- 题目表单卡片容器 -->
                <div class="flex-1 overflow-y-auto p-6 relative">
                    <div id="questions-list" class="relative"></div>
                </div>
            </div>
        </div>
        
        <!-- LaTeX 实时预览气泡 -->
        <div id="batch-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-[60] overflow-hidden flex flex-col hidden" 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="hideBatchPreviewBubble()" 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="batch-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>
        <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end gap-3">
            <button onclick="hideBatchImportModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
            <button id="batch-submit-btn" onclick="submitBatchQuestions()" class="btn-apple bg-gradient-to-r from-green-600 to-emerald-600 text-white hover:from-green-700 hover:to-emerald-700 px-4 py-2 hidden">批量提交</button>
        </div>
    </div>
</div>

<!-- 录入题目模态框 -->
<div id="add-question-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-6 py-4 flex items-center justify-between">
            <div>
                <h2 class="text-xl font-bold">录入新题目</h2>
                <div class="mt-1 flex items-center gap-2 text-sm text-white/90">
                    <span id="add-question-kp-name" class="font-semibold"></span>
                    <span class="text-white/70">|</span>
                    <span class="font-mono text-xs bg-white/20 px-2 py-0.5 rounded" id="add-question-kp-code"></span>
                </div>
            </div>
            <button onclick="hideAddQuestionModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
        </div>
        <div class="flex-1 overflow-hidden flex">
            <!-- 左侧表单区域 -->
            <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
                <form id="add-question-form" class="space-y-4">
                    <p class="text-gray-400 text-xs mb-4">填写题目信息，保存后自动生成题号并创建新题目</p>
                    
                    <!-- 题型和难度选择 -->
                    <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="add-question-type" 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 class="space-y-1">
                            <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
                            <div class="flex items-center gap-2">
                                <select name="difficulty" id="add-question-difficulty" class="flex-1 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>
                                <button type="button" id="add-evaluate-difficulty-btn" onclick="evaluateAddQuestionDifficulty()" 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-2 px-3 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>
                        </div>
                    </div>
                    
                    <!-- 年级选择（所有题目必填） -->
                    <div id="add-question-grade-section" class="space-y-1">
                        <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
                        <select name="grade" id="add-question-grade" required 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="1">小学</option>
                            <option value="2">初中</option>
                            <option value="3">高中</option>
                        </select>
                    </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="add-upload-stem-btn" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit">上传图片</button>
                    </div>
                    <textarea name="stem" id="add-question-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="请输入题干内容或拖拽图片..."></textarea>
                </div>
                
                <!-- 选项编辑（仅选择题显示） -->
                <div id="add-options-section" class="space-y-2">
                    <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
                    <div class="grid grid-cols-2 gap-3">
                        <div class="space-y-1">
                            <label class="text-xs font-medium text-gray-600">选项 A</label>
                            <div class="flex gap-1.5">
                                <textarea id="add-option-A" 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或拖拽图片..."></textarea>
                                <button type="button" onclick="uploadAddQuestionOptionImage('A')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
                            </div>
                        </div>
                        <div class="space-y-1">
                            <label class="text-xs font-medium text-gray-600">选项 B</label>
                            <div class="flex gap-1.5">
                                <textarea id="add-option-B" 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或拖拽图片..."></textarea>
                                <button type="button" onclick="uploadAddQuestionOptionImage('B')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
                            </div>
                        </div>
                        <div class="space-y-1">
                            <label class="text-xs font-medium text-gray-600">选项 C</label>
                            <div class="flex gap-1.5">
                                <textarea id="add-option-C" 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或拖拽图片..."></textarea>
                                <button type="button" onclick="uploadAddQuestionOptionImage('C')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
                            </div>
                        </div>
                        <div class="space-y-1">
                            <label class="text-xs font-medium text-gray-600">选项 D</label>
                            <div class="flex gap-1.5">
                                <textarea id="add-option-D" 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或拖拽图片..."></textarea>
                                <button type="button" onclick="uploadAddQuestionOptionImage('D')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</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="add-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内容", ...}'></textarea>
                    </div>
                </div>
                
                <!-- 答案 -->
                <div class="space-y-1">
                    <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
                    <input type="text" name="answer" id="add-question-answer" 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">
                    <div class="flex items-center justify-between">
                        <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
                        <button type="button" onclick="uploadAddQuestionSolutionImage()" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit">上传图片</button>
                    </div>
                    <textarea name="solution" id="add-question-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="请输入解析内容或拖拽图片..."></textarea>
                </div>
            </form>
            </div>
            
            <!-- 右侧预览区域 -->
            <div class="w-[420px] bg-gray-50 border-l border-gray-200 flex flex-col">
                <div id="add-question-preview-content" class="flex-1 p-6 overflow-y-auto bg-gray-50 text-base leading-relaxed">
                    <p class="text-sm text-gray-400 text-center">题目预览</p>
                </div>
            </div>
        </div>
        <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-between">
            <button onclick="checkDuplicateForAddQuestion()" class="btn-apple bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 px-4 py-2 flex items-center justify-center gap-2 whitespace-nowrap">
                <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                <span>查重检测</span>
            </button>
            <div class="flex items-center gap-3">
                <button onclick="hideAddQuestionModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
                <button onclick="submitAddQuestion()" class="btn-apple bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 px-4 py-2">保存并创建</button>
            </div>
        </div>
    </div>
</div>

<!-- 题目比对弹窗 -->
<div id="duplicate-comparison-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10003;">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
        <div class="bg-gradient-to-r from-orange-600 to-red-600 text-white px-6 py-4 flex items-center justify-between">
            <div>
                <h2 class="text-xl font-bold">题目查重比对</h2>
                <p id="duplicate-similarity-info" class="text-sm text-white/90 mt-1"></p>
            </div>
            <button onclick="hideDuplicateComparisonModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
        </div>
        <div class="flex-1 overflow-hidden flex">
            <!-- 左侧：当前录入的题目 -->
            <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
                <div class="mb-4">
                    <h3 class="text-lg font-bold text-gray-800 mb-2">当前录入的题目</h3>
                </div>
                <div id="duplicate-current-question" class="space-y-4">
                    <!-- 动态填充 -->
                </div>
            </div>
            <!-- 右侧：库中重复的题目 -->
            <div class="flex-1 overflow-y-auto p-6 bg-gray-50">
                <div class="mb-4">
                    <h3 class="text-lg font-bold text-gray-800 mb-2">库中重复的题目</h3>
                </div>
                <div id="duplicate-existing-question" class="space-y-4">
                    <!-- 动态填充 -->
                </div>
            </div>
        </div>
        <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end">
            <button onclick="hideDuplicateComparisonModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-6 py-2">关闭</button>
        </div>
    </div>
</div>

<script>
// 批量导入相关变量
let parsedQuestions = [];
let currentBatchQuestionIndex = 0;
let batchJsonSyncTimer = null;
let isSyncingBatchFromJson = false;
let currentBatchKpCode = null;
let currentBatchKpName = null;

function showBatchImportModal(kpCode, kpName) {
    // 处理 'null' 字符串，转换为 null
    if (kpCode === 'null' || kpCode === null) {
        currentBatchKpCode = null;
        currentBatchKpName = '其他题目（未关联知识点）';
    } else {
        currentBatchKpCode = kpCode;
        currentBatchKpName = kpName || '未指定知识点';
    }
    // 保存是否是"其他题目"的状态，用于后续渲染时显示年级选择
    window.isBatchOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
    document.getElementById('batch-import-modal').classList.remove('hidden');
    document.getElementById('batch-json-input').focus();
}

function hideBatchImportModal() {
    document.getElementById('batch-import-modal').classList.add('hidden');
    document.getElementById('batch-json-input').value = '';
    document.getElementById('batch-preview').classList.add('hidden');
    document.getElementById('batch-submit-btn').classList.add('hidden');
    parsedQuestions = [];
    currentBatchQuestionIndex = 0;
}

function handleBatchJsonInputChange() {
    const jsonInput = document.getElementById('batch-json-input');
    const jsonText = jsonInput.value.trim();
    
    if (jsonText) {
        try {
            JSON.parse(jsonText);
            jsonInput.classList.remove('border-red-500');
            jsonInput.classList.add('border-gray-300');
            
            clearTimeout(batchJsonSyncTimer);
            batchJsonSyncTimer = setTimeout(() => {
                if (!isSyncingBatchFromJson) {
                    parseBatchJson();
                }
            }, 800);
        } catch (e) {
            jsonInput.classList.remove('border-gray-300');
            jsonInput.classList.add('border-red-500');
        }
    }
}

function parseBatchJson() {
    const jsonInput = document.getElementById('batch-json-input');
    const jsonText = jsonInput.value.trim();
    
    if (!jsonText) return;
    
    try {
        isSyncingBatchFromJson = true;
        let data = JSON.parse(jsonText);
        if (!Array.isArray(data)) {
            data = [data];
        }
        
        parsedQuestions = data.filter(q => q && q.number);
        if (parsedQuestions.length === 0) return;
        
        currentBatchQuestionIndex = 0;
        displayBatchPreview();
    } catch (error) {
        console.warn('JSON格式错误：', error);
    } finally {
        isSyncingBatchFromJson = false;
    }
}

function switchBatchQuestion(direction) {
    const newIndex = currentBatchQuestionIndex + direction;
    if (newIndex >= 0 && newIndex < parsedQuestions.length) {
        currentBatchQuestionIndex = newIndex;
        showBatchQuestion(currentBatchQuestionIndex);
        updateBatchNavigation();
    }
}

function updateBatchNavigation() {
    const prevBtn = document.getElementById('batch-prev-btn');
    const nextBtn = document.getElementById('batch-next-btn');
    const currentIndexSpan = document.getElementById('current-question-index');
    const totalCountSpan = document.getElementById('total-question-count');
    const questionNumberSpan = document.getElementById('current-question-number');
    
    if (prevBtn && nextBtn && currentIndexSpan && totalCountSpan) {
        currentIndexSpan.textContent = currentBatchQuestionIndex + 1;
        totalCountSpan.textContent = parsedQuestions.length;
        prevBtn.disabled = currentBatchQuestionIndex === 0;
        nextBtn.disabled = currentBatchQuestionIndex === parsedQuestions.length - 1;
        if (questionNumberSpan && parsedQuestions[currentBatchQuestionIndex]) {
            questionNumberSpan.textContent = parsedQuestions[currentBatchQuestionIndex].number || currentBatchQuestionIndex + 1;
        }
    }
}

function showBatchQuestion(index) {
    const questionsList = document.getElementById('questions-list');
    if (!questionsList) return;
    
    questionsList.querySelectorAll('.batch-question-card').forEach(card => card.classList.add('hidden'));
    const currentCard = document.getElementById(`batch-q-card-${index}`);
    if (currentCard) currentCard.classList.remove('hidden');
    updateBatchFullPreview();
}

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

function updateBatchFullPreview() {
    const previewContent = document.getElementById('batch-latex-preview-content');
    const bubble = document.getElementById('batch-latex-preview-bubble');
    if (!previewContent || !bubble) return;
    
    // 获取当前显示的题目卡片
    const currentCard = document.getElementById(`batch-q-card-${currentBatchQuestionIndex}`);
    if (!currentCard) return;
    
    // 收集当前题目的所有数据
    const stemTextarea = currentCard.querySelector('.batch-stem');
    const answerInput = currentCard.querySelector('.batch-answer');
    const solutionTextarea = currentCard.querySelector('.batch-solution');
    const optionsPreview = currentCard.querySelector('.batch-options-preview');
    const questionTypeSelect = currentCard.querySelector('.batch-question-type');
    const difficultySelect = currentCard.querySelector('.batch-difficulty');
    
    let html = '<div class="space-y-6">';
    
    // 题型和难度信息
    html += '<div class="border-b border-gray-200 pb-3 mb-3">';
    html += '<div class="flex items-center gap-3 text-sm">';
    const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
    const questionType = questionTypeSelect ? questionTypeSelect.value : 'choice';
    html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
    if (difficultySelect && difficultySelect.value) {
        const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
        html += `<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-bold">${diffMap[difficultySelect.value] || difficultySelect.value}</span>`;
    }
    html += '</div>';
    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 stem = stemTextarea ? stemTextarea.value : '';
    if (stem) {
        // 先提取图片标签，替换为占位符
        const imagePlaceholders = [];
        let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
            const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
            imagePlaceholders.push(url);
            return placeholder;
        });
        
        // 转义HTML
        let stemHtml = stemProcessed
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        
        // 将占位符替换为img标签
        imagePlaceholders.forEach((url, index) => {
            const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
            const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
            stemHtml = stemHtml.replace(placeholder, imgTag);
        });
        
        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>';
        
        // 直接从选项输入框读取内容，确保图片标签能正确显示
        let hasOptions = false;
        ['A', 'B', 'C', 'D'].forEach(key => {
            const optionInput = currentCard.querySelector(`.batch-option-${key}`);
            const optionText = optionInput ? optionInput.value : '';
            
            if (optionText && optionText.trim()) {
                hasOptions = true;
                html += `<div class="mb-3">`;
                html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
                
                // 处理选项文本，支持图片标签
                // 先提取图片标签，替换为占位符
                const optionImagePlaceholders = [];
                let optionProcessed = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
                    const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${optionImagePlaceholders.length}__`;
                    optionImagePlaceholders.push(url);
                    return placeholder;
                });
                
                // 转义HTML
                let optionHtml = optionProcessed
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/\n/g, '<br>');
                
                // 将占位符替换为img标签
                optionImagePlaceholders.forEach((url, index) => {
                    const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${index}__`;
                    const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
                    optionHtml = optionHtml.replace(placeholder, imgTag);
                });
                
                html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
                html += `</div>`;
            }
        });
        
        if (!hasOptions) {
            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">${escapeHtml(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) {
        // 先提取图片标签，替换为占位符
        const solutionImagePlaceholders = [];
        let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
            const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
            solutionImagePlaceholders.push(url);
            return placeholder;
        });
        
        // 转义HTML
        let solutionHtml = solutionProcessed
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        
        // 将占位符替换为img标签
        solutionImagePlaceholders.forEach((url, index) => {
            const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
            const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
            solutionHtml = solutionHtml.replace(placeholder, imgTag);
        });
        
        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');
}

function displayBatchPreview() {
    const previewDiv = document.getElementById('batch-preview');
    const questionsList = document.getElementById('questions-list');
    
    previewDiv.classList.remove('hidden');
    document.getElementById('batch-submit-btn').classList.remove('hidden');
    questionsList.innerHTML = '';
    
    // 创建所有题目卡片（默认隐藏）
    parsedQuestions.forEach((q, index) => {
        const questionId = `batch-q-card-${index}`;
        const questionDiv = document.createElement('div');
        questionDiv.className = `batch-question-card apple-card p-6 space-y-4 ${index === 0 ? '' : 'hidden'}`;
        questionDiv.id = questionId;
        questionDiv.setAttribute('data-index', index);
        
        // 解析选项
        let optionsJson = '{}';
        let optionA = '', optionB = '', optionC = '', optionD = '';
        if (q.options && typeof q.options === 'object') {
            optionsJson = JSON.stringify(q.options, null, 2);
            optionA = q.options.A || '';
            optionB = q.options.B || '';
            optionC = q.options.C || '';
            optionD = q.options.D || '';
        }
        
        // 映射题型
        const questionType = mapQuestionType(q.question_type);
        
        questionDiv.innerHTML = `
            <div class="border-b border-gray-100 pb-3 mb-3">
                <div class="flex items-center gap-2">
                    <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">题号 ${q.number || index + 1}</span>
                </div>
            </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" class="batch-question-type 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" ${questionType === 'choice' ? 'selected' : ''}>选择题</option>
                        <option value="fill" ${questionType === 'fill' ? 'selected' : ''}>填空题</option>
                        <option value="answer" ${questionType === 'answer' ? 'selected' : ''}>解答题</option>
                    </select>
                </div>
                <div class="space-y-1">
                    <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
                    <div class="flex items-center gap-2">
                        <select name="difficulty" class="batch-difficulty flex-1 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" ${q.difficulty == 0.2 || q.difficulty == '0.2' ? 'selected' : ''}>筑基</option>
                            <option value="0.4" ${q.difficulty == 0.4 || q.difficulty == '0.4' ? 'selected' : ''}>提分</option>
                            <option value="0.7" ${q.difficulty == 0.7 || q.difficulty == '0.7' ? 'selected' : ''}>培优</option>
                        </select>
                        <button type="button" class="batch-evaluate-difficulty-btn 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-2 px-3 shadow-md whitespace-nowrap" data-index="${index}" onclick="evaluateBatchDifficulty(${index})">
                            <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>
                </div>
            </div>
            
            <!-- 年级选择（所有题目必填） -->
            <div class="batch-grade-section space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
                <select name="grade" class="batch-grade 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" required>
                    <option value="">请选择年级</option>
                    <option value="1" ${q.grade == 1 || q.grade == '1' || (currentGradeFilter === 1 && !q.grade) ? 'selected' : ''}>小学</option>
                    <option value="2" ${q.grade == 2 || q.grade == '2' || (currentGradeFilter === 2 && !q.grade) ? 'selected' : ''}>初中</option>
                    <option value="3" ${q.grade == 3 || q.grade == '3' || (currentGradeFilter === 3 && !q.grade) ? 'selected' : ''}>高中</option>
                </select>
            </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" class="batch-upload-stem btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit" data-index="${index}">上传图片</button>
                </div>
                <textarea name="stem" class="batch-stem 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="请输入题干内容或拖拽图片..."
                    data-index="${index}"
                    data-type="stem"
                    required>${escapeHtml(q.stem || '')}</textarea>
            </div>
            
            <!-- 选项编辑 -->
            <div class="batch-options-section space-y-2" style="display: ${questionType === 'choice' ? 'block' : 'none'}">
                <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
                <div class="grid grid-cols-2 gap-3">
                    <div class="option-item">
                        <label class="text-xs font-medium text-gray-600 mb-1 block">选项 A</label>
                        <div class="flex gap-1.5">
                            <textarea class="batch-option-A 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的内容或拖拽图片..."
                                data-index="${index}" data-option="A" data-type="option">${escapeHtml(optionA)}</textarea>
                            <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="A">上传图片</button>
                        </div>
                    </div>
                    <div class="option-item">
                        <label class="text-xs font-medium text-gray-600 mb-1 block">选项 B</label>
                        <div class="flex gap-1.5">
                            <textarea class="batch-option-B 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的内容或拖拽图片..."
                                data-index="${index}" data-option="B" data-type="option">${escapeHtml(optionB)}</textarea>
                            <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="B">上传图片</button>
                        </div>
                    </div>
                    <div class="option-item">
                        <label class="text-xs font-medium text-gray-600 mb-1 block">选项 C</label>
                        <div class="flex gap-1.5">
                            <textarea class="batch-option-C 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的内容或拖拽图片..."
                                data-index="${index}" data-option="C" data-type="option">${escapeHtml(optionC)}</textarea>
                            <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="C">上传图片</button>
                        </div>
                    </div>
                    <div class="option-item">
                        <label class="text-xs font-medium text-gray-600 mb-1 block">选项 D</label>
                        <div class="flex gap-1.5">
                            <textarea class="batch-option-D 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的内容或拖拽图片..."
                                data-index="${index}" data-option="D" data-type="option">${escapeHtml(optionD)}</textarea>
                            <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="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 class="batch-options-preview 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"
                        data-index="${index}"
                        placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'>${escapeHtml(optionsJson)}</textarea>
                </div>
            </div>
            
            <!-- 答案 -->
            <div class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
                <input type="text" name="answer" class="batch-answer 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" value="${escapeHtml(q.answer || '')}">
            </div>
            
            <!-- 解析 -->
            <div class="space-y-2">
                <div class="flex items-center justify-between">
                    <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
                    <button type="button" class="batch-upload-solution btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit" data-index="${index}">上传图片</button>
                </div>
                <textarea name="solution" class="batch-solution 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="请输入解析内容或拖拽图片..."
                    data-index="${index}"
                    data-type="solution">${escapeHtml(q.solution || '')}</textarea>
            </div>
            
            <!-- 查重检测按钮 -->
            <div class="pt-4 border-t border-gray-200">
                <button onclick="checkDuplicateForBatch(${index})" class="btn-apple bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 px-4 py-2 w-full flex items-center justify-center gap-2 whitespace-nowrap">
                    <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    <span>查重检测</span>
                </button>
            </div>
        `;
        
        questionsList.appendChild(questionDiv);
        
        // 设置选项同步逻辑
        setupBatchQuestionEvents(index);
    });
    
    // 显示当前题并更新导航（不重置索引）
    showBatchQuestion(currentBatchQuestionIndex);
    updateBatchNavigation();
    
    // 初始化预览
    updateBatchFullPreview();
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

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

function setupBatchQuestionEvents(index) {
    // 题型变化时显示/隐藏选项
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    if (!questionDiv) return;
    
    const typeSelect = questionDiv.querySelector('.batch-question-type');
    const optionsSection = questionDiv.querySelector('.batch-options-section');
    
    typeSelect.addEventListener('change', function() {
        if (this.value === 'choice') {
            optionsSection.style.display = 'block';
        } else {
            optionsSection.style.display = 'none';
        }
        updateBatchFullPreview();
    });
    
    // 选项输入框同步到预览
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const input = questionDiv.querySelector(`.batch-option-${opt}`);
        if (input) {
            input.addEventListener('input', function() {
                updateBatchOptionsPreview(index);
                updateBatchFullPreview();
            });
        }
    });
    
    // 预览框同步到输入框
    const previewTextarea = questionDiv.querySelector('.batch-options-preview');
    if (previewTextarea) {
        previewTextarea.addEventListener('input', function() {
            syncBatchOptionsFromPreview(index);
            updateBatchFullPreview();
        });
    }
    
    // 题干、答案、解析字段变化时更新预览和拖拽上传
    const stemTextarea = questionDiv.querySelector('.batch-stem');
    if (stemTextarea) {
        stemTextarea.addEventListener('input', updateBatchFullPreview);
        // 拖拽上传功能
        stemTextarea.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('border-blue-500', 'bg-blue-50');
        });
        stemTextarea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
        });
        stemTextarea.addEventListener('drop', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                await uploadBatchImageFile(files[0], index, 'stem');
            }
        });
    }
    
    const answerInput = questionDiv.querySelector('.batch-answer');
    if (answerInput) {
        answerInput.addEventListener('input', updateBatchFullPreview);
    }
    
    const solutionTextarea = questionDiv.querySelector('.batch-solution');
    if (solutionTextarea) {
        solutionTextarea.addEventListener('input', updateBatchFullPreview);
        // 拖拽上传功能
        solutionTextarea.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('border-blue-500', 'bg-blue-50');
        });
        solutionTextarea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
        });
        solutionTextarea.addEventListener('drop', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                await uploadBatchImageFile(files[0], index, 'solution');
            }
        });
    }
    
    const difficultySelect = questionDiv.querySelector('.batch-difficulty');
    if (difficultySelect) {
        difficultySelect.addEventListener('change', updateBatchFullPreview);
    }
    
    // 图片上传按钮
    const uploadStemBtn = questionDiv.querySelector('.batch-upload-stem');
    if (uploadStemBtn) {
        uploadStemBtn.addEventListener('click', function() {
            uploadBatchImage(index, 'stem');
        });
    }
    
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const uploadBtn = questionDiv.querySelector(`.batch-upload-option[data-option="${opt}"]`);
        if (uploadBtn) {
            uploadBtn.addEventListener('click', function() {
                uploadBatchImage(index, 'option', opt);
            });
        }
    });
    
    const uploadSolutionBtn = questionDiv.querySelector('.batch-upload-solution');
    if (uploadSolutionBtn) {
        uploadSolutionBtn.addEventListener('click', function() {
            uploadBatchImage(index, 'solution');
        });
    }
    
    // 选项拖拽上传功能
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const optionInput = questionDiv.querySelector(`.batch-option-${opt}`);
        if (optionInput) {
            optionInput.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.add('border-blue-500', 'bg-blue-50');
            });
            optionInput.addEventListener('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('border-blue-500', 'bg-blue-50');
            });
            optionInput.addEventListener('drop', async function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('border-blue-500', 'bg-blue-50');
                const files = e.dataTransfer.files;
                if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                    await uploadBatchImageFile(files[0], index, 'option', opt);
                }
            });
        }
    });
    
    // 粘贴图片功能
    const allInputs = questionDiv.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 uploadBatchImageToInput(file, input, index);
                    }
                    break;
                }
            }
        });
    });
}

function updateBatchOptionsPreview(index) {
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    const previewTextarea = questionDiv.querySelector('.batch-options-preview');
    const optionsObj = {};
    
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const input = questionDiv.querySelector(`.batch-option-${opt}`);
        if (input && input.value.trim()) {
            optionsObj[opt] = input.value.trim();
        }
    });
    
    previewTextarea.value = JSON.stringify(optionsObj, null, 2);
}

function syncBatchOptionsFromPreview(index) {
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    const previewTextarea = questionDiv.querySelector('.batch-options-preview');
    
    try {
        const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const input = questionDiv.querySelector(`.batch-option-${opt}`);
            if (input) {
                input.value = optionsObj[opt] || '';
            }
        });
    } catch (error) {
        console.warn('选项预览 JSON 格式错误:', error);
    }
}

function uploadBatchImage(index, type, option = null) {
    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 uploadBatchImageFile(file, index, type, option);
    };
    
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
}

// 通用图片上传函数：上传图片并插入到指定输入框
async function uploadBatchImageToInput(file, inputElement, index) {
    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 (inputElement.classList.contains('batch-option-A') || 
            inputElement.classList.contains('batch-option-B') ||
            inputElement.classList.contains('batch-option-C') ||
            inputElement.classList.contains('batch-option-D')) {
            updateBatchOptionsPreview(index);
        } else if (inputElement.classList.contains('batch-options-preview')) {
            // 如果是在选项预览框中粘贴，需要同步到各个选项输入框
            syncBatchOptionsFromPreview(index);
        }
        
        // 更新完整预览
        updateBatchFullPreview();
        
    } 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;
    }
}

// 保留旧函数以兼容拖拽上传
async function uploadBatchImageFile(file, index, type, option) {
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    if (!questionDiv) {
        questionDiv = document.querySelector(`[data-index="${index}"]`);
    }
    if (!questionDiv) return;
    
    let targetInput;
    
    if (type === 'stem') {
        targetInput = questionDiv.querySelector('.batch-stem');
    } else if (type === 'solution') {
        targetInput = questionDiv.querySelector('.batch-solution');
    } else if (type === 'answer') {
        targetInput = questionDiv.querySelector('.batch-answer');
    } else if (type === 'options-preview') {
        targetInput = questionDiv.querySelector('.batch-options-preview');
    } else if (type === 'option' && option) {
        targetInput = questionDiv.querySelector(`.batch-option-${option}`);
    }
    
    if (!targetInput) return;
    
    // 使用新的通用函数
    await uploadBatchImageToInput(file, targetInput, index);
}

// 批量导入的难度评价函数
async function evaluateBatchDifficulty(index) {
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    if (!questionDiv) return;
    
    const btn = questionDiv.querySelector('.batch-evaluate-difficulty-btn');
    const difficultySelect = questionDiv.querySelector('.batch-difficulty');
    
    if (!btn || !difficultySelect) return;
    
    // 收集题目信息
    const stemTextarea = questionDiv.querySelector('.batch-stem');
    const answerInput = questionDiv.querySelector('.batch-answer');
    const solutionTextarea = questionDiv.querySelector('.batch-solution');
    const optionsPreview = questionDiv.querySelector('.batch-options-preview');
    const questionTypeSelect = questionDiv.querySelector('.batch-question-type');
    
    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();
        
        // 处理返回的 difficulty_level
        let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
        
        // 映射难度等级到枚举值
        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;
            difficultySelect.dispatchEvent(new Event('change', { bubbles: true }));
            updateBatchFullPreview();
        } 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;
    }
}

async function submitBatchQuestions() {
    const questionDivs = document.querySelectorAll('[data-index]');
    if (questionDivs.length === 0) {
        if (window.customAlert) {
            window.customAlert('没有可提交的题目');
        } else {
            alert('没有可提交的题目');
        }
        return;
    }
    
    const submitBtn = document.getElementById('batch-submit-btn');
    submitBtn.disabled = true;
    submitBtn.textContent = '提交中...';
    
    let successCount = 0;
    const userName = localStorage.getItem('user_name') || '';
    
    for (let i = 0; i < questionDivs.length; i++) {
        const questionDiv = questionDivs[i];
        const index = parseInt(questionDiv.getAttribute('data-index'));
        
        try {
            const stem = questionDiv.querySelector('.batch-stem').value.trim();
            if (!stem) continue;
            
            const questionData = {
                stem: stem,
                answer: questionDiv.querySelector('.batch-answer').value.trim(),
                solution: questionDiv.querySelector('.batch-solution').value.trim(),
                question_type: questionDiv.querySelector('.batch-question-type').value
            };
            
            // 只在有知识点代码时才添加 kp_code
            if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
                questionData.kp_code = currentBatchKpCode;
            }
            
            // 处理年级（所有题目必填）
            const gradeSelect = questionDiv.querySelector('.batch-grade');
            if (gradeSelect) {
                const grade = gradeSelect.value;
                if (!grade) {
                    if (window.customAlert) {
                        window.customAlert(`第 ${index + 1} 道题目：请选择年级`);
                    } else {
                        alert(`第 ${index + 1} 道题目：请选择年级`);
                    }
                    gradeSelect.focus();
                    submitBtn.disabled = false;
                    submitBtn.textContent = '批量提交';
                    return;
                }
                questionData.grade = parseInt(grade);
            }
            
            const difficulty = questionDiv.querySelector('.batch-difficulty').value;
            if (difficulty) questionData.difficulty = parseFloat(difficulty);
            
            const optionsPreview = questionDiv.querySelector('.batch-options-preview');
            if (questionData.question_type === 'choice' && optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
                try {
                    const optionsObj = JSON.parse(optionsPreview.value.trim());
                    if (Object.keys(optionsObj).length > 0) {
                        questionData.options = JSON.stringify(optionsObj);
                    }
                } catch (e) {
                    console.warn('选项JSON解析失败:', e);
                }
            }
            
            if (userName) questionData.create_by = userName;
            
            const response = await fetch('/create_question', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(questionData)
            });
            
            const result = await response.json();
            if (result.success) {
                successCount++;
                // 调用接口2确认不重复
                if (result.question_id) {
                    try {
                        await fetch('/api/confirm_repeat', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({
                                questionId: result.question_id,
                                isRepeat: 0
                            })
                        });
                    } catch (error) {
                        console.warn('确认查重结果失败:', error);
                    }
                }
            }
        } catch (error) {
            console.error('提交失败:', error);
        }
    }
    
    submitBtn.disabled = false;
    submitBtn.textContent = '批量提交';
    
    const message = `成功导入 ${successCount} 道题`;
    if (window.customAlert) {
        window.customAlert(message, () => {
            if (successCount > 0) {
                // 只在有知识点代码时才刷新题目列表
                if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
                    loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
                }
                hideBatchImportModal();
            }
        });
    } else {
        alert(message);
        if (successCount > 0) {
            // 只在有知识点代码时才刷新题目列表
            if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
                loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
            }
            hideBatchImportModal();
        }
    }
}

// ==================== 录入题目弹窗相关函数 ====================
let currentAddQuestionKpCode = null;
let currentAddQuestionKpName = null;

function showAddQuestionModal(kpCode, kpName) {
    // 处理 'null' 字符串，转换为 null
    if (kpCode === 'null' || kpCode === null) {
        currentAddQuestionKpCode = null;
        currentAddQuestionKpName = null;
    } else {
        currentAddQuestionKpCode = kpCode;
        currentAddQuestionKpName = kpName;
    }
    
    // 判断是否是"其他题目"
    const isOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
    
    // 设置知识点信息
    if (kpCode && kpCode !== 'null' && kpName && kpName !== 'null') {
        document.getElementById('add-question-kp-name').textContent = kpName;
        document.getElementById('add-question-kp-code').textContent = kpCode;
    } else {
        document.getElementById('add-question-kp-name').textContent = '其他题目（未关联知识点）';
        document.getElementById('add-question-kp-code').textContent = 'N/A';
    }
    
    // 重置表单
    document.getElementById('add-question-form').reset();
    document.getElementById('add-question-type').value = 'choice';
    document.getElementById('add-question-difficulty').value = '';
    
    // 如果有年级筛选，自动填充年级（但可以修改）
    if (document.getElementById('add-question-grade')) {
        if (currentGradeFilter !== null) {
            document.getElementById('add-question-grade').value = currentGradeFilter.toString();
        } else {
            document.getElementById('add-question-grade').value = '';
        }
    }
    ['A', 'B', 'C', 'D'].forEach(opt => {
        document.getElementById(`add-option-${opt}`).value = '';
    });
    // 重置选项预览框
    const optionsPreview = document.getElementById('add-options-preview');
    if (optionsPreview) {
        optionsPreview.value = '';
    }
    
    // 显示选项区域（默认选择题）
    document.getElementById('add-options-section').style.display = 'block';
    
    // 设置题型变化监听器
    const typeSelect = document.getElementById('add-question-type');
    const optionsSection = document.getElementById('add-options-section');
    typeSelect.onchange = function() {
        if (this.value === 'choice') {
            optionsSection.style.display = 'block';
        } else {
            optionsSection.style.display = 'none';
        }
        updateAddQuestionPreview();
    };
    
    // 设置预览更新监听器
    setupAddQuestionPreviewListeners();
    
    // 设置图片上传和粘贴功能
    setupAddQuestionImageUpload();
    
    // 显示弹窗
    document.getElementById('add-question-modal').classList.remove('hidden');
    
    // 更新预览和选项预览
    updateAddQuestionOptionsPreview();
    updateAddQuestionPreview();
    
    // 聚焦到题干输入框
    setTimeout(() => {
        document.getElementById('add-question-stem').focus();
    }, 100);
}

function hideAddQuestionPreview() {
    // 预览区域始终显示，这个函数可以用于未来扩展
}

// ==================== 图片上传和粘贴功能 ====================
function setupAddQuestionImageUpload() {
    // 题干图片上传按钮
    const uploadStemBtn = document.getElementById('add-upload-stem-btn');
    if (uploadStemBtn) {
        uploadStemBtn.onclick = function() {
            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 uploadAddQuestionImageToInput(file, document.getElementById('add-question-stem'));
                }
            };
            document.body.appendChild(fileInput);
            fileInput.click();
            document.body.removeChild(fileInput);
        };
    }
    
    // 题干拖拽上传
    const stemTextarea = document.getElementById('add-question-stem');
    if (stemTextarea) {
        stemTextarea.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('border-blue-500', 'bg-blue-50');
        });
        stemTextarea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
        });
        stemTextarea.addEventListener('drop', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                await uploadAddQuestionImageToInput(files[0], this);
            }
        });
    }
    
    // 选项拖拽上传
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const optionInput = document.getElementById(`add-option-${opt}`);
        if (optionInput) {
            optionInput.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.add('border-blue-500', 'bg-blue-50');
            });
            optionInput.addEventListener('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('border-blue-500', 'bg-blue-50');
            });
            optionInput.addEventListener('drop', async function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.classList.remove('border-blue-500', 'bg-blue-50');
                const files = e.dataTransfer.files;
                if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                    await uploadAddQuestionImageToInput(files[0], this);
                }
            });
        }
    });
    
    // 解析拖拽上传
    const solutionTextarea = document.getElementById('add-question-solution');
    if (solutionTextarea) {
        solutionTextarea.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('border-blue-500', 'bg-blue-50');
        });
        solutionTextarea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
        });
        solutionTextarea.addEventListener('drop', async function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('border-blue-500', 'bg-blue-50');
            const files = e.dataTransfer.files;
            if (files && files.length > 0 && files[0].type.startsWith('image/')) {
                await uploadAddQuestionImageToInput(files[0], this);
            }
        });
    }
    
    // 为所有输入框添加粘贴图片功能
    const allInputs = document.querySelectorAll('#add-question-form textarea, #add-question-form 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 uploadAddQuestionImageToInput(file, this);
                    }
                    break;
                }
            }
        });
    });
}

// 通用图片上传函数：上传图片并插入到指定输入框
async function uploadAddQuestionImageToInput(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 }));
        
        // 更新预览和选项预览
        updateAddQuestionOptionsPreview();
        updateAddQuestionPreview();
        
    } 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 uploadAddQuestionOptionImage(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) {
            await uploadAddQuestionImageToInput(file, document.getElementById(`add-option-${optionKey}`));
        }
    };
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
}

// 解析图片上传函数
function uploadAddQuestionSolutionImage() {
    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 uploadAddQuestionImageToInput(file, document.getElementById('add-question-solution'));
        }
    };
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
}

function setupAddQuestionPreviewListeners() {
    // 题干预览
    const stemTextarea = document.getElementById('add-question-stem');
    if (stemTextarea) {
        stemTextarea.addEventListener('input', updateAddQuestionPreview);
        stemTextarea.addEventListener('focus', updateAddQuestionPreview);
    }
    
    // 选项预览 - 从各个选项输入框自动拼接成JSON
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const optionInput = document.getElementById(`add-option-${opt}`);
        if (optionInput) {
            optionInput.addEventListener('input', function() {
                updateAddQuestionOptionsPreview();
                updateAddQuestionPreview();
            });
        }
    });
    
    // 选项预览框 - 从JSON同步回各个选项输入框
    const optionsPreview = document.getElementById('add-options-preview');
    if (optionsPreview) {
        optionsPreview.addEventListener('input', function() {
            syncAddQuestionOptionsFromPreview();
            updateAddQuestionPreview();
        });
    }
    
    // 答案预览
    const answerInput = document.getElementById('add-question-answer');
    if (answerInput) {
        answerInput.addEventListener('input', updateAddQuestionPreview);
    }
    
    // 解析预览
    const solutionTextarea = document.getElementById('add-question-solution');
    if (solutionTextarea) {
        solutionTextarea.addEventListener('input', updateAddQuestionPreview);
        solutionTextarea.addEventListener('focus', updateAddQuestionPreview);
    }
    
    // 题型和难度变化
    const typeSelect = document.getElementById('add-question-type');
    if (typeSelect) {
        typeSelect.addEventListener('change', updateAddQuestionPreview);
    }
    
    const difficultySelect = document.getElementById('add-question-difficulty');
    if (difficultySelect) {
        difficultySelect.addEventListener('change', updateAddQuestionPreview);
    }
}

function updateAddQuestionPreview() {
    const previewContent = document.getElementById('add-question-preview-content');
    if (!previewContent) return;
    
    const stem = document.getElementById('add-question-stem')?.value || '';
    const answer = document.getElementById('add-question-answer')?.value || '';
    const solution = document.getElementById('add-question-solution')?.value || '';
    const questionType = document.getElementById('add-question-type')?.value || 'choice';
    const difficulty = document.getElementById('add-question-difficulty')?.value || '';
    
    let html = '<div class="space-y-6">';
    
    // 题型和难度信息
    html += '<div class="border-b border-gray-200 pb-3 mb-3">';
    html += '<div class="flex items-center gap-3 text-sm">';
    const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
    html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
    if (difficulty) {
        const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
        html += `<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-bold">${diffMap[difficulty] || difficulty}</span>`;
    }
    html += '</div>';
    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>';
    if (stem) {
        // 处理图片标签
        let stemHtml = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
            return `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
        });
        
        // 转义HTML（但保留图片标签）
        stemHtml = stemHtml
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        
        // 恢复图片标签
        stemHtml = stemHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
            return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
        });
        
        html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
    } else {
        html += '<p class="text-xs text-gray-400">暂无内容</p>';
    }
    html += '</div>';
    
    // 选项预览（仅选择题）
    if (questionType === 'choice') {
        html += '<div class="border-b border-gray-200 pb-4">';
        html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
        let hasOptions = false;
        ['A', 'B', 'C', 'D'].forEach(key => {
            const optionText = document.getElementById(`add-option-${key}`)?.value || '';
            if (optionText && optionText.trim()) {
                hasOptions = true;
                html += `<div class="mb-3">`;
                html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
                
                // 处理选项文本，支持图片标签
                let optionHtml = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
                    return `<img src="${url}" class="max-w-full max-h-[200px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="选项图片" style="object-fit: contain;">`;
                });
                
                // 转义HTML
                optionHtml = optionHtml
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/\n/g, '<br>');
                
                // 恢复图片标签
                optionHtml = optionHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
                    return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                });
                
                html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
                html += `</div>`;
            }
        });
        if (!hasOptions) {
            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>';
    if (answer) {
        html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(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>';
    if (solution) {
        // 处理图片标签
        let solutionHtml = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
            return `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="解析图片" style="object-fit: contain;">`;
        });
        
        // 转义HTML
        solutionHtml = solutionHtml
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        
        // 恢复图片标签
        solutionHtml = solutionHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
            return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
        });
        
        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);
        }
    }
}

// 更新单个录入题目的选项预览（从各个选项输入框自动拼接成JSON）
function updateAddQuestionOptionsPreview() {
    const previewTextarea = document.getElementById('add-options-preview');
    if (!previewTextarea) return;
    
    const optionsObj = {};
    ['A', 'B', 'C', 'D'].forEach(opt => {
        const input = document.getElementById(`add-option-${opt}`);
        if (input && input.value.trim()) {
            optionsObj[opt] = input.value.trim();
        }
    });
    
    previewTextarea.value = JSON.stringify(optionsObj, null, 2);
}

// 从选项预览框同步回各个选项输入框（单个录入题目）
function syncAddQuestionOptionsFromPreview() {
    const previewTextarea = document.getElementById('add-options-preview');
    if (!previewTextarea) return;
    
    try {
        const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const input = document.getElementById(`add-option-${opt}`);
            if (input) {
                input.value = optionsObj[opt] || '';
            }
        });
    } catch (error) {
        console.warn('选项预览 JSON 格式错误:', error);
    }
}

function hideAddQuestionModal() {
    document.getElementById('add-question-modal').classList.add('hidden');
    currentAddQuestionKpCode = null;
    currentAddQuestionKpName = null;
}

// ==================== 查重检测相关函数 ====================

// 单独录题的查重检测
async function checkDuplicateForAddQuestion() {
    const stem = document.getElementById('add-question-stem').value.trim();
    
    if (!stem) {
        if (window.customAlert) {
            window.customAlert('请先填写题干内容');
        } else {
            alert('请先填写题干内容');
        }
        return;
    }
    
    // 构建查重请求数据
    const checkData = {
        stem: stem,
        answer: document.getElementById('add-question-answer').value.trim(),
        solution: document.getElementById('add-question-solution').value.trim()
    };
    
    // 处理选项（仅选择题）
    const questionType = document.getElementById('add-question-type').value;
    if (questionType === 'choice') {
        const optionsObj = {};
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const value = document.getElementById(`add-option-${opt}`).value.trim();
            if (value) {
                optionsObj[opt] = value;
            }
        });
        if (Object.keys(optionsObj).length > 0) {
            checkData.options = JSON.stringify(optionsObj);
        }
    }
    
    await performDuplicateCheck(checkData, null);
}

// 批量导入的查重检测
async function checkDuplicateForBatch(index) {
    const questionDiv = document.getElementById(`batch-q-card-${index}`);
    if (!questionDiv) return;
    
    const stem = questionDiv.querySelector('.batch-stem').value.trim();
    if (!stem) {
        if (window.customAlert) {
            window.customAlert('请先填写题干内容');
        } else {
            alert('请先填写题干内容');
        }
        return;
    }
    
    // 构建查重请求数据
    const checkData = {
        stem: stem,
        answer: questionDiv.querySelector('.batch-answer').value.trim(),
        solution: questionDiv.querySelector('.batch-solution').value.trim()
    };
    
    // 处理选项（仅选择题）
    const questionType = questionDiv.querySelector('.batch-question-type').value;
    if (questionType === 'choice') {
        const optionsPreview = questionDiv.querySelector('.batch-options-preview');
        if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
            try {
                checkData.options = optionsPreview.value.trim();
            } catch (e) {
                console.warn('选项JSON解析失败:', e);
            }
        }
    }
    
    await performDuplicateCheck(checkData, questionDiv);
}

// 关闭所有 customAlert 弹窗
function closeAllCustomAlerts() {
    // 查找所有 customAlert 创建的模态框（通过样式特征识别）
    const modals = document.querySelectorAll('div[style*="position:fixed"][style*="z-index:9999"]');
    modals.forEach(modal => {
        // 检查是否是 customAlert 创建的（包含白色背景的 dialog）
        const dialog = modal.querySelector('div[style*="background:white"]');
        if (dialog) {
            document.body.removeChild(modal);
        }
    });
}

// 执行查重检测
async function performDuplicateCheck(checkData, sourceElement) {
    let loadingModal = null;
    try {
        // 显示加载状态
        if (window.customAlert) {
            // 创建 loading 模式的弹窗（不显示按钮）
            loadingModal = document.createElement('div');
            loadingModal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.4);z-index:9999;display:flex;align-items:center;justify-content:center;';
            
            const dialog = document.createElement('div');
            dialog.style.cssText = 'background:white;padding:2rem;border-radius:12px;box-shadow:0 10px 40px rgba(0,0,0,0.2);max-width:400px;text-align:center;';
            
            const msg = document.createElement('div');
            msg.style.cssText = 'margin-bottom:1.5rem;font-size:1rem;color:#333;';
            msg.textContent = '正在检测重复题目...';
            
            dialog.appendChild(msg);
            loadingModal.appendChild(dialog);
            document.body.appendChild(loadingModal);
        }
        
        const response = await fetch('/api/check_duplicate', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(checkData)
        });
        
        const result = await response.json();
        
        // 关闭加载弹窗
        if (loadingModal && loadingModal.parentNode) {
            document.body.removeChild(loadingModal);
            loadingModal = null;
        }
        closeAllCustomAlerts(); // 确保所有弹窗都关闭
        
        if (result.code === -1 && result.result && result.result.repeatIdList && result.result.repeatIdList.length > 0) {
            // 发现重复，显示比对弹窗
            const repeatInfo = result.result.repeatIdList[0];
            await showDuplicateComparison(checkData, repeatInfo, sourceElement);
        } else if (result.code === 0) {
            // 无重复
            if (window.customAlert) {
                window.customAlert('未发现重复题目，可以继续录入');
            } else {
                alert('未发现重复题目，可以继续录入');
            }
        } else {
            throw new Error('查重接口返回异常');
        }
    } catch (error) {
        // 关闭加载弹窗
        if (loadingModal && loadingModal.parentNode) {
            document.body.removeChild(loadingModal);
            loadingModal = null;
        }
        closeAllCustomAlerts(); // 确保所有弹窗都关闭
        
        console.error('查重检测失败:', error);
        if (window.customAlert) {
            window.customAlert('查重检测失败: ' + error.message);
        } else {
            alert('查重检测失败: ' + error.message);
        }
    }
}

// 显示比对弹窗
async function showDuplicateComparison(currentQuestionData, repeatInfo, sourceElement) {
    const modal = document.getElementById('duplicate-comparison-modal');
    const similarityInfo = document.getElementById('duplicate-similarity-info');
    const currentQuestionDiv = document.getElementById('duplicate-current-question');
    const existingQuestionDiv = document.getElementById('duplicate-existing-question');
    
    // 显示相似度信息
    similarityInfo.textContent = repeatInfo.repeatMsg || '发现重复题目';
    
    // 渲染当前录入的题目
    currentQuestionDiv.innerHTML = renderQuestionForComparison(currentQuestionData, sourceElement);
    
    // 查询库中重复的题目
    try {
        const response = await fetch(`/api/question_by_id/${repeatInfo.questionsId}`);
        const result = await response.json();
        
        if (result.success && result.question) {
            existingQuestionDiv.innerHTML = renderQuestionForComparison(result.question, null, true);
        } else {
            existingQuestionDiv.innerHTML = '<p class="text-gray-500">无法加载重复题目详情</p>';
        }
    } catch (error) {
        console.error('加载重复题目失败:', error);
        existingQuestionDiv.innerHTML = '<p class="text-red-500">加载重复题目失败: ' + error.message + '</p>';
    }
    
    // 显示弹窗
    modal.classList.remove('hidden');
    
    // 渲染LaTeX
    setTimeout(() => {
        [currentQuestionDiv, existingQuestionDiv].forEach(container => {
            if (window.renderMathInElement) {
                try {
                    window.renderMathInElement(container, {
                        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 renderQuestionForComparison(questionData, sourceElement, isExisting = false) {
    let html = '';
    
    // 题型
    const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
    const questionType = questionData.question_type || '';
    const typeText = typeMap[questionType] || questionType || '未分类';
    
    html += `<div class="mb-4">
        <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs font-bold">${typeText}</span>
    </div>`;
    
    // 题干
    html += '<div class="mb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
    let stem = '';
    if (isExisting) {
        stem = questionData.stem || '';
    } else if (sourceElement) {
        stem = sourceElement.querySelector('.batch-stem').value;
    } else {
        stem = document.getElementById('add-question-stem').value;
    }
    
    // 处理图片标签
    const imagePlaceholders = [];
    let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
        const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
        imagePlaceholders.push(url);
        return placeholder;
    });
    
    // 转义HTML
    let stemHtml = stemProcessed
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\n/g, '<br>');
    
    // 替换图片占位符
    imagePlaceholders.forEach((url, index) => {
        const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
        const imgTag = `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg" alt="题目图片" style="object-fit: contain;">`;
        stemHtml = stemHtml.replace(placeholder, imgTag);
    });
    
    html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
    html += '</div>';
    
    // 选项（仅选择题）
    if (questionType === 'choice') {
        html += '<div class="mb-4">';
        html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
        
        let options = {};
        if (isExisting) {
            if (questionData.options) {
                try {
                    options = typeof questionData.options === 'string' ? JSON.parse(questionData.options) : questionData.options;
                } catch (e) {
                    options = {};
                }
            }
        } else if (sourceElement) {
            const optionsPreview = sourceElement.querySelector('.batch-options-preview');
            if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
                try {
                    options = JSON.parse(optionsPreview.value.trim());
                } catch (e) {
                    options = {};
                }
            }
        } else {
            ['A', 'B', 'C', 'D'].forEach(opt => {
                const value = document.getElementById(`add-option-${opt}`).value.trim();
                if (value) {
                    options[opt] = value;
                }
            });
        }
        
        Object.entries(options).forEach(([key, value]) => {
            html += `<div class="mb-2">
                <span class="font-semibold text-gray-700">${key}:</span>
                <span class="text-sm text-gray-600 ml-2">${escapeHtml(value)}</span>
            </div>`;
        });
        
        html += '</div>';
    }
    
    // 答案
    html += '<div class="mb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">答案</div>';
    let answer = '';
    if (isExisting) {
        answer = questionData.answer || '';
    } else if (sourceElement) {
        answer = sourceElement.querySelector('.batch-answer').value;
    } else {
        answer = document.getElementById('add-question-answer').value;
    }
    html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer) || '暂无'}</div>`;
    html += '</div>';
    
    // 解析
    html += '<div class="mb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
    let solution = '';
    if (isExisting) {
        solution = questionData.solution || '';
    } else if (sourceElement) {
        solution = sourceElement.querySelector('.batch-solution').value;
    } else {
        solution = document.getElementById('add-question-solution').value;
    }
    
    if (solution) {
        // 处理图片标签
        const solutionImagePlaceholders = [];
        let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
            const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
            solutionImagePlaceholders.push(url);
            return placeholder;
        });
        
        // 转义HTML
        let solutionHtml = solutionProcessed
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\n/g, '<br>');
        
        // 替换图片占位符
        solutionImagePlaceholders.forEach((url, index) => {
            const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
            const imgTag = `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg" alt="解析图片" style="object-fit: contain;">`;
            solutionHtml = solutionHtml.replace(placeholder, imgTag);
        });
        
        html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
    } else {
        html += '<p class="text-sm text-gray-400">暂无解析</p>';
    }
    html += '</div>';
    
    return html;
}

// 关闭比对弹窗
function hideDuplicateComparisonModal() {
    document.getElementById('duplicate-comparison-modal').classList.add('hidden');
}

async function submitAddQuestion() {
    const form = document.getElementById('add-question-form');
    const stem = document.getElementById('add-question-stem').value.trim();
    
    // 验证必填项
    if (!stem) {
        if (window.customAlert) {
            window.customAlert('请填写题干');
        } else {
            alert('请填写题干');
        }
        return;
    }
    
    // 构建提交数据
    const data = {
        stem: stem,
        answer: document.getElementById('add-question-answer').value.trim(),
        solution: document.getElementById('add-question-solution').value.trim(),
        question_type: document.getElementById('add-question-type').value
    };
    
    // 只在有知识点代码时才添加 kp_code
    if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '') {
        data.kp_code = currentAddQuestionKpCode;
    }
    
    // 处理年级（所有题目必填）
    const gradeSelect = document.getElementById('add-question-grade');
    if (gradeSelect) {
        const grade = gradeSelect.value;
        if (!grade) {
            if (window.customAlert) {
                window.customAlert('请选择年级');
            } else {
                alert('请选择年级');
            }
            gradeSelect.focus();
            return;
        }
        data.grade = parseInt(grade);
    }
    
    // 处理难度
    const difficulty = document.getElementById('add-question-difficulty').value;
    if (difficulty) {
        data.difficulty = parseFloat(difficulty);
    }
    
    // 处理选项（仅选择题）
    if (data.question_type === 'choice') {
        const optionsObj = {};
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const value = document.getElementById(`add-option-${opt}`).value.trim();
            if (value) {
                optionsObj[opt] = value;
            }
        });
        if (Object.keys(optionsObj).length > 0) {
            data.options = JSON.stringify(optionsObj);
        }
    }
    
    // 添加创建者
    const userName = localStorage.getItem('user_name');
    if (userName && userName.trim()) {
        data.create_by = userName.trim();
    }
    
    // 提交按钮状态
    const submitBtn = document.querySelector('#add-question-modal button[onclick="submitAddQuestion()"]');
    const originalText = submitBtn.textContent;
    submitBtn.disabled = true;
    submitBtn.textContent = '提交中...';
    
    try {
        const response = await fetch('/create_question', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 调用接口2确认不重复
            if (result.question_id) {
                try {
                    await fetch('/api/confirm_repeat', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({
                            questionId: result.question_id,
                            isRepeat: 0
                        })
                    });
                } catch (error) {
                    console.warn('确认查重结果失败:', error);
                }
            }
            
            if (window.customAlert) {
                window.customAlert('题目创建成功！', () => {
                    // 只在有知识点代码时才刷新题目列表
                    if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
                        loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
                    }
                    hideAddQuestionModal();
                });
            } else {
                alert('题目创建成功！');
                // 只在有知识点代码时才刷新题目列表
                if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
                    loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
                }
                hideAddQuestionModal();
            }
        } else {
            if (window.customAlert) {
                window.customAlert('创建失败: ' + (result.error || '未知错误'));
            } else {
                alert('创建失败: ' + (result.error || '未知错误'));
            }
        }
    } catch (error) {
        console.error('提交失败:', error);
        if (window.customAlert) {
            window.customAlert('提交失败: ' + error.message);
        } else {
            alert('提交失败: ' + error.message);
        }
    } finally {
        submitBtn.disabled = false;
        submitBtn.textContent = originalText;
    }
}

// 难度评价函数
async function evaluateAddQuestionDifficulty() {
    const btn = document.getElementById('add-evaluate-difficulty-btn');
    const difficultySelect = document.getElementById('add-question-difficulty');
    const stem = document.getElementById('add-question-stem').value.trim();
    
    if (!stem) {
        if (window.customAlert) {
            window.customAlert('请先填写题干内容');
        } else {
            alert('请先填写题干内容');
        }
        return;
    }
    
    const requestData = {
        stem: stem,
        answer: document.getElementById('add-question-answer').value.trim(),
        solution: document.getElementById('add-question-solution').value.trim(),
        question_type: document.getElementById('add-question-type').value
    };
    
    // 处理选项
    if (requestData.question_type === 'choice') {
        const optionsObj = {};
        ['A', 'B', 'C', 'D'].forEach(opt => {
            const value = document.getElementById(`add-option-${opt}`).value.trim();
            if (value) {
                optionsObj[opt] = value;
            }
        });
        if (Object.keys(optionsObj).length > 0) {
            requestData.options = optionsObj;
        }
    }
    
    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}`);
        }
        
        const result = await response.json();
        let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
        
        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;
        } else {
            console.error('无法识别难度等级:', result);
            if (window.customAlert) {
                window.customAlert('无法识别返回的难度等级');
            }
        }
    } catch (error) {
        console.error('难度评价失败:', error);
        if (window.customAlert) {
            window.customAlert('难度评价失败: ' + error.message);
        } else {
            alert('难度评价失败: ' + error.message);
        }
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}
</script>
{% endblock %}

