{% extends "layout.html" %}

{% block page_title %}编辑题目 - {{ q.question_code }}{% endblock %}

{% block content %}
<div class="mb-8 no-print">
    <a href="/detail/{{ q.question_code }}" class="text-blue-600 font-medium hover:underline">← 取消编辑</a>
</div>

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

<form id="edit-form" class="grid grid-cols-1 gap-4">
    <input type="hidden" name="question_code" value="{{ q.question_code }}">
    <div class="apple-card p-6 space-y-4">
        <div class="border-b border-gray-100 pb-3 mb-3">
            <div class="flex items-center gap-3 flex-wrap">
                <h2 class="text-xl font-bold">编辑题目</h2>
            </div>
            <p class="text-gray-400 text-xs mt-1">修改题目信息，保存后生效</p>
        </div>

        <!-- 题型和难度选择 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <div class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
                <select name="question_type" id="question-type-select" data-original="{{ q.question_type or '' }}" 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="choice" {% if q.question_type == 'choice' %}selected{% endif %}>选择题</option>
                    <option value="fill" {% if q.question_type == 'fill' %}selected{% endif %}>填空题</option>
                    <option value="answer" {% if q.question_type == 'answer' %}selected{% endif %}>解答题</option>
                </select>
            </div>
            <!-- 难度选择 -->
            <div id="difficulty-section" class="space-y-1">
                <label class="text-xs font-bold text-gray-400 uppercase block">难度</label>
                <div class="flex items-center gap-2">
                    <select name="difficulty" id="difficulty-select" data-original="{{ q.difficulty or '' }}" 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>
                        {% set diff = q.difficulty %}
                        {% if diff %}
                            {% set diff_str = diff | string %}
                            {% set diff_float = diff | float if diff is number else 0.0 %}
                        {% else %}
                            {% set diff_str = '' %}
                            {% set diff_float = 0.0 %}
                        {% endif %}
                        <option value="0.2" {% if diff_str == '0.2' or diff == 0.2 or (diff_float >= 0.19 and diff_float <= 0.21) %}selected{% endif %}>筑基</option>
                        <option value="0.4" {% if diff_str == '0.4' or diff == 0.4 or (diff_float >= 0.39 and diff_float <= 0.41) %}selected{% endif %}>提分</option>
                        <option value="0.7" {% if diff_str == '0.7' or diff == 0.7 or (diff_float >= 0.69 and diff_float <= 0.71) %}selected{% endif %}>培优</option>
                    </select>
                    <button type="button" id="evaluate-difficulty-btn" onclick="evaluateDifficulty()" class="btn-apple bg-gradient-to-r from-purple-500 to-indigo-600 text-white hover:from-purple-600 hover:to-indigo-700 text-xs py-1 px-2 shadow-md whitespace-nowrap flex-shrink-0">
                        <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="space-y-2">
            <div class="flex items-center justify-between">
                <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
                <button 
                    type="button" 
                    id="upload-image-btn" 
                    class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit"
                    onclick="triggerStemImageUpload()"
                >
                    上传图片
                </button>
            </div>
            <textarea 
                id="stem-textarea" 
                name="stem" 
                data-original="{{ q.stem | tojson }}"
                required
                class="w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm" 
                placeholder="请输入题干内容或拖拽图片..."
                ondrop="handleStemDrop(event)"
                ondragover="handleStemDragOver(event)"
                ondragleave="handleStemDragLeave(event)"
            >{{ q.stem or '' }}</textarea>
            <div id="upload-status" class="mt-1 text-xs hidden"></div>
        </div>

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

        <!-- 答案 -->
        <div class="space-y-1">
            <label class="text-xs font-bold text-gray-400 uppercase">正确答案 <span class="text-red-500">*</span></label>
            <input type="text" name="answer" id="answer-input" data-original="{{ q.answer | tojson }}" value="{{ q.answer or '' }}" 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" placeholder="例如: A">
        </div>

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

        <!-- 保存按钮 -->
        <div class="pt-4 flex justify-end space-x-2">
            <button type="button" onclick="window.location.href='/detail/{{ q.question_code }}'" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 text-sm py-2 px-4">取消</button>
            <button type="submit" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 shadow-lg shadow-blue-200 text-sm py-2 px-4">保存修改</button>
        </div>
    </div>
</form>

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

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

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

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

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

function setupPreviewForElement(elementId, label) {
    const element = document.getElementById(elementId);
    if (!element) return;
    
    element.addEventListener('focus', function() {
        showPreviewBubble(this, label);
        updatePreviewContent(this.value || '');
    });
    
    element.addEventListener('input', function() {
        if (currentPreviewElement === this) {
            // 防抖处理，避免频繁更新
            clearTimeout(previewUpdateTimer);
            previewUpdateTimer = setTimeout(() => {
                updatePreviewContent(this.value || '');
            }, 300);
        }
    });
    
    element.addEventListener('blur', function() {
        // 不自动隐藏，保持预览气泡显示
    });
}

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

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

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

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

// 从预览区域同步到选项输入框（当用户直接编辑预览时）
function syncOptionsFromPreview() {
    const preview = document.getElementById('options-preview');
    const jsonInput = document.getElementById('options-json-input');
    
    try {
        const jsonStr = preview.value.trim();
        if (!jsonStr || jsonStr === '{}') {
            ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
                const input = document.getElementById(`option-${key}-input`);
                if (input) {
                    input.value = '';
                }
            });
            jsonInput.value = '';
            if (currentPreviewElement === preview) {
                updateOptionsPreviewBubble();
            }
            return;
        }
        
        const optionsObj = JSON.parse(jsonStr);
        jsonInput.value = JSON.stringify(optionsObj);
        
        ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
            const input = document.getElementById(`option-${key}-input`);
            if (input) {
                input.value = optionsObj[key] || '';
            }
        });
        
        if (currentPreviewElement === preview) {
            updateOptionsPreviewBubble();
        }
    } catch (error) {
        console.warn('选项预览 JSON 格式错误:', error);
        if (currentPreviewElement === preview) {
            const content = document.getElementById('latex-preview-content');
            if (content) {
                content.innerHTML = '<p class="text-sm text-red-400 text-center">JSON 格式错误，请检查输入</p>';
            }
        }
    }
}

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

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

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

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

// 通用的选项图片上传函数
async function uploadOptionImageFile(file, optionKey) {
    const optionInput = document.getElementById(`option-${optionKey}-input`);
    const uploadBtn = document.querySelector(`[onclick="uploadOptionImage('${optionKey}')"]`);
    
    let originalText = '';
    if (uploadBtn) {
        originalText = uploadBtn.textContent;
        uploadBtn.disabled = true;
        uploadBtn.textContent = '上传中...';
    }
    
    const originalPlaceholder = optionInput.placeholder;
    optionInput.placeholder = '正在上传图片...';
    optionInput.style.opacity = '0.6';
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        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));
        }
        
        const imageTag = `<image src="${imageUrl}"/>`;
        const cursorPos = optionInput.selectionStart;
        const textBefore = optionInput.value.substring(0, cursorPos);
        const textAfter = optionInput.value.substring(cursorPos);
        
        optionInput.value = textBefore + imageTag + textAfter;
        const newCursorPos = cursorPos + imageTag.length;
        optionInput.setSelectionRange(newCursorPos, newCursorPos);
        optionInput.focus();
        
        updateOptionsPreview();
        
        const optionsPreviewTextarea = document.getElementById('options-preview');
        if (currentPreviewElement === optionsPreviewTextarea) {
            updateOptionsPreviewBubble();
        }
        
    } catch (error) {
        console.error('上传失败:', error);
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        if (uploadBtn) {
            uploadBtn.disabled = false;
            uploadBtn.textContent = originalText;
        }
        optionInput.placeholder = originalPlaceholder;
        optionInput.style.opacity = '1';
    }
}

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

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

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

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

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

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

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

// 题干图片上传函数
async function uploadStemImageFile(file) {
    const stemTextarea = document.getElementById('stem-textarea');
    const statusDiv = document.getElementById('upload-status');
    
    const originalPlaceholder = stemTextarea.placeholder;
    stemTextarea.placeholder = '正在上传图片...';
    stemTextarea.style.opacity = '0.6';
    
    if (statusDiv) {
        statusDiv.classList.remove('hidden');
        statusDiv.textContent = '正在上传图片...';
        statusDiv.className = 'mt-2 text-sm text-blue-600';
    }
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        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));
        }
        
        const imageTag = `<image src="${imageUrl}"/>`;
        const cursorPos = stemTextarea.selectionStart;
        const textBefore = stemTextarea.value.substring(0, cursorPos);
        const textAfter = stemTextarea.value.substring(cursorPos);
        
        stemTextarea.value = textBefore + imageTag + textAfter;
        const newCursorPos = cursorPos + imageTag.length;
        stemTextarea.setSelectionRange(newCursorPos, newCursorPos);
        stemTextarea.focus();
        
        if (currentPreviewElement === stemTextarea) {
            updatePreviewContent(stemTextarea.value);
        }
        
        if (statusDiv) {
            statusDiv.textContent = '图片上传成功！已插入到题干中。';
            statusDiv.className = 'mt-2 text-sm text-green-600';
            setTimeout(() => {
                statusDiv.classList.add('hidden');
            }, 1500);
        }
        
    } catch (error) {
        console.error('上传失败:', error);
        if (statusDiv) {
            statusDiv.textContent = '上传失败: ' + error.message;
            statusDiv.className = 'mt-2 text-sm text-red-600';
        }
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        stemTextarea.placeholder = originalPlaceholder;
        stemTextarea.style.opacity = '1';
    }
}

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

// 通用图片上传函数：上传图片并插入到指定输入框
async function uploadImageToInput(file, inputElement) {
    if (!inputElement || !file) {
        return;
    }
    
    if (!file.type.startsWith('image/')) {
        if (window.customAlert) {
            window.customAlert('请选择图片文件！');
        } else {
            alert('请选择图片文件！');
        }
        return;
    }
    
    const originalPlaceholder = inputElement.placeholder || '';
    const originalOpacity = inputElement.style.opacity || '1';
    inputElement.placeholder = '正在上传图片...';
    inputElement.style.opacity = '0.6';
    inputElement.disabled = true;
    
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
        }
        
        const result = await response.json();
        
        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));
        }
        
        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);
        
        inputElement.value = textBefore + imageTag + textAfter;
        const newCursorPos = cursorPos + imageTag.length;
        if (inputElement.setSelectionRange) {
            inputElement.setSelectionRange(newCursorPos, newCursorPos);
        }
        inputElement.focus();
        
        inputElement.dispatchEvent(new Event('input', { bubbles: true }));
        
        if (currentPreviewElement === inputElement) {
            updatePreviewContent(inputElement.value);
        }
        
        if (inputElement.id && inputElement.id.startsWith('option-')) {
            updateOptionsPreview();
        }
        
    } catch (error) {
        console.error('上传失败:', error);
        if (window.customAlert) {
            window.customAlert('图片上传失败: ' + error.message);
        } else {
            alert('图片上传失败: ' + error.message);
        }
    } finally {
        inputElement.placeholder = originalPlaceholder;
        inputElement.style.opacity = originalOpacity;
        inputElement.disabled = false;
    }
}

// 为所有输入框设置粘贴图片功能
function setupPasteImageForAllInputs() {
    const allInputs = document.querySelectorAll('textarea, input[type="text"]');
    
    allInputs.forEach(input => {
        input.addEventListener('paste', async function(e) {
            const clipboardData = e.clipboardData || window.clipboardData;
            if (!clipboardData) {
                return;
            }
            
            const items = clipboardData.items;
            if (!items) {
                return;
            }
            
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                
                if (item.type.indexOf('image') !== -1) {
                    e.preventDefault();
                    
                    const file = item.getAsFile();
                    if (file) {
                        await uploadImageToInput(file, input);
                    }
                    break;
                }
            }
        });
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化难度选择框的回显
    const difficultySelect = document.getElementById('difficulty-select');
    if (difficultySelect) {
        const originalValue = difficultySelect.getAttribute('data-original');
        if (originalValue) {
            // 处理难度值的各种格式：可能是字符串 "0.2" 或数字 0.2
            let difficultyValue = originalValue;
            // 尝试转换为数字进行比较
            const numValue = parseFloat(originalValue);
            if (!isNaN(numValue)) {
                // 根据数值范围匹配对应的选项值
                if (numValue >= 0.19 && numValue <= 0.21) {
                    difficultySelect.value = '0.2';
                } else if (numValue >= 0.39 && numValue <= 0.41) {
                    difficultySelect.value = '0.4';
                } else if (numValue >= 0.69 && numValue <= 0.71) {
                    difficultySelect.value = '0.7';
                } else if (originalValue === '0.2' || originalValue === 0.2) {
                    difficultySelect.value = '0.2';
                } else if (originalValue === '0.4' || originalValue === 0.4) {
                    difficultySelect.value = '0.4';
                } else if (originalValue === '0.7' || originalValue === 0.7) {
                    difficultySelect.value = '0.7';
                }
            } else if (originalValue === '0.2' || originalValue === '0.4' || originalValue === '0.7') {
                difficultySelect.value = originalValue;
            }
        }
    }
    
    // 解析现有选项JSON并填充到输入框
    const optionsPreview = document.getElementById('options-preview');
    if (optionsPreview && optionsPreview.value && optionsPreview.value.trim() !== '{}') {
        try {
            const optionsObj = JSON.parse(optionsPreview.value);
            ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
                const input = document.getElementById(`option-${key}-input`);
                if (input && optionsObj[key]) {
                    input.value = optionsObj[key];
                }
            });
        } catch (e) {
            console.warn('解析选项JSON失败:', e);
        }
    }
    
    updateOptionsPreview();
    
    // 题型选择变化
    const questionTypeSelect = document.getElementById('question-type-select');
    if (questionTypeSelect) {
        questionTypeSelect.addEventListener('change', function() {
            toggleOptionsVisibility(this.value);
        });
        
        // 初始化时根据题型显示/隐藏选项
        toggleOptionsVisibility(questionTypeSelect.value);
    }
    
    // 设置 LaTeX 实时预览
    setupPreviewForElement('stem-textarea', '题干预览');
    setupPreviewForElement('solution-textarea', '解析预览');
    setupPreviewForElement('option-A-input', '选项 A 预览');
    setupPreviewForElement('option-B-input', '选项 B 预览');
    setupPreviewForElement('option-C-input', '选项 C 预览');
    setupPreviewForElement('option-D-input', '选项 D 预览');
    setupPreviewForElement('answer-input', '正确答案预览');
    
    // 设置选项预览输入框的预览功能
    setupOptionsPreviewTextarea();
    
    // 为所有输入框添加粘贴图片功能
    setupPasteImageForAllInputs();
});

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

// 表单提交
document.getElementById('edit-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    
    // 只发送实际修改过的字段（对比原始值）
    const data = { question_code: formData.get('question_code') };
    
    // 检查字段变化
    const fields = ['stem', 'answer', 'solution', 'question_type', 'difficulty'];
    fields.forEach(field => {
        const input = e.target.querySelector(`[name="${field}"]`);
        if (input) {
            const newValue = input.value || '';
            let oldValue = input.getAttribute('data-original') || '';
            
            // 处理 JSON 字符串
            try {
                if (oldValue && (oldValue.startsWith('{') || oldValue.startsWith('['))) {
                    oldValue = JSON.stringify(JSON.parse(oldValue));
                }
            } catch(e) {
                // 解析失败，保持原值
            }
            
            // 处理difficulty字段：转换为浮点数，保留两位小数
            if (field === 'difficulty' && newValue) {
                const difficultyValue = parseFloat(newValue);
                if (!isNaN(difficultyValue)) {
                    const newDifficulty = round(difficultyValue, 2);
                    const oldDifficulty = oldValue ? parseFloat(oldValue) : null;
                    if (newDifficulty !== oldDifficulty) {
                        data[field] = newDifficulty;
                    }
                }
            } else if (newValue !== oldValue) {
                data[field] = newValue.trim();
            }
        }
    });
    
    // 处理选项
    const previewTextarea = document.getElementById('options-preview');
    const optionsOriginal = previewTextarea ? previewTextarea.getAttribute('data-original') || '' : '';
    
    let optionsJson = '';
    if (previewTextarea && previewTextarea.value.trim() && previewTextarea.value.trim() !== '{}') {
        try {
            const parsed = JSON.parse(previewTextarea.value.trim());
            optionsJson = JSON.stringify(parsed);
        } catch (e) {
            const optionsObj = {};
            ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
                const input = document.getElementById(`option-${key}-input`);
                if (input && input.value && input.value.trim()) {
                    optionsObj[key] = input.value.trim();
                }
            });
            if (Object.keys(optionsObj).length > 0) {
                optionsJson = JSON.stringify(optionsObj);
            }
        }
    } else {
        const optionsObj = {};
        ['A', 'B', 'C', 'D', 'E', 'F'].forEach(key => {
            const input = document.getElementById(`option-${key}-input`);
            if (input && input.value && input.value.trim()) {
                optionsObj[key] = input.value.trim();
            }
        });
        if (Object.keys(optionsObj).length > 0) {
            optionsJson = JSON.stringify(optionsObj);
        }
    }
    
    // 对比选项是否变化
    let optionsOriginalNormalized = optionsOriginal;
    try {
        if (optionsOriginal && (optionsOriginal.startsWith('{') || optionsOriginal.startsWith('['))) {
            optionsOriginalNormalized = JSON.stringify(JSON.parse(optionsOriginal));
        }
    } catch(e) {
        // 解析失败，保持原值
    }
    
    if (optionsJson && optionsJson !== optionsOriginalNormalized) {
        data.options = optionsJson;
    } else if (!optionsJson && optionsOriginalNormalized) {
        // 如果新值为空但原值不为空，也要更新（删除选项）
        data.options = '';
    }
    
    // 验证必填项
    const requiredFields = {
        'stem': '题干',
        'answer': '正确答案',
        'solution': '解析'
    };
    
    const missingFields = [];
    for (const [field, label] of Object.entries(requiredFields)) {
        const input = e.target.querySelector(`[name="${field}"]`);
        if (!input || !input.value || !input.value.trim()) {
            missingFields.push(label);
        }
    }
    
    if (missingFields.length > 0) {
        const message = '请填写以下必填项：' + missingFields.join('、');
        if (window.customAlert) {
            window.customAlert(message);
        } else {
            alert(message);
        }
        return;
    }
    
    // 如果没有变化，提示用户
    if (Object.keys(data).length === 1) {
        if (window.customAlert) {
            window.customAlert('没有检测到任何修改');
        } else {
            alert('没有检测到任何修改');
        }
        return;
    }
    
    const res = await fetch('/update_question', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    
    const result = await res.json();
    if(result.success) {
        if (window.customAlert) {
            window.customAlert('修改成功！', () => {
                window.location.href = '/detail/' + data.question_code;
            });
        } else {
            alert('修改成功！');
            window.location.href = '/detail/' + data.question_code;
        }
    } else {
        if (window.customAlert) {
            window.customAlert('修改失败: ' + result.error);
        } else {
            alert('修改失败: ' + result.error);
        }
    }
});
</script>
{% endblock %}
