questions.html 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. {% extends "layout.html" %}
  2. {% 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 %}
  3. {% block content %}
  4. {% set audit_only = audit_only|default(false) %}
  5. <div class="mb-6 flex items-center gap-4">
  6. {% if audit_only %}
  7. <a href="/audit_questions" class="text-blue-600 font-medium hover:underline text-sm">← 返回审核题目</a>
  8. {% elif kp_code %}
  9. <a href="/question_management?kp_code={{ kp_code }}" class="text-blue-600 font-medium hover:underline text-sm">← 返回知识点列表</a>
  10. {% elif node_id %}
  11. <a href="/textbook/{{ node_id }}" class="text-blue-600 font-medium hover:underline text-sm">← 返回教材列表</a>
  12. {% else %}
  13. <a href="javascript:history.back()" class="text-blue-600 font-medium hover:underline text-sm">← 返回上一页</a>
  14. {% endif %}
  15. </div>
  16. {% if kp_code %}
  17. <div class="flex items-center gap-2">
  18. <a href="{{ add_question_url }}"
  19. 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">
  20. 录入题目
  21. </a>
  22. <button onclick="showBatchImportModal()"
  23. 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">
  24. 批量导入
  25. </button>
  26. </div>
  27. {% endif %}
  28. </div>
  29. <div class="space-y-4">
  30. {% for q in questions %}
  31. <div class="apple-card p-6 flex items-center justify-between">
  32. <div class="flex-1 pr-8">
  33. <div class="flex items-center space-x-3 mb-2">
  34. <span class="text-xs font-bold uppercase tracking-wider text-gray-400">#{{ q.question_code }}</span>
  35. {% set pk = (q.get('id') or q.get('question_id') or q.get('pk_id') or q.get('qid')) %}
  36. {% if pk %}
  37. <span class="text-xs text-gray-300 font-mono">ID: {{ pk }}</span>
  38. {% endif %}
  39. {% if q.audit_reason == '合格' %}
  40. <span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold">合格</span>
  41. {% elif q.audit_reason == '不合格' %}
  42. <span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold">不合格</span>
  43. {% endif %}
  44. </div>
  45. <p class="text-gray-700 line-clamp-2 math-render">{{ q.stem }}</p>
  46. </div>
  47. <a href="/detail/{{ q.question_code }}" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 shadow-lg shadow-blue-200">去审核</a>
  48. </div>
  49. {% endfor %}
  50. </div>
  51. <!-- 批量导入模态框 -->
  52. <div id="batch-import-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
  53. <div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[95vh] overflow-hidden flex flex-col">
  54. <div class="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 flex items-center justify-between">
  55. <h2 class="text-xl font-bold">批量导入题目</h2>
  56. <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>
  57. </div>
  58. <div class="flex-1 overflow-hidden flex flex-col">
  59. <!-- JSON输入区域 -->
  60. <div class="p-6 border-b border-gray-200">
  61. <label class="block text-sm font-bold text-gray-700 mb-2">粘贴JSON数据(每道题以number字段切分)</label>
  62. <textarea id="batch-json-input"
  63. 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"
  64. placeholder='[{"number": "1", "stem": "...", "options": {"A": "...", "B": "..."}, "answer": "A", "question_type": "选择题", "solution": "..."}, ...]'
  65. oninput="handleBatchJsonInputChange()"></textarea>
  66. <p class="text-xs text-gray-500 mt-2">支持数组格式或单个对象格式,每道题必须包含number字段。粘贴后自动填充到下方表单</p>
  67. </div>
  68. <!-- 题目卡片区域 -->
  69. <div id="batch-preview" class="hidden flex-1 overflow-hidden flex flex-col">
  70. <!-- 题目导航 -->
  71. <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
  72. <div class="flex items-center gap-3">
  73. <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>
  74. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  75. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
  76. </svg>
  77. </button>
  78. <span class="text-sm font-medium text-gray-700">
  79. 第 <span id="current-question-index">1</span> / <span id="total-question-count">0</span> 题
  80. </span>
  81. <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">
  82. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  83. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
  84. </svg>
  85. </button>
  86. </div>
  87. <div class="text-xs text-gray-500">题号: <span id="current-question-number">-</span></div>
  88. </div>
  89. <!-- 题目表单卡片容器 -->
  90. <div class="flex-1 overflow-y-auto p-6 relative">
  91. <div id="questions-list" class="relative"></div>
  92. </div>
  93. </div>
  94. </div>
  95. <!-- LaTeX 实时预览气泡 -->
  96. <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);">
  97. <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white px-4 py-3 flex items-center justify-between">
  98. <span class="text-sm font-bold">题目预览</span>
  99. <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>
  100. </div>
  101. <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;">
  102. <p class="text-sm text-gray-400 text-center">题目预览</p>
  103. </div>
  104. </div>
  105. <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end gap-3">
  106. <button onclick="hideBatchImportModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
  107. <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>
  108. </div>
  109. </div>
  110. </div>
  111. <script>
  112. let parsedQuestions = [];
  113. let currentBatchQuestionIndex = 0;
  114. let batchJsonSyncTimer = null;
  115. let isSyncingBatchFromJson = false;
  116. let currentHierarchyInfo = {
  117. kp_code: '{{ kp_code }}',
  118. chapter: '{{ hierarchy_info.chapter.label if hierarchy_info.chapter else "" }}',
  119. section: '{{ hierarchy_info.section.label if hierarchy_info.section else "" }}',
  120. subsection: '{{ hierarchy_info.subsection.label if hierarchy_info.subsection else "" }}'
  121. };
  122. function showBatchImportModal() {
  123. document.getElementById('batch-import-modal').classList.remove('hidden');
  124. document.getElementById('batch-json-input').focus();
  125. }
  126. function hideBatchImportModal() {
  127. document.getElementById('batch-import-modal').classList.add('hidden');
  128. document.getElementById('batch-json-input').value = '';
  129. document.getElementById('batch-preview').classList.add('hidden');
  130. document.getElementById('batch-submit-btn').classList.add('hidden');
  131. parsedQuestions = [];
  132. currentBatchQuestionIndex = 0;
  133. }
  134. function handleBatchJsonInputChange() {
  135. const jsonInput = document.getElementById('batch-json-input');
  136. const jsonText = jsonInput.value.trim();
  137. if (jsonText) {
  138. try {
  139. JSON.parse(jsonText);
  140. jsonInput.classList.remove('border-red-500');
  141. jsonInput.classList.add('border-gray-300');
  142. // 防抖处理,自动解析并填充
  143. clearTimeout(batchJsonSyncTimer);
  144. batchJsonSyncTimer = setTimeout(() => {
  145. if (!isSyncingBatchFromJson) {
  146. parseBatchJson();
  147. }
  148. }, 800);
  149. } catch (e) {
  150. jsonInput.classList.remove('border-gray-300');
  151. jsonInput.classList.add('border-red-500');
  152. }
  153. }
  154. }
  155. function parseBatchJson() {
  156. const jsonInput = document.getElementById('batch-json-input');
  157. const jsonText = jsonInput.value.trim();
  158. if (!jsonText) {
  159. return;
  160. }
  161. try {
  162. isSyncingBatchFromJson = true;
  163. let data = null;
  164. // 尝试1: 标准JSON数组格式 [ {...}, {...} ]
  165. try {
  166. data = JSON.parse(jsonText);
  167. if (Array.isArray(data)) {
  168. // 成功解析为数组
  169. } else if (typeof data === 'object' && data !== null) {
  170. // 单个对象,转换为数组
  171. data = [data];
  172. } else {
  173. throw new Error('不是有效的JSON对象或数组');
  174. }
  175. } catch (e) {
  176. // 尝试2: NDJSON格式(每行一个JSON对象)
  177. const lines = jsonText.split('\n').filter(line => line.trim());
  178. if (lines.length > 0) {
  179. data = [];
  180. for (let i = 0; i < lines.length; i++) {
  181. const line = lines[i].trim();
  182. if (!line) continue;
  183. try {
  184. const obj = JSON.parse(line);
  185. if (obj && typeof obj === 'object') {
  186. data.push(obj);
  187. }
  188. } catch (lineError) {
  189. console.warn(`第 ${i + 1} 行解析失败:`, lineError);
  190. }
  191. }
  192. if (data.length === 0) {
  193. throw new Error('无法解析任何有效的JSON对象');
  194. }
  195. } else {
  196. throw e;
  197. }
  198. }
  199. // 按number字段切分
  200. const newParsedQuestions = data.filter(q => q && q.number);
  201. if (newParsedQuestions.length === 0) {
  202. return;
  203. }
  204. // 保留当前题号索引(如果当前索引超出范围,则重置为0)
  205. const oldIndex = currentBatchQuestionIndex;
  206. parsedQuestions = newParsedQuestions;
  207. // 如果当前索引超出新数组范围,重置为0;否则保持当前索引
  208. if (oldIndex >= parsedQuestions.length) {
  209. currentBatchQuestionIndex = 0;
  210. } else {
  211. // 保持当前索引,但确保不超过新数组长度
  212. currentBatchQuestionIndex = Math.min(oldIndex, parsedQuestions.length - 1);
  213. }
  214. displayBatchPreview();
  215. } catch (error) {
  216. console.warn('JSON格式错误:', error);
  217. } finally {
  218. isSyncingBatchFromJson = false;
  219. }
  220. }
  221. function switchBatchQuestion(direction) {
  222. const newIndex = currentBatchQuestionIndex + direction;
  223. if (newIndex >= 0 && newIndex < parsedQuestions.length) {
  224. currentBatchQuestionIndex = newIndex;
  225. showBatchQuestion(currentBatchQuestionIndex);
  226. updateBatchNavigation();
  227. }
  228. }
  229. function updateBatchNavigation() {
  230. const prevBtn = document.getElementById('batch-prev-btn');
  231. const nextBtn = document.getElementById('batch-next-btn');
  232. const currentIndexSpan = document.getElementById('current-question-index');
  233. const totalCountSpan = document.getElementById('total-question-count');
  234. const questionNumberSpan = document.getElementById('current-question-number');
  235. if (prevBtn && nextBtn && currentIndexSpan && totalCountSpan) {
  236. currentIndexSpan.textContent = currentBatchQuestionIndex + 1;
  237. totalCountSpan.textContent = parsedQuestions.length;
  238. prevBtn.disabled = currentBatchQuestionIndex === 0;
  239. nextBtn.disabled = currentBatchQuestionIndex === parsedQuestions.length - 1;
  240. if (questionNumberSpan && parsedQuestions[currentBatchQuestionIndex]) {
  241. questionNumberSpan.textContent = parsedQuestions[currentBatchQuestionIndex].number || currentBatchQuestionIndex + 1;
  242. }
  243. }
  244. }
  245. function showBatchQuestion(index) {
  246. const questionsList = document.getElementById('questions-list');
  247. if (!questionsList) return;
  248. // 隐藏所有题目卡片
  249. const allCards = questionsList.querySelectorAll('.batch-question-card');
  250. allCards.forEach(card => {
  251. card.classList.add('hidden');
  252. });
  253. // 显示当前题目卡片
  254. const currentCard = document.getElementById(`batch-q-card-${index}`);
  255. if (currentCard) {
  256. currentCard.classList.remove('hidden');
  257. }
  258. // 更新预览
  259. updateBatchFullPreview();
  260. }
  261. function hideBatchPreviewBubble() {
  262. const bubble = document.getElementById('batch-latex-preview-bubble');
  263. if (bubble) {
  264. bubble.classList.add('hidden');
  265. }
  266. }
  267. function updateBatchFullPreview() {
  268. const previewContent = document.getElementById('batch-latex-preview-content');
  269. if (!previewContent) return;
  270. const bubble = document.getElementById('batch-latex-preview-bubble');
  271. if (!bubble) return;
  272. // 获取当前显示的题目卡片
  273. const currentCard = document.getElementById(`batch-q-card-${currentBatchQuestionIndex}`);
  274. if (!currentCard) return;
  275. // 收集当前题目的所有数据
  276. const stemTextarea = currentCard.querySelector('.batch-stem');
  277. const answerInput = currentCard.querySelector('.batch-answer');
  278. const solutionTextarea = currentCard.querySelector('.batch-solution');
  279. const optionsPreview = currentCard.querySelector('.batch-options-preview');
  280. const questionTypeSelect = currentCard.querySelector('.batch-question-type');
  281. let html = '<div class="space-y-6">';
  282. // 题干预览
  283. html += '<div class="border-b border-gray-200 pb-4">';
  284. html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
  285. const stem = stemTextarea ? stemTextarea.value : '';
  286. if (stem) {
  287. // 先提取图片标签,替换为占位符
  288. const imagePlaceholders = [];
  289. let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  290. const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
  291. imagePlaceholders.push(url);
  292. return placeholder;
  293. });
  294. // 转义HTML
  295. let stemHtml = stemProcessed
  296. .replace(/&/g, '&amp;')
  297. .replace(/</g, '&lt;')
  298. .replace(/>/g, '&gt;')
  299. .replace(/\n/g, '<br>');
  300. // 将占位符替换为img标签
  301. imagePlaceholders.forEach((url, index) => {
  302. const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
  303. 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;">`;
  304. stemHtml = stemHtml.replace(placeholder, imgTag);
  305. });
  306. html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
  307. } else {
  308. html += '<p class="text-xs text-gray-400">暂无内容</p>';
  309. }
  310. html += '</div>';
  311. // 选项预览(仅选择题)
  312. if (questionTypeSelect && questionTypeSelect.value === 'choice') {
  313. html += '<div class="border-b border-gray-200 pb-4">';
  314. html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
  315. // 直接从选项输入框读取内容,确保图片标签能正确显示
  316. let hasOptions = false;
  317. ['A', 'B', 'C', 'D'].forEach(key => {
  318. const optionInput = currentCard.querySelector(`.batch-option-${key}`);
  319. const optionText = optionInput ? optionInput.value : '';
  320. if (optionText && optionText.trim()) {
  321. hasOptions = true;
  322. html += `<div class="mb-3">`;
  323. html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
  324. // 处理选项文本,支持图片标签
  325. // 先提取图片标签,替换为占位符
  326. const optionImagePlaceholders = [];
  327. let optionProcessed = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  328. const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${optionImagePlaceholders.length}__`;
  329. optionImagePlaceholders.push(url);
  330. return placeholder;
  331. });
  332. // 转义HTML
  333. let optionHtml = optionProcessed
  334. .replace(/&/g, '&amp;')
  335. .replace(/</g, '&lt;')
  336. .replace(/>/g, '&gt;')
  337. .replace(/\n/g, '<br>');
  338. // 将占位符替换为img标签
  339. optionImagePlaceholders.forEach((url, index) => {
  340. const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${index}__`;
  341. 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;">`;
  342. optionHtml = optionHtml.replace(placeholder, imgTag);
  343. });
  344. html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
  345. html += `</div>`;
  346. }
  347. });
  348. if (!hasOptions) {
  349. html += '<p class="text-xs text-gray-400">暂无选项</p>';
  350. }
  351. html += '</div>';
  352. }
  353. // 答案预览
  354. html += '<div class="border-b border-gray-200 pb-4">';
  355. html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
  356. const answer = answerInput ? answerInput.value : '';
  357. if (answer) {
  358. html += `<div class="text-sm font-bold text-blue-600">${answer}</div>`;
  359. } else {
  360. html += '<p class="text-xs text-gray-400">暂无答案</p>';
  361. }
  362. html += '</div>';
  363. // 解析预览
  364. html += '<div>';
  365. html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
  366. const solution = solutionTextarea ? solutionTextarea.value : '';
  367. if (solution) {
  368. // 先提取图片标签,替换为占位符
  369. const solutionImagePlaceholders = [];
  370. let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  371. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
  372. solutionImagePlaceholders.push(url);
  373. return placeholder;
  374. });
  375. // 转义HTML
  376. let solutionHtml = solutionProcessed
  377. .replace(/&/g, '&amp;')
  378. .replace(/</g, '&lt;')
  379. .replace(/>/g, '&gt;')
  380. .replace(/\n/g, '<br>');
  381. // 将占位符替换为img标签
  382. solutionImagePlaceholders.forEach((url, index) => {
  383. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
  384. 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;">`;
  385. solutionHtml = solutionHtml.replace(placeholder, imgTag);
  386. });
  387. html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
  388. } else {
  389. html += '<p class="text-xs text-gray-400">暂无解析</p>';
  390. }
  391. html += '</div>';
  392. html += '</div>';
  393. previewContent.innerHTML = html;
  394. // 渲染LaTeX
  395. if (window.renderMathInElement) {
  396. try {
  397. window.renderMathInElement(previewContent, {
  398. delimiters: [
  399. {left: "$$", right: "$$", display: true},
  400. {left: "$", right: "$", display: false},
  401. {left: "\\(", right: "\\)", display: false},
  402. {left: "\\[", right: "\\]", display: true}
  403. ],
  404. throwOnError: false
  405. });
  406. } catch (e) {
  407. console.warn('LaTeX 渲染失败:', e);
  408. }
  409. }
  410. // 显示预览气泡
  411. bubble.classList.remove('hidden');
  412. }
  413. function displayBatchPreview() {
  414. const previewDiv = document.getElementById('batch-preview');
  415. const questionsList = document.getElementById('questions-list');
  416. previewDiv.classList.remove('hidden');
  417. document.getElementById('batch-submit-btn').classList.remove('hidden');
  418. questionsList.innerHTML = '';
  419. // 创建所有题目卡片(默认隐藏)
  420. parsedQuestions.forEach((q, index) => {
  421. const questionId = `batch-q-card-${index}`;
  422. const questionDiv = document.createElement('div');
  423. questionDiv.className = `batch-question-card apple-card p-6 space-y-4 ${index === 0 ? '' : 'hidden'}`;
  424. questionDiv.id = questionId;
  425. questionDiv.setAttribute('data-index', index);
  426. // 解析选项
  427. let optionsJson = '{}';
  428. let optionA = '', optionB = '', optionC = '', optionD = '';
  429. if (q.options && typeof q.options === 'object') {
  430. optionsJson = JSON.stringify(q.options, null, 2);
  431. optionA = q.options.A || '';
  432. optionB = q.options.B || '';
  433. optionC = q.options.C || '';
  434. optionD = q.options.D || '';
  435. }
  436. // 映射题型
  437. const questionType = mapQuestionType(q.question_type);
  438. questionDiv.innerHTML = `
  439. <div class="border-b border-gray-100 pb-3 mb-3">
  440. <div class="flex items-center gap-2">
  441. <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">题号 ${q.number || index + 1}</span>
  442. </div>
  443. </div>
  444. <!-- 题型和难度选择 -->
  445. <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
  446. <div class="space-y-1">
  447. <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
  448. <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">
  449. <option value="choice" ${questionType === 'choice' ? 'selected' : ''}>选择题</option>
  450. <option value="fill" ${questionType === 'fill' ? 'selected' : ''}>填空题</option>
  451. <option value="answer" ${questionType === 'answer' ? 'selected' : ''}>解答题</option>
  452. </select>
  453. </div>
  454. <div class="space-y-1">
  455. <div class="flex items-center gap-2">
  456. <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
  457. <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})">
  458. <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  459. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
  460. </svg>
  461. 难度评价
  462. </button>
  463. </div>
  464. <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">
  465. <option value="">请选择难度</option>
  466. <option value="0.2" ${q.difficulty == 0.2 || q.difficulty == '0.2' ? 'selected' : ''}>筑基</option>
  467. <option value="0.4" ${q.difficulty == 0.4 || q.difficulty == '0.4' ? 'selected' : ''}>提分</option>
  468. <option value="0.7" ${q.difficulty == 0.7 || q.difficulty == '0.7' ? 'selected' : ''}>培优</option>
  469. </select>
  470. </div>
  471. </div>
  472. <!-- 题干编辑 -->
  473. <div class="space-y-2">
  474. <div class="flex items-center justify-between">
  475. <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
  476. <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>
  477. </div>
  478. <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"
  479. placeholder="请输入题干内容或拖拽图片..."
  480. data-index="${index}"
  481. data-type="stem"
  482. required>${escapeHtml(q.stem || '')}</textarea>
  483. </div>
  484. <!-- 选项编辑 -->
  485. <div class="batch-options-section space-y-2" style="display: ${questionType === 'choice' ? 'block' : 'none'}">
  486. <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
  487. <div class="grid grid-cols-2 gap-3">
  488. <div class="option-item">
  489. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 A</label>
  490. <div class="flex gap-1.5">
  491. <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"
  492. placeholder="输入选项A的内容或拖拽图片..."
  493. data-index="${index}" data-option="A" data-type="option">${escapeHtml(optionA)}</textarea>
  494. <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>
  495. </div>
  496. </div>
  497. <div class="option-item">
  498. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 B</label>
  499. <div class="flex gap-1.5">
  500. <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"
  501. placeholder="输入选项B的内容或拖拽图片..."
  502. data-index="${index}" data-option="B" data-type="option">${escapeHtml(optionB)}</textarea>
  503. <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>
  504. </div>
  505. </div>
  506. <div class="option-item">
  507. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 C</label>
  508. <div class="flex gap-1.5">
  509. <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"
  510. placeholder="输入选项C的内容或拖拽图片..."
  511. data-index="${index}" data-option="C" data-type="option">${escapeHtml(optionC)}</textarea>
  512. <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>
  513. </div>
  514. </div>
  515. <div class="option-item">
  516. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 D</label>
  517. <div class="flex gap-1.5">
  518. <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"
  519. placeholder="输入选项D的内容或拖拽图片..."
  520. data-index="${index}" data-option="D" data-type="option">${escapeHtml(optionD)}</textarea>
  521. <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>
  522. </div>
  523. </div>
  524. </div>
  525. <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
  526. <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式,可直接编辑)</label>
  527. <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"
  528. data-index="${index}"
  529. placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'>${escapeHtml(optionsJson)}</textarea>
  530. </div>
  531. </div>
  532. <!-- 答案 -->
  533. <div class="space-y-1">
  534. <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
  535. <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"
  536. placeholder="例如: A" value="${escapeHtml(q.answer || '')}">
  537. </div>
  538. <!-- 解析 -->
  539. <div class="space-y-2">
  540. <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
  541. <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"
  542. placeholder="请输入解析内容或拖拽图片..."
  543. data-index="${index}"
  544. data-type="solution">${escapeHtml(q.solution || '')}</textarea>
  545. </div>
  546. `;
  547. questionsList.appendChild(questionDiv);
  548. // 设置选项同步逻辑
  549. setupBatchQuestionEvents(index);
  550. });
  551. // 显示当前题并更新导航(不重置索引)
  552. showBatchQuestion(currentBatchQuestionIndex);
  553. updateBatchNavigation();
  554. // 初始化预览
  555. updateBatchFullPreview();
  556. }
  557. function escapeHtml(text) {
  558. if (!text) return '';
  559. const div = document.createElement('div');
  560. div.textContent = text;
  561. return div.innerHTML;
  562. }
  563. function setupBatchQuestionEvents(index) {
  564. // 题型变化时显示/隐藏选项
  565. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  566. if (!questionDiv) return;
  567. const typeSelect = questionDiv.querySelector('.batch-question-type');
  568. const optionsSection = questionDiv.querySelector('.batch-options-section');
  569. typeSelect.addEventListener('change', function() {
  570. if (this.value === 'choice') {
  571. optionsSection.style.display = 'block';
  572. } else {
  573. optionsSection.style.display = 'none';
  574. }
  575. updateBatchFullPreview();
  576. });
  577. // 选项输入框同步到预览
  578. ['A', 'B', 'C', 'D'].forEach(opt => {
  579. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  580. if (input) {
  581. input.addEventListener('input', function() {
  582. updateBatchOptionsPreview(index);
  583. updateBatchFullPreview();
  584. });
  585. }
  586. });
  587. // 预览框同步到输入框
  588. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  589. if (previewTextarea) {
  590. previewTextarea.addEventListener('input', function() {
  591. syncBatchOptionsFromPreview(index);
  592. updateBatchFullPreview();
  593. });
  594. }
  595. // 题干、答案、解析字段变化时更新预览和拖拽上传
  596. const stemTextarea = questionDiv.querySelector('.batch-stem');
  597. if (stemTextarea) {
  598. stemTextarea.addEventListener('input', updateBatchFullPreview);
  599. // 拖拽上传功能
  600. stemTextarea.addEventListener('dragover', function(e) {
  601. e.preventDefault();
  602. e.stopPropagation();
  603. this.classList.add('border-blue-500', 'bg-blue-50');
  604. });
  605. stemTextarea.addEventListener('dragleave', function(e) {
  606. e.preventDefault();
  607. e.stopPropagation();
  608. this.classList.remove('border-blue-500', 'bg-blue-50');
  609. });
  610. stemTextarea.addEventListener('drop', async function(e) {
  611. e.preventDefault();
  612. e.stopPropagation();
  613. this.classList.remove('border-blue-500', 'bg-blue-50');
  614. const files = e.dataTransfer.files;
  615. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  616. await uploadBatchImageFile(files[0], index, 'stem');
  617. }
  618. });
  619. }
  620. const answerInput = questionDiv.querySelector('.batch-answer');
  621. if (answerInput) {
  622. answerInput.addEventListener('input', updateBatchFullPreview);
  623. }
  624. const solutionTextarea = questionDiv.querySelector('.batch-solution');
  625. if (solutionTextarea) {
  626. solutionTextarea.addEventListener('input', updateBatchFullPreview);
  627. // 拖拽上传功能
  628. solutionTextarea.addEventListener('dragover', function(e) {
  629. e.preventDefault();
  630. e.stopPropagation();
  631. this.classList.add('border-blue-500', 'bg-blue-50');
  632. });
  633. solutionTextarea.addEventListener('dragleave', function(e) {
  634. e.preventDefault();
  635. e.stopPropagation();
  636. this.classList.remove('border-blue-500', 'bg-blue-50');
  637. });
  638. solutionTextarea.addEventListener('drop', async function(e) {
  639. e.preventDefault();
  640. e.stopPropagation();
  641. this.classList.remove('border-blue-500', 'bg-blue-50');
  642. const files = e.dataTransfer.files;
  643. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  644. await uploadBatchImageFile(files[0], index, 'solution');
  645. }
  646. });
  647. }
  648. const difficultySelect = questionDiv.querySelector('.batch-difficulty');
  649. if (difficultySelect) {
  650. difficultySelect.addEventListener('change', updateBatchFullPreview);
  651. }
  652. // 图片上传按钮
  653. const uploadStemBtn = questionDiv.querySelector('.batch-upload-stem');
  654. if (uploadStemBtn) {
  655. uploadStemBtn.addEventListener('click', function() {
  656. uploadBatchImage(index, 'stem');
  657. });
  658. }
  659. ['A', 'B', 'C', 'D'].forEach(opt => {
  660. const uploadBtn = questionDiv.querySelector(`.batch-upload-option[data-option="${opt}"]`);
  661. if (uploadBtn) {
  662. uploadBtn.addEventListener('click', function() {
  663. uploadBatchImage(index, 'option', opt);
  664. });
  665. }
  666. });
  667. // 选项拖拽上传功能
  668. ['A', 'B', 'C', 'D'].forEach(opt => {
  669. const optionInput = questionDiv.querySelector(`.batch-option-${opt}`);
  670. if (optionInput) {
  671. optionInput.addEventListener('dragover', function(e) {
  672. e.preventDefault();
  673. e.stopPropagation();
  674. this.classList.add('border-blue-500', 'bg-blue-50');
  675. });
  676. optionInput.addEventListener('dragleave', function(e) {
  677. e.preventDefault();
  678. e.stopPropagation();
  679. this.classList.remove('border-blue-500', 'bg-blue-50');
  680. });
  681. optionInput.addEventListener('drop', async function(e) {
  682. e.preventDefault();
  683. e.stopPropagation();
  684. this.classList.remove('border-blue-500', 'bg-blue-50');
  685. const files = e.dataTransfer.files;
  686. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  687. await uploadBatchImageFile(files[0], index, 'option', opt);
  688. }
  689. });
  690. }
  691. });
  692. // 移除重复的拖拽代码
  693. const solutionTextareaDuplicate = questionDiv.querySelector('.batch-solution');
  694. if (solutionTextarea) {
  695. solutionTextarea.addEventListener('dragover', function(e) {
  696. e.preventDefault();
  697. e.stopPropagation();
  698. this.classList.add('border-blue-500', 'bg-blue-50');
  699. });
  700. solutionTextarea.addEventListener('dragleave', function(e) {
  701. e.preventDefault();
  702. e.stopPropagation();
  703. this.classList.remove('border-blue-500', 'bg-blue-50');
  704. });
  705. solutionTextarea.addEventListener('drop', async function(e) {
  706. e.preventDefault();
  707. e.stopPropagation();
  708. this.classList.remove('border-blue-500', 'bg-blue-50');
  709. const files = e.dataTransfer.files;
  710. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  711. await uploadBatchImageFile(files[0], index, 'solution');
  712. }
  713. });
  714. }
  715. ['A', 'B', 'C', 'D'].forEach(opt => {
  716. const optionInput = questionDiv.querySelector(`.batch-option-${opt}`);
  717. if (optionInput) {
  718. optionInput.addEventListener('dragover', function(e) {
  719. e.preventDefault();
  720. e.stopPropagation();
  721. this.classList.add('border-blue-500', 'bg-blue-50');
  722. });
  723. optionInput.addEventListener('dragleave', function(e) {
  724. e.preventDefault();
  725. e.stopPropagation();
  726. this.classList.remove('border-blue-500', 'bg-blue-50');
  727. });
  728. optionInput.addEventListener('drop', async function(e) {
  729. e.preventDefault();
  730. e.stopPropagation();
  731. this.classList.remove('border-blue-500', 'bg-blue-50');
  732. const files = e.dataTransfer.files;
  733. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  734. await uploadBatchImageFile(files[0], index, 'option', opt);
  735. }
  736. });
  737. }
  738. });
  739. // 粘贴图片功能 - 完全按照录入题目的逻辑
  740. const allInputs = questionDiv.querySelectorAll('textarea, input[type="text"]');
  741. allInputs.forEach(input => {
  742. input.addEventListener('paste', async function(e) {
  743. const clipboardData = e.clipboardData || window.clipboardData;
  744. if (!clipboardData) {
  745. return;
  746. }
  747. // 检查是否有图片数据
  748. const items = clipboardData.items;
  749. if (!items) {
  750. return;
  751. }
  752. for (let i = 0; i < items.length; i++) {
  753. const item = items[i];
  754. // 如果是图片类型
  755. if (item.type.indexOf('image') !== -1) {
  756. e.preventDefault(); // 阻止默认粘贴行为
  757. const file = item.getAsFile();
  758. if (file) {
  759. // 直接上传图片并插入到当前输入框(完全按照录入题目的逻辑)
  760. await uploadBatchImageToInput(file, input, index);
  761. }
  762. break;
  763. }
  764. }
  765. });
  766. });
  767. }
  768. function updateBatchOptionsPreview(index) {
  769. const questionDiv = document.querySelector(`[data-index="${index}"]`);
  770. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  771. const optionsObj = {};
  772. ['A', 'B', 'C', 'D'].forEach(opt => {
  773. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  774. if (input && input.value.trim()) {
  775. optionsObj[opt] = input.value.trim();
  776. }
  777. });
  778. previewTextarea.value = JSON.stringify(optionsObj, null, 2);
  779. }
  780. function syncBatchOptionsFromPreview(index) {
  781. const questionDiv = document.querySelector(`[data-index="${index}"]`);
  782. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  783. try {
  784. const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
  785. ['A', 'B', 'C', 'D'].forEach(opt => {
  786. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  787. if (input) {
  788. input.value = optionsObj[opt] || '';
  789. }
  790. });
  791. } catch (error) {
  792. console.warn('选项预览 JSON 格式错误:', error);
  793. }
  794. }
  795. function uploadBatchImage(index, type, option = null) {
  796. const fileInput = document.createElement('input');
  797. fileInput.type = 'file';
  798. fileInput.accept = 'image/*';
  799. fileInput.style.display = 'none';
  800. fileInput.onchange = async (e) => {
  801. const file = e.target.files[0];
  802. if (!file) return;
  803. if (!file.type.startsWith('image/')) {
  804. if (window.customAlert) {
  805. window.customAlert('请选择图片文件!');
  806. } else {
  807. alert('请选择图片文件!');
  808. }
  809. return;
  810. }
  811. await uploadBatchImageFile(file, index, type, option);
  812. };
  813. document.body.appendChild(fileInput);
  814. fileInput.click();
  815. document.body.removeChild(fileInput);
  816. }
  817. // 通用图片上传函数:上传图片并插入到指定输入框(完全按照录入题目的逻辑)
  818. async function uploadBatchImageToInput(file, inputElement, index) {
  819. if (!inputElement || !file) {
  820. return;
  821. }
  822. // 检查文件类型
  823. if (!file.type.startsWith('image/')) {
  824. if (window.customAlert) {
  825. window.customAlert('请选择图片文件!');
  826. } else {
  827. alert('请选择图片文件!');
  828. }
  829. return;
  830. }
  831. // 显示上传中状态
  832. const originalPlaceholder = inputElement.placeholder || '';
  833. const originalOpacity = inputElement.style.opacity || '1';
  834. inputElement.placeholder = '正在上传图片...';
  835. inputElement.style.opacity = '0.6';
  836. inputElement.disabled = true;
  837. try {
  838. const formData = new FormData();
  839. formData.append('file', file);
  840. const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
  841. method: 'POST',
  842. body: formData
  843. });
  844. if (!response.ok) {
  845. throw new Error(`上传失败: ${response.status} ${response.statusText}`);
  846. }
  847. const result = await response.json();
  848. // 检查返回结果,提取URL
  849. let imageUrl = null;
  850. if (typeof result === 'string') {
  851. imageUrl = result;
  852. } else if (result.url) {
  853. imageUrl = result.url;
  854. } else if (result.data && result.data.url) {
  855. imageUrl = result.data.url;
  856. } else if (result.data && typeof result.data === 'string') {
  857. imageUrl = result.data;
  858. } else {
  859. const resultStr = JSON.stringify(result);
  860. const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
  861. if (urlMatch) {
  862. imageUrl = urlMatch[0];
  863. }
  864. }
  865. if (!imageUrl) {
  866. throw new Error('接口返回格式异常,未找到图片URL。返回结果:' + JSON.stringify(result));
  867. }
  868. // 构建 image 标签
  869. const imageTag = `<image src="${imageUrl}"/>`;
  870. // 获取当前光标位置
  871. const cursorPos = inputElement.selectionStart || inputElement.value.length;
  872. const textBefore = inputElement.value.substring(0, cursorPos);
  873. const textAfter = inputElement.value.substring(cursorPos);
  874. // 插入 image 标签
  875. inputElement.value = textBefore + imageTag + textAfter;
  876. // 设置光标位置到插入内容之后
  877. const newCursorPos = cursorPos + imageTag.length;
  878. if (inputElement.setSelectionRange) {
  879. inputElement.setSelectionRange(newCursorPos, newCursorPos);
  880. }
  881. inputElement.focus();
  882. // 触发input事件,更新预览
  883. inputElement.dispatchEvent(new Event('input', { bubbles: true }));
  884. // 如果是选项输入框,更新选项预览
  885. if (inputElement.classList.contains('batch-option-A') ||
  886. inputElement.classList.contains('batch-option-B') ||
  887. inputElement.classList.contains('batch-option-C') ||
  888. inputElement.classList.contains('batch-option-D')) {
  889. updateBatchOptionsPreview(index);
  890. } else if (inputElement.classList.contains('batch-options-preview')) {
  891. // 如果是在选项预览框中粘贴,需要同步到各个选项输入框
  892. syncBatchOptionsFromPreview(index);
  893. }
  894. // 更新完整预览
  895. updateBatchFullPreview();
  896. } catch (error) {
  897. console.error('上传失败:', error);
  898. if (window.customAlert) {
  899. window.customAlert('图片上传失败: ' + error.message);
  900. } else {
  901. alert('图片上传失败: ' + error.message);
  902. }
  903. } finally {
  904. inputElement.placeholder = originalPlaceholder;
  905. inputElement.style.opacity = originalOpacity;
  906. inputElement.disabled = false;
  907. }
  908. }
  909. // 保留旧函数以兼容拖拽上传
  910. async function uploadBatchImageFile(file, index, type, option) {
  911. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  912. if (!questionDiv) {
  913. questionDiv = document.querySelector(`[data-index="${index}"]`);
  914. }
  915. if (!questionDiv) return;
  916. let targetInput;
  917. if (type === 'stem') {
  918. targetInput = questionDiv.querySelector('.batch-stem');
  919. } else if (type === 'solution') {
  920. targetInput = questionDiv.querySelector('.batch-solution');
  921. } else if (type === 'answer') {
  922. targetInput = questionDiv.querySelector('.batch-answer');
  923. } else if (type === 'options-preview') {
  924. targetInput = questionDiv.querySelector('.batch-options-preview');
  925. } else if (type === 'option' && option) {
  926. targetInput = questionDiv.querySelector(`.batch-option-${option}`);
  927. }
  928. if (!targetInput) return;
  929. // 使用新的通用函数
  930. await uploadBatchImageToInput(file, targetInput, index);
  931. }
  932. async function submitBatchQuestions() {
  933. const questionDivs = document.querySelectorAll('[data-index]');
  934. if (questionDivs.length === 0) {
  935. if (window.customAlert) {
  936. window.customAlert('没有可提交的题目');
  937. } else {
  938. alert('没有可提交的题目');
  939. }
  940. return;
  941. }
  942. const submitBtn = document.getElementById('batch-submit-btn');
  943. submitBtn.disabled = true;
  944. submitBtn.textContent = '提交中...';
  945. let successCount = 0;
  946. let failCount = 0;
  947. const errors = [];
  948. // 获取用户姓名
  949. const userName = localStorage.getItem('user_name') || '';
  950. // 逐个提交题目(从表单中读取数据)
  951. for (let i = 0; i < questionDivs.length; i++) {
  952. const questionDiv = questionDivs[i];
  953. const index = parseInt(questionDiv.getAttribute('data-index'));
  954. try {
  955. // 从表单中读取数据
  956. const stem = questionDiv.querySelector('.batch-stem').value.trim();
  957. const answer = questionDiv.querySelector('.batch-answer').value.trim();
  958. const solution = questionDiv.querySelector('.batch-solution').value.trim();
  959. const questionType = questionDiv.querySelector('.batch-question-type').value;
  960. const difficulty = questionDiv.querySelector('.batch-difficulty').value;
  961. // 验证必填项(仅题干)
  962. if (!stem) {
  963. failCount++;
  964. errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: 缺少必填项(题干)`);
  965. continue;
  966. }
  967. // 构建题目数据
  968. const questionData = {
  969. stem: stem,
  970. answer: answer,
  971. solution: solution,
  972. question_type: questionType,
  973. kp_code: currentHierarchyInfo.kp_code,
  974. chapter: currentHierarchyInfo.chapter,
  975. section: currentHierarchyInfo.section,
  976. subsection: currentHierarchyInfo.subsection
  977. };
  978. // 处理难度(可选)
  979. if (difficulty) {
  980. questionData.difficulty = parseFloat(difficulty);
  981. }
  982. // 处理选项(仅选择题)
  983. if (questionType === 'choice') {
  984. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  985. if (previewTextarea && previewTextarea.value.trim() && previewTextarea.value.trim() !== '{}') {
  986. try {
  987. const optionsObj = JSON.parse(previewTextarea.value.trim());
  988. if (Object.keys(optionsObj).length > 0) {
  989. questionData.options = JSON.stringify(optionsObj);
  990. }
  991. } catch (e) {
  992. // JSON解析失败,从输入框收集
  993. const optionsObj = {};
  994. ['A', 'B', 'C', 'D'].forEach(opt => {
  995. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  996. if (input && input.value.trim()) {
  997. optionsObj[opt] = input.value.trim();
  998. }
  999. });
  1000. if (Object.keys(optionsObj).length > 0) {
  1001. questionData.options = JSON.stringify(optionsObj);
  1002. }
  1003. }
  1004. } else {
  1005. // 预览为空,从输入框收集
  1006. const optionsObj = {};
  1007. ['A', 'B', 'C', 'D'].forEach(opt => {
  1008. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  1009. if (input && input.value.trim()) {
  1010. optionsObj[opt] = input.value.trim();
  1011. }
  1012. });
  1013. if (Object.keys(optionsObj).length > 0) {
  1014. questionData.options = JSON.stringify(optionsObj);
  1015. }
  1016. }
  1017. }
  1018. // 添加创建者
  1019. if (userName) {
  1020. questionData.create_by = userName;
  1021. }
  1022. // 提交到后端
  1023. const response = await fetch('/create_question', {
  1024. method: 'POST',
  1025. headers: {'Content-Type': 'application/json'},
  1026. body: JSON.stringify(questionData)
  1027. });
  1028. const result = await response.json();
  1029. if (result.success) {
  1030. successCount++;
  1031. } else {
  1032. failCount++;
  1033. errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: ${result.error || '未知错误'}`);
  1034. }
  1035. } catch (error) {
  1036. failCount++;
  1037. errors.push(`题号 ${parsedQuestions[index]?.number || i + 1}: ${error.message}`);
  1038. }
  1039. }
  1040. submitBtn.disabled = false;
  1041. submitBtn.textContent = '批量提交';
  1042. // 显示结果(仅显示成功数量)
  1043. const message = `成功导入 ${successCount} 道题`;
  1044. if (window.customAlert) {
  1045. window.customAlert(message, () => {
  1046. if (successCount > 0) {
  1047. // 刷新页面
  1048. window.location.reload();
  1049. }
  1050. });
  1051. } else {
  1052. alert(message);
  1053. if (successCount > 0) {
  1054. window.location.reload();
  1055. }
  1056. }
  1057. }
  1058. // 批量导入的难度评价函数
  1059. async function evaluateBatchDifficulty(index) {
  1060. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  1061. if (!questionDiv) return;
  1062. const btn = questionDiv.querySelector('.batch-evaluate-difficulty-btn');
  1063. const difficultySelect = questionDiv.querySelector('.batch-difficulty');
  1064. if (!btn || !difficultySelect) return;
  1065. // 收集题目信息
  1066. const stemTextarea = questionDiv.querySelector('.batch-stem');
  1067. const answerInput = questionDiv.querySelector('.batch-answer');
  1068. const solutionTextarea = questionDiv.querySelector('.batch-solution');
  1069. const optionsPreview = questionDiv.querySelector('.batch-options-preview');
  1070. const questionTypeSelect = questionDiv.querySelector('.batch-question-type');
  1071. const stem = stemTextarea ? stemTextarea.value.trim() : '';
  1072. if (!stem) {
  1073. if (window.customAlert) {
  1074. window.customAlert('请先填写题干内容');
  1075. } else {
  1076. alert('请先填写题干内容');
  1077. }
  1078. return;
  1079. }
  1080. // 构建请求数据
  1081. const requestData = {
  1082. stem: stem,
  1083. answer: answerInput ? answerInput.value.trim() : '',
  1084. solution: solutionTextarea ? solutionTextarea.value.trim() : '',
  1085. question_type: questionTypeSelect ? questionTypeSelect.value : ''
  1086. };
  1087. // 处理选项
  1088. if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
  1089. try {
  1090. requestData.options = JSON.parse(optionsPreview.value.trim());
  1091. } catch (e) {
  1092. console.warn('选项JSON解析失败:', e);
  1093. }
  1094. }
  1095. // 显示加载状态
  1096. const originalText = btn.innerHTML;
  1097. btn.disabled = true;
  1098. 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>评价中...';
  1099. try {
  1100. const response = await fetch('/api/score', {
  1101. method: 'POST',
  1102. headers: {
  1103. 'Content-Type': 'application/json'
  1104. },
  1105. body: JSON.stringify(requestData)
  1106. });
  1107. if (!response.ok) {
  1108. throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  1109. }
  1110. const result = await response.json();
  1111. // 调试:打印完整返回结果
  1112. console.log('难度评价接口返回:', result);
  1113. // 处理返回的 difficulty_level(优先使用 data.difficulty_level,兼容旧格式)
  1114. let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
  1115. // 映射难度等级到枚举值
  1116. let difficultyValue = '';
  1117. if (difficultyLevel !== undefined && difficultyLevel !== null) {
  1118. const levelStr = String(difficultyLevel).trim();
  1119. // 字符串匹配
  1120. if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
  1121. difficultyValue = '0.2';
  1122. } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
  1123. difficultyValue = '0.4';
  1124. } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
  1125. difficultyValue = '0.7';
  1126. } else {
  1127. // 尝试转换为数字
  1128. const levelNum = parseFloat(levelStr);
  1129. if (!isNaN(levelNum)) {
  1130. if (Math.abs(levelNum - 0.2) < 0.1) {
  1131. difficultyValue = '0.2';
  1132. } else if (Math.abs(levelNum - 0.4) < 0.1) {
  1133. difficultyValue = '0.4';
  1134. } else if (Math.abs(levelNum - 0.7) < 0.1) {
  1135. difficultyValue = '0.7';
  1136. }
  1137. }
  1138. }
  1139. }
  1140. if (difficultyValue) {
  1141. difficultySelect.value = difficultyValue;
  1142. // 触发change事件以更新预览
  1143. difficultySelect.dispatchEvent(new Event('change', { bubbles: true }));
  1144. updateBatchFullPreview();
  1145. // 不显示弹窗,直接完成
  1146. } else {
  1147. // 如果无法识别,打印完整返回结果以便调试
  1148. console.error('无法识别难度等级,完整返回结果:', result);
  1149. if (window.customAlert) {
  1150. window.customAlert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
  1151. } else {
  1152. alert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
  1153. }
  1154. }
  1155. } catch (error) {
  1156. console.error('难度评价失败:', error);
  1157. if (window.customAlert) {
  1158. window.customAlert('难度评价失败: ' + error.message);
  1159. } else {
  1160. alert('难度评价失败: ' + error.message);
  1161. }
  1162. } finally {
  1163. // 恢复按钮
  1164. btn.disabled = false;
  1165. btn.innerHTML = originalText;
  1166. }
  1167. }
  1168. // 映射题型:将中文转换为英文
  1169. function mapQuestionType(type) {
  1170. if (!type) return 'choice';
  1171. const typeMap = {
  1172. '选择题': 'choice',
  1173. '填空题': 'fill',
  1174. '解答题': 'answer',
  1175. 'choice': 'choice',
  1176. 'fill': 'fill',
  1177. 'answer': 'answer'
  1178. };
  1179. return typeMap[type] || 'choice';
  1180. }
  1181. // 移除点击背景关闭功能,只能通过X按钮关闭
  1182. // document.getElementById('batch-import-modal').addEventListener('click', function(e) {
  1183. // if (e.target === this) {
  1184. // hideBatchImportModal();
  1185. // }
  1186. // });
  1187. </script>
  1188. {% endblock %}