{% extends "layout.html" %}

{% block page_title %}{{ kp_name }}{% if audit_only %} <span class="text-orange-500 text-lg font-normal">(未审核)</span>{% endif %} <span class="text-gray-400 text-lg font-normal">({{ questions|length }} 题)</span>{% endblock %}

{% block content %}
{% set audit_only = audit_only|default(false) %}
<div class="mb-6 flex items-center gap-4">
    {% if audit_only %}
    <a href="/audit_questions" class="text-blue-600 font-medium hover:underline text-sm">← 返回审核题目</a>
    {% elif kp_code %}
    <a href="/question_management?kp_code={{ kp_code }}" class="text-blue-600 font-medium hover:underline text-sm">← 返回知识点列表</a>
    {% elif node_id %}
    <a href="/textbook/{{ node_id }}" class="text-blue-600 font-medium hover:underline text-sm">← 返回教材列表</a>
    {% else %}
    <a href="javascript:history.back()" class="text-blue-600 font-medium hover:underline text-sm">← 返回上一页</a>
    {% endif %}
    </div>
    {% if kp_code %}
    <div class="flex items-center gap-2">
        <a href="{{ add_question_url }}" 
           class="btn-apple bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 text-sm py-2 px-4">
            录入题目
        </a>
        <button onclick="showBatchImportModal()" 
                class="btn-apple bg-gradient-to-r from-green-600 to-emerald-600 text-white hover:from-green-700 hover:to-emerald-700 text-sm py-2 px-4">
            批量导入
        </button>
    </div>
    {% endif %}
</div>

<div class="space-y-4">
    {% for q in questions %}
    <div class="apple-card p-6 flex items-center justify-between">
        <div class="flex-1 pr-8">
            <div class="flex items-center space-x-3 mb-2">
                <span class="text-xs font-bold uppercase tracking-wider text-gray-400">#{{ q.question_code }}</span>
                {% set pk = (q.get('id') or q.get('question_id') or q.get('pk_id') or q.get('qid')) %}
                {% if pk %}
                <span class="text-xs text-gray-300 font-mono">ID: {{ pk }}</span>
                {% endif %}
                {% if q.audit_reason == '合格' %}
                <span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold">合格</span>
                {% elif q.audit_reason == '不合格' %}
                <span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold">不合格</span>
                {% endif %}
            </div>
            <p class="text-gray-700 line-clamp-2 math-render">{{ q.stem }}</p>
        </div>
        <a href="/detail/{{ q.question_code }}" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 shadow-lg shadow-blue-200">去审核</a>
    </div>
    {% endfor %}
</div>

<!-- 批量导入模态框 -->
<div id="batch-import-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
    <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>

<script>
let parsedQuestions = [];
let currentBatchQuestionIndex = 0;
let batchJsonSyncTimer = null;
let isSyncingBatchFromJson = false;
let currentHierarchyInfo = {
    kp_code: '{{ kp_code }}',
    chapter: '{{ hierarchy_info.chapter.label if hierarchy_info.chapter else "" }}',
    section: '{{ hierarchy_info.section.label if hierarchy_info.section else "" }}',
    subsection: '{{ hierarchy_info.subsection.label if hierarchy_info.subsection else "" }}'
};

function showBatchImportModal() {
    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 = null;
        
        // 尝试1: 标准JSON数组格式 [ {...}, {...} ]
        try {
            data = JSON.parse(jsonText);
            if (Array.isArray(data)) {
                // 成功解析为数组
            } else if (typeof data === 'object' && data !== null) {
                // 单个对象，转换为数组
                data = [data];
            } else {
                throw new Error('不是有效的JSON对象或数组');
            }
        } catch (e) {
            // 尝试2: NDJSON格式（每行一个JSON对象）
            const lines = jsonText.split('\n').filter(line => line.trim());
            if (lines.length > 0) {
                data = [];
                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i].trim();
                    if (!line) continue;
                    try {
                        const obj = JSON.parse(line);
                        if (obj && typeof obj === 'object') {
                            data.push(obj);
                        }
                    } catch (lineError) {
                        console.warn(`第 ${i + 1} 行解析失败:`, lineError);
                    }
                }
                if (data.length === 0) {
                    throw new Error('无法解析任何有效的JSON对象');
                }
            } else {
                throw e;
            }
        }
        
        // 按number字段切分
        const newParsedQuestions = data.filter(q => q && q.number);
        
        if (newParsedQuestions.length === 0) {
            return;
        }
        
        // 保留当前题号索引（如果当前索引超出范围，则重置为0）
        const oldIndex = currentBatchQuestionIndex;
        parsedQuestions = newParsedQuestions;
        
        // 如果当前索引超出新数组范围，重置为0；否则保持当前索引
        if (oldIndex >= parsedQuestions.length) {
            currentBatchQuestionIndex = 0;
        } else {
            // 保持当前索引，但确保不超过新数组长度
            currentBatchQuestionIndex = Math.min(oldIndex, parsedQuestions.length - 1);
        }
        
        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;
    
    // 隐藏所有题目卡片
    const allCards = questionsList.querySelectorAll('.batch-question-card');
    allCards.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');
    if (!previewContent) return;
    
    const bubble = document.getElementById('batch-latex-preview-bubble');
    if (!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');
    
    let html = '<div class="space-y-6">';
    
    // 题干预览
    html += '<div class="border-b border-gray-200 pb-4">';
    html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
    const stem = stemTextarea ? stemTextarea.value : '';
    if (stem) {
        // 先提取图片标签，替换为占位符
        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">${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">
                    <div class="flex items-center gap-2">
                        <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
                        <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-1 px-2 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>
                    <select name="difficulty" class="batch-difficulty w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
                        <option value="">请选择难度</option>
                        <option value="0.2" ${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>
                </div>
            </div>
            
            <!-- 题干编辑 -->
            <div class="space-y-2">
                <div class="flex items-center justify-between">
                    <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
                    <button type="button" 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">
                <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
                <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>
        `;
        
        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 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);
            });
        }
    });
    
    // 选项拖拽上传功能
    ['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 solutionTextareaDuplicate = questionDiv.querySelector('.batch-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 uploadBatchImageFile(files[0], 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.querySelector(`[data-index="${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.querySelector(`[data-index="${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 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;
    let failCount = 0;
    const errors = [];
    
    // 获取用户姓名
    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();
            const answer = questionDiv.querySelector('.batch-answer').value.trim();
            const solution = questionDiv.querySelector('.batch-solution').value.trim();
            const questionType = questionDiv.querySelector('.batch-question-type').value;
            const difficulty = questionDiv.querySelector('.batch-difficulty').value;
            
            // 验证必填项（仅题干）
            if (!stem) {
                failCount++;
                errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: 缺少必填项（题干）`);
                continue;
            }
            
            // 构建题目数据
            const questionData = {
                stem: stem,
                answer: answer,
                solution: solution,
                question_type: questionType,
                kp_code: currentHierarchyInfo.kp_code,
                chapter: currentHierarchyInfo.chapter,
                section: currentHierarchyInfo.section,
                subsection: currentHierarchyInfo.subsection
            };
            
            // 处理难度（可选）
            if (difficulty) {
                questionData.difficulty = parseFloat(difficulty);
            }
            
            // 处理选项（仅选择题）
            if (questionType === 'choice') {
                const previewTextarea = questionDiv.querySelector('.batch-options-preview');
                if (previewTextarea && previewTextarea.value.trim() && previewTextarea.value.trim() !== '{}') {
                    try {
                        const optionsObj = JSON.parse(previewTextarea.value.trim());
                        if (Object.keys(optionsObj).length > 0) {
                            questionData.options = JSON.stringify(optionsObj);
                        }
                    } catch (e) {
                        // JSON解析失败，从输入框收集
                        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();
                            }
                        });
                        if (Object.keys(optionsObj).length > 0) {
                            questionData.options = JSON.stringify(optionsObj);
                        }
                    }
                } else {
                    // 预览为空，从输入框收集
                    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();
                        }
                    });
                    if (Object.keys(optionsObj).length > 0) {
                        questionData.options = JSON.stringify(optionsObj);
                    }
                }
            }
            
            // 添加创建者
            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++;
            } else {
                failCount++;
                errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: ${result.error || '未知错误'}`);
            }
            
        } catch (error) {
            failCount++;
            errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: ${error.message}`);
        }
    }
    
    submitBtn.disabled = false;
    submitBtn.textContent = '批量提交';
    
    // 显示结果（仅显示成功数量）
    const message = `成功导入 ${successCount} 道题`;
    
    if (window.customAlert) {
        window.customAlert(message, () => {
            if (successCount > 0) {
                // 刷新页面
                window.location.reload();
            }
        });
    } else {
        alert(message);
        if (successCount > 0) {
            window.location.reload();
        }
    }
}

// 批量导入的难度评价函数
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();
        
        // 调试：打印完整返回结果
        console.log('难度评价接口返回:', result);
        
        // 处理返回的 difficulty_level（优先使用 data.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;
                   // 触发change事件以更新预览
                   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;
    }
}

// 映射题型：将中文转换为英文
function mapQuestionType(type) {
    if (!type) return 'choice';
    const typeMap = {
        '选择题': 'choice',
        '填空题': 'fill',
        '解答题': 'answer',
        'choice': 'choice',
        'fill': 'fill',
        'answer': 'answer'
    };
    return typeMap[type] || 'choice';
}

// 移除点击背景关闭功能，只能通过X按钮关闭
// document.getElementById('batch-import-modal').addEventListener('click', function(e) {
//     if (e.target === this) {
//         hideBatchImportModal();
//     }
// });
</script>
{% endblock %}

