question_management.html 173 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776
  1. {% extends "layout.html" %}
  2. {% block page_title %}题目管理{% endblock %}
  3. {% block content %}
  4. {% set is_audit_mode = is_audit_mode|default(false) %}
  5. <div class="flex gap-6">
  6. <!-- 左侧目录索引 -->
  7. <div class="w-96 flex-shrink-0">
  8. <div class="apple-card p-6 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
  9. <div class="flex items-center justify-between mb-6 pb-3 border-b border-gray-200">
  10. <h2 class="text-lg font-bold text-gray-800">{% if is_audit_mode %}未审核知识点{% else %}知识点目录{% endif %}</h2>
  11. </div>
  12. <nav class="space-y-1">
  13. {% macro render_kp_node(node, level) %}
  14. <div class="kp-node-item mb-1" data-kp-code="{{ node.kp_code }}" data-level="{{ level }}">
  15. <div class="flex items-center gap-1 group">
  16. {% if node.children|length > 0 %}
  17. <button
  18. onclick="toggleKpNode('{{ node.kp_code }}'); event.stopPropagation();"
  19. class="w-6 h-6 rounded flex items-center justify-center text-gray-500 hover:text-blue-600 hover:bg-blue-50 transition-all flex-shrink-0 kp-expand-btn"
  20. data-expanded="{% if level == 0 %}true{% else %}false{% endif %}"
  21. data-kp-code="{{ node.kp_code }}">
  22. {% if level == 0 %}
  23. <i class="ri-subtract-line text-sm"></i>
  24. {% else %}
  25. <i class="ri-add-line text-sm"></i>
  26. {% endif %}
  27. </button>
  28. {% else %}
  29. <div class="w-6 h-6 flex items-center justify-center flex-shrink-0">
  30. <div class="w-1.5 h-1.5 rounded-full bg-gray-400"></div>
  31. </div>
  32. {% endif %}
  33. <a href="javascript:void(0)"
  34. onclick="loadQuestionsByKp('{{ node.kp_code }}', '{{ node.name }}', this); return false;"
  35. data-kp-code="{{ node.kp_code }}"
  36. data-kp-name="{{ node.name }}"
  37. class="flex-1 block px-3 py-2 rounded-lg hover:bg-gradient-to-r hover:from-blue-50 hover:to-indigo-50 transition-all border-l-2 border-transparent hover:border-blue-400 kp-link">
  38. <div class="flex items-center gap-2 flex-nowrap">
  39. {% if level == 0 %}
  40. <span class="bg-gradient-to-r from-slate-600 to-slate-700 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">章</span>
  41. {% elif level == 1 %}
  42. <span class="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">节</span>
  43. {% else %}
  44. <span class="bg-gray-200 text-gray-700 px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0">小节</span>
  45. {% endif %}
  46. <span class="text-sm {% if level == 0 %}font-bold text-gray-800{% elif level == 1 %}font-semibold text-gray-800{% else %}font-normal text-gray-600{% endif %} group-hover:text-blue-600 transition-colors flex-1 min-w-0 truncate">{{ node.name }}</span>
  47. {% set total_count = node.total_question_count|default(node.question_count|default(0)) %}
  48. {% if total_count > 0 %}
  49. <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0 ml-1">{{ total_count }}</span>
  50. {% endif %}
  51. </div>
  52. </a>
  53. </div>
  54. {% if node.children|length > 0 %}
  55. <div class="kp-children ml-8 mt-1 {% if level >= 1 %}hidden{% endif %}" id="kp-children-{{ node.kp_code }}" data-level="{{ level }}">
  56. {% for child in node.children %}
  57. {{ render_kp_node(child, level + 1) }}
  58. {% endfor %}
  59. </div>
  60. {% endif %}
  61. </div>
  62. {% endmacro %}
  63. <!-- 其他题目节点 -->
  64. <div class="kp-node-item mb-2 pb-2 border-b border-gray-200" data-kp-code="null" data-level="-1">
  65. <a href="javascript:void(0)"
  66. onclick="loadQuestionsByKp('null', '其他题目', this); return false;"
  67. data-kp-code="null"
  68. data-kp-name="其他题目"
  69. class="flex-1 block px-3 py-2 rounded-lg hover:bg-gradient-to-r hover:from-purple-50 hover:to-pink-50 transition-all border-l-2 border-transparent hover:border-purple-400 kp-link">
  70. <div class="flex items-center gap-2 flex-nowrap">
  71. <span class="bg-gradient-to-r from-purple-500 to-pink-500 text-white px-2 py-0.5 rounded text-xs font-bold shadow-sm flex-shrink-0">其他</span>
  72. <span class="text-sm font-bold text-gray-800 group-hover:text-purple-600 transition-colors flex-1 min-w-0 truncate">其他题目</span>
  73. {% if other_questions_count|default(0) > 0 %}
  74. <span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded-full text-xs font-bold flex-shrink-0 ml-1">{{ other_questions_count }}</span>
  75. {% endif %}
  76. </div>
  77. </a>
  78. </div>
  79. {% if kp_tree %}
  80. {% for root_node in kp_tree %}
  81. {{ render_kp_node(root_node, 0) }}
  82. {% endfor %}
  83. {% else %}
  84. <div class="text-sm text-gray-500 text-center py-8">暂无知识点数据</div>
  85. {% endif %}
  86. </nav>
  87. </div>
  88. </div>
  89. <!-- 右侧题目列表区域 -->
  90. <div class="flex-1">
  91. <!-- 年级筛选栏(仅对"其他题目"显示) -->
  92. <div id="grade-filter-bar" class="mb-4 flex items-center gap-3 hidden">
  93. <span class="text-sm font-semibold text-gray-700">年级筛选:</span>
  94. <div class="flex items-center gap-2">
  95. <button
  96. id="grade-filter-all"
  97. onclick="setGradeFilter(null)"
  98. class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-gray-300 bg-white text-gray-700 hover:bg-gray-50 active">
  99. 全部
  100. </button>
  101. <button
  102. id="grade-filter-1"
  103. onclick="setGradeFilter(1)"
  104. class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-pink-300 bg-white text-pink-700 hover:bg-pink-50">
  105. 小学
  106. </button>
  107. <button
  108. id="grade-filter-2"
  109. onclick="setGradeFilter(2)"
  110. class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-blue-300 bg-white text-blue-700 hover:bg-blue-50">
  111. 初中
  112. </button>
  113. <button
  114. id="grade-filter-3"
  115. onclick="setGradeFilter(3)"
  116. class="grade-filter-btn px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 border-purple-300 bg-white text-purple-700 hover:bg-purple-50">
  117. 高中
  118. </button>
  119. </div>
  120. <span id="grade-filter-indicator" class="text-xs text-gray-500 ml-2 hidden">
  121. <span id="grade-filter-text"></span>
  122. </span>
  123. </div>
  124. <div id="questions-container" class="space-y-4">
  125. <div class="apple-card p-12 text-center">
  126. <div class="text-gray-400 mb-4">
  127. <i class="ri-file-list-line text-6xl"></i>
  128. </div>
  129. <h3 class="text-lg font-bold text-gray-600 mb-2">请选择左侧知识点</h3>
  130. <p class="text-sm text-gray-500 mb-6">点击知识点查看该知识点下的题目</p>
  131. <div class="flex items-center justify-center gap-3">
  132. <button onclick="showAddQuestionModal(null, null)"
  133. class="btn-apple bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 px-6 py-3 shadow-lg shadow-blue-200 flex items-center gap-2">
  134. <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  135. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
  136. </svg>
  137. 录入题目
  138. </button>
  139. <button onclick="showBatchImportModal(null, null)"
  140. class="btn-apple bg-gradient-to-r from-green-600 to-emerald-600 text-white hover:from-green-700 hover:to-emerald-700 px-6 py-3 shadow-lg shadow-green-200 flex items-center gap-2">
  141. <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  142. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
  143. </svg>
  144. 批量导入
  145. </button>
  146. </div>
  147. </div>
  148. </div>
  149. </div>
  150. </div>
  151. <script>
  152. // 知识点树形数据(从服务器端传递)
  153. const kpTreeData = {{ kp_tree|tojson|safe }};
  154. // 当前选中的年级筛选(null表示全部,1=小学,2=初中,3=高中)
  155. let currentGradeFilter = null;
  156. // 设置年级筛选
  157. function setGradeFilter(grade) {
  158. currentGradeFilter = grade;
  159. // 更新按钮样式
  160. document.querySelectorAll('.grade-filter-btn').forEach(btn => {
  161. btn.classList.remove('active', 'bg-pink-100', 'bg-blue-100', 'bg-purple-100', 'border-pink-500', 'border-blue-500', 'border-purple-500');
  162. btn.classList.add('border-gray-300', 'bg-white');
  163. });
  164. // 设置当前选中按钮的样式
  165. const indicator = document.getElementById('grade-filter-indicator');
  166. const indicatorText = document.getElementById('grade-filter-text');
  167. if (grade === null) {
  168. document.getElementById('grade-filter-all').classList.add('active', 'bg-gray-100', 'border-gray-500');
  169. indicator.classList.add('hidden');
  170. } else {
  171. const gradeNames = { 1: '小学', 2: '初中', 3: '高中' };
  172. const gradeColors = {
  173. 1: { bg: 'bg-pink-100', border: 'border-pink-500' },
  174. 2: { bg: 'bg-blue-100', border: 'border-blue-500' },
  175. 3: { bg: 'bg-purple-100', border: 'border-purple-500' }
  176. };
  177. const btn = document.getElementById(`grade-filter-${grade}`);
  178. btn.classList.add('active', gradeColors[grade].bg, gradeColors[grade].border);
  179. btn.classList.remove('border-gray-300', 'bg-white');
  180. indicator.classList.remove('hidden');
  181. indicatorText.textContent = `当前筛选:${gradeNames[grade]}`;
  182. }
  183. // 如果当前有加载的题目列表,且是"其他题目",重新加载(根据年级筛选)
  184. if (currentKpCode && (currentKpCode === 'null' || currentKpCode === '' || currentKpCode === null)) {
  185. // 找到"其他题目"的链接元素,保持选中状态
  186. const otherQuestionsLink = document.querySelector('.kp-link[data-kp-code="null"]');
  187. loadQuestionsByKp(currentKpCode, currentKpName || '其他题目', otherQuestionsLink);
  188. }
  189. }
  190. // 页面加载时初始化年级筛选按钮样式
  191. document.addEventListener('DOMContentLoaded', function() {
  192. // 默认选中"全部"
  193. setGradeFilter(null);
  194. });
  195. // 知识点目录折叠/展开功能
  196. function toggleKpNode(kpCode) {
  197. const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
  198. const expandBtn = document.querySelector(`.kp-expand-btn[data-kp-code="${kpCode}"]`);
  199. if (!childrenContainer || !expandBtn) return;
  200. const isExpanded = expandBtn.getAttribute('data-expanded') === 'true';
  201. const icon = expandBtn.querySelector('i');
  202. if (isExpanded) {
  203. // 折叠
  204. childrenContainer.classList.add('hidden');
  205. expandBtn.setAttribute('data-expanded', 'false');
  206. if (icon) {
  207. icon.className = 'ri-add-line text-sm';
  208. }
  209. } else {
  210. // 展开
  211. childrenContainer.classList.remove('hidden');
  212. expandBtn.setAttribute('data-expanded', 'true');
  213. if (icon) {
  214. icon.className = 'ri-subtract-line text-sm';
  215. }
  216. }
  217. }
  218. // 存储当前知识点的代码和名称(用于构建返回链接)
  219. let currentKpCode = null;
  220. let currentKpName = null;
  221. // 加载指定知识点的题目列表(带页码)
  222. function loadQuestionsByKpPage(kpCode, page) {
  223. // 更新URL参数,但不刷新页面
  224. const url = new URL(window.location);
  225. url.searchParams.set('kp_code', kpCode);
  226. if (page > 1) {
  227. url.searchParams.set('page', page);
  228. } else {
  229. url.searchParams.delete('page');
  230. }
  231. window.history.pushState({}, '', url);
  232. // 重新加载题目列表
  233. const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
  234. const kpName = kpLink ? (kpLink.getAttribute('data-kp-name') || kpCode) : kpCode;
  235. loadQuestionsByKp(kpCode, kpName, kpLink, page);
  236. }
  237. // 加载指定知识点的题目列表
  238. function loadQuestionsByKp(kpCode, kpName, linkElement, page = null) {
  239. const container = document.getElementById('questions-container');
  240. if (!container) return;
  241. // 保存当前知识点信息
  242. currentKpCode = kpCode;
  243. currentKpName = kpName;
  244. // 判断是否是"其他题目"
  245. const isOtherQuestions = kpCode === 'null' || kpCode === '' || kpCode === null;
  246. // 控制年级筛选栏的显示/隐藏
  247. const gradeFilterBar = document.getElementById('grade-filter-bar');
  248. if (gradeFilterBar) {
  249. if (isOtherQuestions) {
  250. // 是"其他题目",显示年级筛选栏
  251. gradeFilterBar.classList.remove('hidden');
  252. } else {
  253. // 不是"其他题目",隐藏年级筛选栏并重置筛选
  254. gradeFilterBar.classList.add('hidden');
  255. // 重置年级筛选
  256. if (currentGradeFilter !== null) {
  257. currentGradeFilter = null;
  258. setGradeFilter(null);
  259. }
  260. }
  261. }
  262. // 更新选中状态
  263. document.querySelectorAll('.kp-link').forEach(link => {
  264. link.classList.remove('bg-blue-50', 'border-blue-400');
  265. });
  266. if (linkElement) {
  267. linkElement.classList.add('bg-blue-50', 'border-blue-400');
  268. }
  269. // 显示加载状态
  270. container.innerHTML = `
  271. <div class="apple-card p-12 text-center">
  272. <div class="text-blue-500 mb-4">
  273. <i class="ri-loader-4-line text-6xl animate-spin"></i>
  274. </div>
  275. <p class="text-gray-600">正在加载题目...</p>
  276. </div>
  277. `;
  278. // 如果没有指定页码,从URL参数获取
  279. if (page === null) {
  280. const urlParams = new URLSearchParams(window.location.search);
  281. const pageParam = urlParams.get('page');
  282. page = pageParam ? parseInt(pageParam) : 1;
  283. }
  284. // 构建请求URL(只有"其他题目"才添加年级筛选参数)
  285. let apiUrl = `/api/questions_by_kp/${encodeURIComponent(kpCode)}`;
  286. const params = [];
  287. // 只有"其他题目"才添加年级筛选参数
  288. if (isOtherQuestions && currentGradeFilter !== null) {
  289. params.push(`grade=${currentGradeFilter}`);
  290. }
  291. if (page > 1) {
  292. params.push(`page=${page}`);
  293. }
  294. if (params.length > 0) {
  295. apiUrl += '?' + params.join('&');
  296. }
  297. // 请求题目列表
  298. fetch(apiUrl)
  299. .then(response => response.json())
  300. .then(data => {
  301. if (!data.success) {
  302. throw new Error(data.error || '加载失败');
  303. }
  304. const questions = data.questions || [];
  305. const kpName = data.kp_name || kpCode;
  306. // 获取统计数据(即使没有题目也要显示)
  307. const stats = data.stats || {};
  308. const auditStats = stats.audit || {pass: 0, fail: 0, pending: 0, pass_rate: 0, audit_rate: 0};
  309. const difficultyStats = stats.difficulty || {jichu: 0, tifen: 0, peiyou: 0, unknown: 0};
  310. // 构建录入题目URL
  311. const addQuestionUrl = `/add_question?kp_code=${encodeURIComponent(kpCode)}`;
  312. // 渲染题目列表
  313. let html = '';
  314. // 如果是"其他题目",只显示按钮,不显示横幅和统计数据
  315. if (kpCode === 'null' || kpCode === '') {
  316. html = `
  317. <div class="mb-6 flex items-center gap-2 flex-wrap">
  318. <button onclick="showAddQuestionModal(null, null)"
  319. class="bg-white text-blue-600 hover:bg-blue-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-blue-200">
  320. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  321. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
  322. </svg>
  323. <span>录入题目</span>
  324. </button>
  325. <button onclick="showBatchImportModal(null, null)"
  326. class="bg-white text-green-600 hover:bg-green-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-green-200">
  327. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  328. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
  329. </svg>
  330. <span>批量导入</span>
  331. </button>
  332. </div>
  333. `;
  334. } else {
  335. // 其他知识点显示完整的横幅和统计数据
  336. html = `
  337. <div class="mb-6">
  338. <div class="bg-gradient-to-r from-gray-800 via-slate-800 to-gray-900 text-white px-6 py-5 rounded-2xl shadow-lg">
  339. <div class="mb-4">
  340. <div class="flex items-center justify-between mb-3">
  341. <div class="flex-1 min-w-0">
  342. <h2 class="text-xl font-bold mb-2 truncate">${kpName}</h2>
  343. <p class="text-sm text-white/80">共 ${stats.total || questions.length} 道题目</p>
  344. </div>
  345. </div>
  346. <div class="flex items-center gap-2 flex-wrap">
  347. <button onclick="showAddQuestionModal('${kpCode}', '${kpName}')"
  348. class="bg-white text-blue-600 hover:bg-blue-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-blue-200">
  349. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  350. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
  351. </svg>
  352. <span>录入题目</span>
  353. </button>
  354. <button onclick="showBatchImportModal('${kpCode}', '${kpName}')"
  355. class="bg-white text-green-600 hover:bg-green-50 px-4 py-2 rounded-lg text-sm font-semibold transition-all flex items-center justify-center gap-2 shadow-md whitespace-nowrap flex-shrink-0 border border-green-200">
  356. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  357. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
  358. </svg>
  359. <span>批量导入</span>
  360. </button>
  361. </div>
  362. </div>
  363. <!-- 统计数据 -->
  364. <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4 pt-4 border-t border-white/20">
  365. <!-- 审核统计 -->
  366. <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
  367. <div class="text-xs text-white/70 mb-1">审核状态</div>
  368. <div class="space-y-1">
  369. <div class="flex items-center justify-between text-xs">
  370. <span class="text-white/90">合格</span>
  371. <span class="font-bold text-green-200">${auditStats.pass || 0}</span>
  372. </div>
  373. <div class="flex items-center justify-between text-xs">
  374. <span class="text-white/90">不合格</span>
  375. <span class="font-bold text-red-200">${auditStats.fail || 0}</span>
  376. </div>
  377. <div class="flex items-center justify-between text-xs">
  378. <span class="text-white/90">待审核</span>
  379. <span class="font-bold text-orange-200">${auditStats.pending || 0}</span>
  380. </div>
  381. </div>
  382. </div>
  383. <!-- 难度统计 -->
  384. <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
  385. <div class="text-xs text-white/70 mb-1">难度分布</div>
  386. <div class="space-y-1">
  387. <div class="flex items-center justify-between text-xs">
  388. <span class="text-white/90">筑基</span>
  389. <span class="font-bold text-green-200">${difficultyStats.jichu || 0}</span>
  390. </div>
  391. <div class="flex items-center justify-between text-xs">
  392. <span class="text-white/90">提分</span>
  393. <span class="font-bold text-yellow-200">${difficultyStats.tifen || 0}</span>
  394. </div>
  395. <div class="flex items-center justify-between text-xs">
  396. <span class="text-white/90">培优</span>
  397. <span class="font-bold text-orange-200">${difficultyStats.peiyou || 0}</span>
  398. </div>
  399. ${(difficultyStats.unknown || 0) > 0 ? `
  400. <div class="flex items-center justify-between text-xs">
  401. <span class="text-white/90">未设置</span>
  402. <span class="font-bold text-gray-300">${difficultyStats.unknown || 0}</span>
  403. </div>
  404. ` : ''}
  405. </div>
  406. </div>
  407. <!-- 审核率 -->
  408. <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
  409. <div class="text-xs text-white/70 mb-1">审核进度</div>
  410. <div class="space-y-2">
  411. <div>
  412. <div class="flex items-center justify-between text-xs mb-1">
  413. <span class="text-white/90">审核率</span>
  414. <span class="font-bold text-white">${auditStats.audit_rate || 0}%</span>
  415. </div>
  416. <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
  417. <div class="h-full bg-blue-300 rounded-full transition-all" style="width: ${auditStats.audit_rate || 0}%"></div>
  418. </div>
  419. </div>
  420. <div>
  421. <div class="flex items-center justify-between text-xs mb-1">
  422. <span class="text-white/90">通过率</span>
  423. <span class="font-bold text-white">${auditStats.pass_rate || 0}%</span>
  424. </div>
  425. <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
  426. <div class="h-full bg-green-300 rounded-full transition-all" style="width: ${auditStats.pass_rate || 0}%"></div>
  427. </div>
  428. </div>
  429. </div>
  430. </div>
  431. <!-- 题型统计 -->
  432. <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
  433. <div class="text-xs text-white/70 mb-1">题型分布</div>
  434. <div class="space-y-1 max-h-20 overflow-y-auto">
  435. ${Object.keys(stats.question_type || {}).length > 0 ? Object.entries(stats.question_type || {}).map(([type, count]) => {
  436. // 题型映射:英文转中文
  437. const typeMap = {
  438. 'choice': '选择题',
  439. 'fill': '填空题',
  440. 'answer': '解答题',
  441. '选择题': '选择题',
  442. '填空题': '填空题',
  443. '解答题': '解答题'
  444. };
  445. const typeName = typeMap[type] || type;
  446. return `
  447. <div class="flex items-center justify-between text-xs">
  448. <span class="text-white/90 truncate">${typeName}</span>
  449. <span class="font-bold text-white ml-2">${count}</span>
  450. </div>
  451. `;
  452. }).join('') : '<div class="text-xs text-white/60">暂无数据</div>'}
  453. </div>
  454. </div>
  455. </div>
  456. </div>
  457. `;
  458. }
  459. html += `<div class="space-y-3 ${kpCode === 'null' || kpCode === '' ? '' : 'mt-6'}">`;
  460. // 如果没有题目,显示提示信息
  461. if (questions.length === 0) {
  462. html += `
  463. <div class="apple-card p-12 text-center">
  464. <div class="text-gray-400 mb-4">
  465. <i class="ri-file-list-line text-6xl"></i>
  466. </div>
  467. <h3 class="text-lg font-bold text-gray-600 mb-2">该知识点下暂无题目</h3>
  468. <p class="text-sm text-gray-500 mb-6">点击上方"录入题目"或"批量导入"按钮开始添加题目</p>
  469. </div>
  470. `;
  471. } else {
  472. // 获取分页信息(从API返回)
  473. const pagination = data.pagination || {};
  474. const currentPage = pagination.page || 1;
  475. const totalPages = pagination.total_pages || 1;
  476. const totalCount = pagination.total_count || questions.length;
  477. const pageSize = pagination.page_size || 20;
  478. const startIndex = (currentPage - 1) * pageSize;
  479. const endIndex = Math.min(startIndex + pageSize, totalCount);
  480. // 有题目时,渲染题目列表
  481. questions.forEach(q => {
  482. // 审核状态
  483. let auditBadge = '';
  484. if (q.audit_reason === '合格') {
  485. auditBadge = '<span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">合格</span>';
  486. } else if (q.audit_reason === '不合格') {
  487. auditBadge = '<span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">不合格</span>';
  488. } else {
  489. auditBadge = '<span class="bg-orange-100 text-orange-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">待审核</span>';
  490. }
  491. // 难度标签
  492. let difficultyBadge = '';
  493. if (q.difficulty !== null && q.difficulty !== undefined) {
  494. const diff = parseFloat(q.difficulty);
  495. if (diff === 0.2 || Math.abs(diff - 0.2) < 0.1) {
  496. difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-green-100 text-green-700 border border-green-200 whitespace-nowrap">筑基</span>';
  497. } else if (diff === 0.4 || Math.abs(diff - 0.4) < 0.1) {
  498. difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-yellow-100 text-yellow-700 border border-yellow-200 whitespace-nowrap">提分</span>';
  499. } else if (diff === 0.7 || Math.abs(diff - 0.7) < 0.1) {
  500. difficultyBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-orange-100 text-orange-700 border border-orange-200 whitespace-nowrap">培优</span>';
  501. }
  502. }
  503. // 题型标签
  504. const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
  505. const questionTypeText = typeMap[q.question_type] || q.question_type || '未分类';
  506. // 年级标签
  507. let gradeBadge = '';
  508. if (q.grade !== null && q.grade !== undefined) {
  509. const grade = parseInt(q.grade);
  510. if (grade === 1) {
  511. gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-pink-100 text-pink-700 border border-pink-200 whitespace-nowrap">小学</span>';
  512. } else if (grade === 2) {
  513. gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-blue-100 text-blue-700 border border-blue-200 whitespace-nowrap">初中</span>';
  514. } else if (grade === 3) {
  515. gradeBadge = '<span class="px-2 py-0.5 rounded-full text-xs font-bold bg-purple-100 text-purple-700 border border-purple-200 whitespace-nowrap">高中</span>';
  516. }
  517. }
  518. // 题干预览(去除HTML标签,只显示文本)
  519. const stemText = (q.stem || '').replace(/<[^>]*>/g, '').substring(0, 150);
  520. html += `
  521. <a href="/detail/${q.question_code}${currentKpCode ? '?kp_code=' + encodeURIComponent(currentKpCode) : ''}"
  522. class="apple-card p-4 block group hover:shadow-lg transition-all border-l-4 border-transparent hover:border-blue-500">
  523. <div class="flex items-center gap-4">
  524. <!-- 左侧:题号 -->
  525. <div class="flex-shrink-0">
  526. <span class="text-xs font-mono text-gray-500 bg-gray-100 px-3 py-1.5 rounded font-semibold">${q.question_code}</span>
  527. </div>
  528. <!-- 中间:题干内容 -->
  529. <div class="flex-1 min-w-0">
  530. <div class="text-sm text-gray-800 group-hover:text-blue-600 transition-colors line-clamp-1">
  531. ${stemText}${stemText.length >= 150 ? '...' : ''}
  532. </div>
  533. </div>
  534. <!-- 右侧:标签和操作 -->
  535. <div class="flex items-center gap-3 flex-shrink-0">
  536. <span class="text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded">${questionTypeText}</span>
  537. ${gradeBadge}
  538. ${difficultyBadge}
  539. ${auditBadge}
  540. <span class="text-xs text-blue-600 font-medium opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">查看详情 →</span>
  541. </div>
  542. </div>
  543. </a>
  544. `;
  545. });
  546. // 添加翻页控件
  547. if (totalPages > 1) {
  548. html += `
  549. <div class="mt-6 flex items-center justify-between">
  550. <div class="text-sm text-gray-600">
  551. 显示第 ${startIndex + 1}-${endIndex} 题,共 ${totalCount} 题
  552. </div>
  553. <div class="flex items-center gap-2">
  554. <button
  555. onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage - 1})"
  556. ${currentPage === 1 ? 'disabled' : ''}
  557. class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
  558. currentPage === 1
  559. ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
  560. : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
  561. }">
  562. <i class="ri-arrow-left-s-line"></i> 上一页
  563. </button>
  564. <div class="flex items-center gap-1">
  565. ${Array.from({length: totalPages}, (_, i) => i + 1).map(page => {
  566. if (page === 1 || page === totalPages || (page >= currentPage - 2 && page <= currentPage + 2)) {
  567. return `
  568. <button
  569. onclick="loadQuestionsByKpPage('${kpCode}', ${page})"
  570. class="px-3 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
  571. page === currentPage
  572. ? 'border-blue-500 bg-blue-500 text-white'
  573. : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
  574. }">
  575. ${page}
  576. </button>
  577. `;
  578. } else if (page === currentPage - 3 || page === currentPage + 3) {
  579. return '<span class="px-2 text-gray-400">...</span>';
  580. }
  581. return '';
  582. }).join('')}
  583. </div>
  584. <button
  585. onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage + 1})"
  586. ${currentPage === totalPages ? 'disabled' : ''}
  587. class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
  588. currentPage === totalPages
  589. ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
  590. : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
  591. }">
  592. 下一页 <i class="ri-arrow-right-s-line"></i>
  593. </button>
  594. </div>
  595. </div>
  596. `;
  597. }
  598. }
  599. html += '</div>';
  600. container.innerHTML = html;
  601. // 渲染数学公式
  602. if (window.renderMathInElement) {
  603. container.querySelectorAll('.math-render').forEach(el => {
  604. try {
  605. window.renderMathInElement(el, {
  606. delimiters: [
  607. {left: "$$", right: "$$", display: true},
  608. {left: "$", right: "$", display: false},
  609. {left: "\\(", right: "\\)", display: false},
  610. {left: "\\[", right: "\\]", display: true}
  611. ],
  612. throwOnError: false
  613. });
  614. } catch (e) {
  615. console.warn('数学公式渲染失败:', e);
  616. }
  617. });
  618. }
  619. })
  620. .catch(error => {
  621. container.innerHTML = `
  622. <div class="apple-card p-12 text-center">
  623. <div class="text-red-400 mb-4">
  624. <i class="ri-error-warning-line text-6xl"></i>
  625. </div>
  626. <h3 class="text-lg font-bold text-gray-600 mb-2">加载失败</h3>
  627. <p class="text-sm text-red-500">${error.message || '未知错误'}</p>
  628. </div>
  629. `;
  630. });
  631. }
  632. // 页面加载时,设置进度条宽度和初始化知识点目录
  633. document.addEventListener('DOMContentLoaded', function() {
  634. // 设置进度条宽度
  635. document.querySelectorAll('.progress-gradient[data-width]').forEach(function(el) {
  636. const width = parseFloat(el.getAttribute('data-width')) || 0;
  637. el.style.width = width + '%';
  638. });
  639. // 初始化知识点目录:默认展开第一级节点
  640. const firstLevelNodes = document.querySelectorAll('.kp-node-item[data-level="0"]');
  641. firstLevelNodes.forEach(node => {
  642. const kpCode = node.getAttribute('data-kp-code');
  643. const expandBtn = node.querySelector('.kp-expand-btn');
  644. if (expandBtn && expandBtn.getAttribute('data-expanded') === 'true') {
  645. const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
  646. if (childrenContainer) {
  647. childrenContainer.classList.remove('hidden');
  648. }
  649. }
  650. });
  651. // 如果 URL 中有锚点(hash),自动滚动到对应知识点
  652. const hash = window.location.hash;
  653. if (hash && hash.startsWith('#kp-')) {
  654. const targetId = hash.substring(1); // 去掉 # 号
  655. const targetElement = document.getElementById(targetId);
  656. if (targetElement) {
  657. // 延迟一下,确保页面完全渲染
  658. setTimeout(() => {
  659. targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
  660. // 高亮一下,让用户知道定位到了
  661. targetElement.style.transition = 'box-shadow 0.3s';
  662. targetElement.style.boxShadow = '0 0 20px rgba(59, 130, 246, 0.5)';
  663. setTimeout(() => {
  664. targetElement.style.boxShadow = '';
  665. }, 2000);
  666. }, 100);
  667. }
  668. }
  669. // 如果 URL 中有 kp_code 参数,自动加载对应知识点的题目列表
  670. const urlParams = new URLSearchParams(window.location.search);
  671. const kpCode = urlParams.get('kp_code');
  672. if (kpCode) {
  673. // 延迟一下,确保页面完全渲染
  674. setTimeout(() => {
  675. // 查找对应的知识点链接
  676. const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
  677. if (kpLink) {
  678. // 获取知识点名称(从链接文本或data属性)
  679. const kpName = kpLink.getAttribute('data-kp-name') || kpLink.textContent.trim() || kpCode;
  680. // 展开父节点(如果需要)
  681. let parent = kpLink.closest('.kp-node-item');
  682. while (parent) {
  683. const parentKpCode = parent.getAttribute('data-kp-code');
  684. if (parentKpCode) {
  685. const expandBtn = parent.querySelector('.kp-expand-btn');
  686. if (expandBtn && expandBtn.getAttribute('data-expanded') === 'false') {
  687. toggleKpNode(parentKpCode);
  688. }
  689. }
  690. parent = parent.parentElement?.closest('.kp-node-item');
  691. }
  692. // 滚动到知识点链接
  693. setTimeout(() => {
  694. kpLink.scrollIntoView({ behavior: 'smooth', block: 'center' });
  695. // 加载题目列表
  696. loadQuestionsByKp(kpCode, kpName, kpLink);
  697. }, 200);
  698. } else {
  699. // 如果找不到链接,直接加载题目(可能是通过API获取知识点名称)
  700. fetch(`/api/questions_by_kp/${encodeURIComponent(kpCode)}`)
  701. .then(response => response.json())
  702. .then(data => {
  703. if (data.success) {
  704. const kpName = data.kp_name || kpCode;
  705. loadQuestionsByKp(kpCode, kpName, null);
  706. }
  707. })
  708. .catch(error => {
  709. console.error('加载知识点信息失败:', error);
  710. // 即使失败也尝试加载题目列表
  711. loadQuestionsByKp(kpCode, kpCode, null);
  712. });
  713. }
  714. }, 300);
  715. }
  716. });
  717. // 显示添加知识点弹窗
  718. function showAddKpModal() {
  719. const modal = document.createElement('div');
  720. modal.id = 'add-kp-modal';
  721. modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
  722. const dialog = document.createElement('div');
  723. dialog.style.cssText = 'background:white;padding:2rem;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,0.3);max-width:500px;width:90%;';
  724. const title = document.createElement('div');
  725. title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
  726. title.textContent = '添加知识点';
  727. // Chapter 选择
  728. const chapterLabel = document.createElement('label');
  729. chapterLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
  730. chapterLabel.textContent = '选择章节 *';
  731. const chapterSelect = document.createElement('select');
  732. chapterSelect.id = 'add-kp-chapter-select';
  733. chapterSelect.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
  734. chapterSelect.innerHTML = '<option value="">请选择章节</option>';
  735. // 填充章节选项(从知识点树形数据中提取)
  736. function extractChaptersFromTree(tree) {
  737. const chapters = [];
  738. tree.forEach(function(node) {
  739. chapters.push({
  740. id: node.kp_code,
  741. label: node.name
  742. });
  743. });
  744. return chapters;
  745. }
  746. const chapters = extractChaptersFromTree(kpTreeData || []);
  747. chapters.forEach(function(chapter) {
  748. const option = document.createElement('option');
  749. option.value = chapter.id;
  750. option.textContent = chapter.label;
  751. chapterSelect.appendChild(option);
  752. });
  753. // 类型选择
  754. const typeLabel = document.createElement('label');
  755. typeLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
  756. typeLabel.textContent = '添加类型 *';
  757. const typeSelect = document.createElement('select');
  758. typeSelect.id = 'add-kp-type-select';
  759. typeSelect.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
  760. typeSelect.innerHTML = '<option value="">请选择类型</option><option value="section">节 (Section)</option><option value="subsection">小节 (Subsection)</option>';
  761. // Section 选择(仅当添加 subsection 时显示)
  762. const sectionLabel = document.createElement('label');
  763. sectionLabel.id = 'add-kp-section-label';
  764. sectionLabel.style.cssText = 'display:none;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
  765. sectionLabel.textContent = '选择节 *';
  766. const sectionSelect = document.createElement('select');
  767. sectionSelect.id = 'add-kp-section-select';
  768. sectionSelect.style.cssText = 'display:none;width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
  769. sectionSelect.innerHTML = '<option value="">请选择节</option>';
  770. // 监听类型变化,更新 section 选择框
  771. typeSelect.addEventListener('change', function() {
  772. if (this.value === 'subsection') {
  773. sectionLabel.style.display = 'block';
  774. sectionSelect.style.display = 'block';
  775. sectionSelect.required = true;
  776. updateSectionOptions(chapterSelect.value);
  777. } else {
  778. sectionLabel.style.display = 'none';
  779. sectionSelect.style.display = 'none';
  780. sectionSelect.required = false;
  781. }
  782. });
  783. // 监听章节变化,更新 section 选项
  784. chapterSelect.addEventListener('change', function() {
  785. if (typeSelect.value === 'subsection') {
  786. updateSectionOptions(this.value);
  787. }
  788. });
  789. function updateSectionOptions(chapterId) {
  790. sectionSelect.innerHTML = '<option value="">请选择节</option>';
  791. if (!chapterId) return;
  792. // 从 kpTreeData 中查找对应章节的子节点(sections)
  793. function findNodeByCode(tree, code) {
  794. for (let node of tree) {
  795. if (node.kp_code === code) {
  796. return node;
  797. }
  798. if (node.children && node.children.length > 0) {
  799. const found = findNodeByCode(node.children, code);
  800. if (found) return found;
  801. }
  802. }
  803. return null;
  804. }
  805. const chapter = findNodeByCode(kpTreeData || [], chapterId);
  806. if (chapter && chapter.children) {
  807. chapter.children.forEach(function(section) {
  808. const option = document.createElement('option');
  809. option.value = section.kp_code;
  810. option.textContent = section.name;
  811. sectionSelect.appendChild(option);
  812. });
  813. }
  814. }
  815. // 名称输入
  816. const nameLabel = document.createElement('label');
  817. nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
  818. nameLabel.textContent = '名称 *';
  819. const nameInput = document.createElement('input');
  820. nameInput.type = 'text';
  821. nameInput.id = 'add-kp-name-input';
  822. nameInput.placeholder = '请输入名称';
  823. nameInput.required = true;
  824. nameInput.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
  825. nameInput.addEventListener('focus', function() {
  826. this.style.borderColor = '#3b82f6';
  827. });
  828. nameInput.addEventListener('blur', function() {
  829. this.style.borderColor = '#e5e7eb';
  830. });
  831. // 按钮容器
  832. const btnContainer = document.createElement('div');
  833. btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
  834. const cancelBtn = document.createElement('button');
  835. cancelBtn.style.cssText = 'background:#f3f4f6;color:#374151;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
  836. cancelBtn.textContent = '取消';
  837. cancelBtn.addEventListener('mouseenter', function() {
  838. this.style.background = '#e5e7eb';
  839. });
  840. cancelBtn.addEventListener('mouseleave', function() {
  841. this.style.background = '#f3f4f6';
  842. });
  843. const confirmBtn = document.createElement('button');
  844. confirmBtn.style.cssText = 'background:#3b82f6;color:white;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
  845. confirmBtn.textContent = '确定';
  846. confirmBtn.addEventListener('mouseenter', function() {
  847. this.style.background = '#2563eb';
  848. });
  849. confirmBtn.addEventListener('mouseleave', function() {
  850. this.style.background = '#3b82f6';
  851. });
  852. const handleCancel = () => {
  853. document.body.removeChild(modal);
  854. };
  855. const handleConfirm = async () => {
  856. const chapterId = chapterSelect.value;
  857. const type = typeSelect.value;
  858. const sectionId = sectionSelect.value;
  859. const name = nameInput.value.trim();
  860. if (!chapterId || !type || !name) {
  861. if (window.customAlert) {
  862. window.customAlert('请填写所有必填项!');
  863. } else {
  864. alert('请填写所有必填项!');
  865. }
  866. return;
  867. }
  868. if (type === 'subsection' && !sectionId) {
  869. if (window.customAlert) {
  870. window.customAlert('添加小节时必须选择节!');
  871. } else {
  872. alert('添加小节时必须选择节!');
  873. }
  874. return;
  875. }
  876. // 禁用按钮
  877. confirmBtn.disabled = true;
  878. confirmBtn.textContent = '添加中...';
  879. try {
  880. const response = await fetch('/add_kp_node', {
  881. method: 'POST',
  882. headers: {'Content-Type': 'application/json'},
  883. body: JSON.stringify({
  884. chapter_id: parseInt(chapterId),
  885. type: type,
  886. section_id: sectionId ? parseInt(sectionId) : null,
  887. name: name
  888. })
  889. });
  890. const result = await response.json();
  891. if (result.success) {
  892. if (window.customAlert) {
  893. window.customAlert('添加成功!页面即将刷新。', () => {
  894. window.location.reload();
  895. });
  896. } else {
  897. alert('添加成功!');
  898. window.location.reload();
  899. }
  900. } else {
  901. if (window.customAlert) {
  902. window.customAlert('添加失败: ' + result.error);
  903. } else {
  904. alert('添加失败: ' + result.error);
  905. }
  906. confirmBtn.disabled = false;
  907. confirmBtn.textContent = '确定';
  908. }
  909. } catch (error) {
  910. console.error('添加失败:', error);
  911. if (window.customAlert) {
  912. window.customAlert('添加失败: ' + error.message);
  913. } else {
  914. alert('添加失败: ' + error.message);
  915. }
  916. confirmBtn.disabled = false;
  917. confirmBtn.textContent = '确定';
  918. }
  919. };
  920. cancelBtn.onclick = handleCancel;
  921. confirmBtn.onclick = handleConfirm;
  922. // 点击背景关闭
  923. modal.onclick = (e) => {
  924. if (e.target === modal) {
  925. handleCancel();
  926. }
  927. };
  928. dialog.appendChild(title);
  929. dialog.appendChild(chapterLabel);
  930. dialog.appendChild(chapterSelect);
  931. dialog.appendChild(typeLabel);
  932. dialog.appendChild(typeSelect);
  933. dialog.appendChild(sectionLabel);
  934. dialog.appendChild(sectionSelect);
  935. dialog.appendChild(nameLabel);
  936. dialog.appendChild(nameInput);
  937. btnContainer.appendChild(cancelBtn);
  938. btnContainer.appendChild(confirmBtn);
  939. dialog.appendChild(btnContainer);
  940. modal.appendChild(dialog);
  941. document.body.appendChild(modal);
  942. // 聚焦第一个输入框
  943. setTimeout(() => chapterSelect.focus(), 100);
  944. }
  945. // 显示编辑知识点名称弹窗
  946. function showEditKpModal(nodeId, nodeType, currentName) {
  947. const modal = document.createElement('div');
  948. modal.id = 'edit-kp-modal';
  949. modal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:10000;display:flex;align-items:center;justify-content:center;';
  950. const dialog = document.createElement('div');
  951. dialog.style.cssText = 'background:white;padding:2rem;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,0.3);max-width:500px;width:90%;';
  952. const title = document.createElement('div');
  953. title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
  954. const typeName = nodeType === 'chapter' ? '章节' : nodeType === 'section' ? '节' : '小节';
  955. title.textContent = '编辑' + typeName + '名称';
  956. // 名称输入
  957. const nameLabel = document.createElement('label');
  958. nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
  959. nameLabel.textContent = '名称 *';
  960. const nameInput = document.createElement('input');
  961. nameInput.type = 'text';
  962. nameInput.id = 'edit-kp-name-input';
  963. nameInput.value = currentName;
  964. nameInput.required = true;
  965. nameInput.style.cssText = 'width:100%;padding:0.75rem;border:2px solid #e5e7eb;border-radius:8px;font-size:1rem;margin-bottom:1.5rem;outline:none;transition:border-color 0.2s;';
  966. nameInput.addEventListener('focus', function() {
  967. this.style.borderColor = '#3b82f6';
  968. });
  969. nameInput.addEventListener('blur', function() {
  970. this.style.borderColor = '#e5e7eb';
  971. });
  972. // 按钮容器
  973. const btnContainer = document.createElement('div');
  974. btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
  975. const cancelBtn = document.createElement('button');
  976. cancelBtn.style.cssText = 'background:#f3f4f6;color:#374151;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
  977. cancelBtn.textContent = '取消';
  978. cancelBtn.addEventListener('mouseenter', function() {
  979. this.style.background = '#e5e7eb';
  980. });
  981. cancelBtn.addEventListener('mouseleave', function() {
  982. this.style.background = '#f3f4f6';
  983. });
  984. const confirmBtn = document.createElement('button');
  985. confirmBtn.style.cssText = 'background:#3b82f6;color:white;border:none;padding:0.75rem 1.5rem;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:600;transition:background 0.2s;';
  986. confirmBtn.textContent = '确定';
  987. confirmBtn.addEventListener('mouseenter', function() {
  988. this.style.background = '#2563eb';
  989. });
  990. confirmBtn.addEventListener('mouseleave', function() {
  991. this.style.background = '#3b82f6';
  992. });
  993. const handleCancel = () => {
  994. document.body.removeChild(modal);
  995. };
  996. const handleConfirm = async () => {
  997. const name = nameInput.value.trim();
  998. if (!name) {
  999. if (window.customAlert) {
  1000. window.customAlert('请输入名称!');
  1001. } else {
  1002. alert('请输入名称!');
  1003. }
  1004. return;
  1005. }
  1006. // 禁用按钮
  1007. confirmBtn.disabled = true;
  1008. confirmBtn.textContent = '保存中...';
  1009. try {
  1010. const response = await fetch('/update_kp_node', {
  1011. method: 'POST',
  1012. headers: {'Content-Type': 'application/json'},
  1013. body: JSON.stringify({
  1014. node_id: nodeId,
  1015. node_type: nodeType,
  1016. name: name
  1017. })
  1018. });
  1019. const result = await response.json();
  1020. if (result.success) {
  1021. // 更新页面上的显示
  1022. const labelElement = document.getElementById(nodeType + '-label-' + nodeId);
  1023. if (labelElement) {
  1024. labelElement.textContent = name;
  1025. }
  1026. if (window.customAlert) {
  1027. window.customAlert('修改成功!', () => {
  1028. document.body.removeChild(modal);
  1029. });
  1030. } else {
  1031. alert('修改成功!');
  1032. document.body.removeChild(modal);
  1033. }
  1034. } else {
  1035. if (window.customAlert) {
  1036. window.customAlert('修改失败: ' + result.error);
  1037. } else {
  1038. alert('修改失败: ' + result.error);
  1039. }
  1040. confirmBtn.disabled = false;
  1041. confirmBtn.textContent = '确定';
  1042. }
  1043. } catch (error) {
  1044. console.error('修改失败:', error);
  1045. if (window.customAlert) {
  1046. window.customAlert('修改失败: ' + error.message);
  1047. } else {
  1048. alert('修改失败: ' + error.message);
  1049. }
  1050. confirmBtn.disabled = false;
  1051. confirmBtn.textContent = '确定';
  1052. }
  1053. };
  1054. cancelBtn.onclick = handleCancel;
  1055. confirmBtn.onclick = handleConfirm;
  1056. // 点击背景关闭
  1057. modal.onclick = (e) => {
  1058. if (e.target === modal) {
  1059. handleCancel();
  1060. }
  1061. };
  1062. // Enter 键确认
  1063. nameInput.onkeypress = function(e) {
  1064. if (e.key === 'Enter') {
  1065. handleConfirm();
  1066. }
  1067. };
  1068. dialog.appendChild(title);
  1069. dialog.appendChild(nameLabel);
  1070. dialog.appendChild(nameInput);
  1071. btnContainer.appendChild(cancelBtn);
  1072. btnContainer.appendChild(confirmBtn);
  1073. dialog.appendChild(btnContainer);
  1074. modal.appendChild(dialog);
  1075. document.body.appendChild(modal);
  1076. // 聚焦输入框并选中所有文本
  1077. setTimeout(() => {
  1078. nameInput.focus();
  1079. nameInput.select();
  1080. }, 100);
  1081. }
  1082. </script>
  1083. <!-- 批量导入模态框 -->
  1084. <div id="batch-import-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
  1085. <div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[95vh] overflow-hidden flex flex-col">
  1086. <div class="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 flex items-center justify-between">
  1087. <h2 class="text-xl font-bold">批量导入题目</h2>
  1088. <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>
  1089. </div>
  1090. <div class="flex-1 overflow-hidden flex flex-col">
  1091. <!-- JSON输入区域 -->
  1092. <div class="p-6 border-b border-gray-200">
  1093. <label class="block text-sm font-bold text-gray-700 mb-2">粘贴JSON数据(每道题以number字段切分)</label>
  1094. <textarea id="batch-json-input"
  1095. 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"
  1096. placeholder='[{"number": "1", "stem": "...", "options": {"A": "...", "B": "..."}, "answer": "A", "question_type": "选择题", "solution": "..."}, ...]'
  1097. oninput="handleBatchJsonInputChange()"></textarea>
  1098. <p class="text-xs text-gray-500 mt-2">支持数组格式或单个对象格式,每道题必须包含number字段。粘贴后自动填充到下方表单</p>
  1099. </div>
  1100. <!-- 题目卡片区域 -->
  1101. <div id="batch-preview" class="hidden flex-1 overflow-hidden flex flex-col">
  1102. <!-- 题目导航 -->
  1103. <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
  1104. <div class="flex items-center gap-3">
  1105. <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>
  1106. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1107. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
  1108. </svg>
  1109. </button>
  1110. <span class="text-sm font-medium text-gray-700">
  1111. 第 <span id="current-question-index">1</span> / <span id="total-question-count">0</span> 题
  1112. </span>
  1113. <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">
  1114. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1115. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
  1116. </svg>
  1117. </button>
  1118. </div>
  1119. <div class="text-xs text-gray-500">题号: <span id="current-question-number">-</span></div>
  1120. </div>
  1121. <!-- 题目表单卡片容器 -->
  1122. <div class="flex-1 overflow-y-auto p-6 relative">
  1123. <div id="questions-list" class="relative"></div>
  1124. </div>
  1125. </div>
  1126. </div>
  1127. <!-- LaTeX 实时预览气泡 -->
  1128. <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);">
  1129. <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white px-4 py-3 flex items-center justify-between">
  1130. <span class="text-sm font-bold">题目预览</span>
  1131. <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>
  1132. </div>
  1133. <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;">
  1134. <p class="text-sm text-gray-400 text-center">题目预览</p>
  1135. </div>
  1136. </div>
  1137. <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end gap-3">
  1138. <button onclick="hideBatchImportModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
  1139. <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>
  1140. </div>
  1141. </div>
  1142. </div>
  1143. <!-- 录入题目模态框 -->
  1144. <div id="add-question-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
  1145. <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
  1146. <div class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-6 py-4 flex items-center justify-between">
  1147. <div>
  1148. <h2 class="text-xl font-bold">录入新题目</h2>
  1149. <div class="mt-1 flex items-center gap-2 text-sm text-white/90">
  1150. <span id="add-question-kp-name" class="font-semibold"></span>
  1151. <span class="text-white/70">|</span>
  1152. <span class="font-mono text-xs bg-white/20 px-2 py-0.5 rounded" id="add-question-kp-code"></span>
  1153. </div>
  1154. </div>
  1155. <button onclick="hideAddQuestionModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
  1156. </div>
  1157. <div class="flex-1 overflow-hidden flex">
  1158. <!-- 左侧表单区域 -->
  1159. <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
  1160. <form id="add-question-form" class="space-y-4">
  1161. <p class="text-gray-400 text-xs mb-4">填写题目信息,保存后自动生成题号并创建新题目</p>
  1162. <!-- 题型和难度选择 -->
  1163. <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
  1164. <div class="space-y-1">
  1165. <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
  1166. <select name="question_type" id="add-question-type" class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
  1167. <option value="choice" selected>选择题</option>
  1168. <option value="fill">填空题</option>
  1169. <option value="answer">解答题</option>
  1170. </select>
  1171. </div>
  1172. <div class="space-y-1">
  1173. <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
  1174. <div class="flex items-center gap-2">
  1175. <select name="difficulty" id="add-question-difficulty" class="flex-1 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
  1176. <option value="">请选择难度</option>
  1177. <option value="0.2">筑基</option>
  1178. <option value="0.4">提分</option>
  1179. <option value="0.7">培优</option>
  1180. </select>
  1181. <button type="button" id="add-evaluate-difficulty-btn" onclick="evaluateAddQuestionDifficulty()" class="btn-apple bg-gradient-to-r from-purple-500 to-indigo-600 text-white hover:from-purple-600 hover:to-indigo-700 text-xs py-2 px-3 shadow-md whitespace-nowrap">
  1182. <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1183. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
  1184. </svg>
  1185. 难度评价
  1186. </button>
  1187. </div>
  1188. </div>
  1189. </div>
  1190. <!-- 年级选择(所有题目必填) -->
  1191. <div id="add-question-grade-section" class="space-y-1">
  1192. <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
  1193. <select name="grade" id="add-question-grade" required class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
  1194. <option value="">请选择年级</option>
  1195. <option value="1">小学</option>
  1196. <option value="2">初中</option>
  1197. <option value="3">高中</option>
  1198. </select>
  1199. </div>
  1200. <!-- 题干编辑 -->
  1201. <div class="space-y-2">
  1202. <div class="flex items-center justify-between">
  1203. <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
  1204. <button type="button" id="add-upload-stem-btn" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit">上传图片</button>
  1205. </div>
  1206. <textarea name="stem" id="add-question-stem" required
  1207. 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"
  1208. placeholder="请输入题干内容或拖拽图片..."></textarea>
  1209. </div>
  1210. <!-- 选项编辑(仅选择题显示) -->
  1211. <div id="add-options-section" class="space-y-2">
  1212. <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
  1213. <div class="grid grid-cols-2 gap-3">
  1214. <div class="space-y-1">
  1215. <label class="text-xs font-medium text-gray-600">选项 A</label>
  1216. <div class="flex gap-1.5">
  1217. <textarea id="add-option-A" class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs" placeholder="输入选项A或拖拽图片..."></textarea>
  1218. <button type="button" onclick="uploadAddQuestionOptionImage('A')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
  1219. </div>
  1220. </div>
  1221. <div class="space-y-1">
  1222. <label class="text-xs font-medium text-gray-600">选项 B</label>
  1223. <div class="flex gap-1.5">
  1224. <textarea id="add-option-B" class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs" placeholder="输入选项B或拖拽图片..."></textarea>
  1225. <button type="button" onclick="uploadAddQuestionOptionImage('B')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
  1226. </div>
  1227. </div>
  1228. <div class="space-y-1">
  1229. <label class="text-xs font-medium text-gray-600">选项 C</label>
  1230. <div class="flex gap-1.5">
  1231. <textarea id="add-option-C" class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs" placeholder="输入选项C或拖拽图片..."></textarea>
  1232. <button type="button" onclick="uploadAddQuestionOptionImage('C')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
  1233. </div>
  1234. </div>
  1235. <div class="space-y-1">
  1236. <label class="text-xs font-medium text-gray-600">选项 D</label>
  1237. <div class="flex gap-1.5">
  1238. <textarea id="add-option-D" class="flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs" placeholder="输入选项D或拖拽图片..."></textarea>
  1239. <button type="button" onclick="uploadAddQuestionOptionImage('D')" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start">上传</button>
  1240. </div>
  1241. </div>
  1242. </div>
  1243. <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
  1244. <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式,可直接编辑)</label>
  1245. <textarea id="add-options-preview" class="w-full text-xs text-gray-700 font-mono bg-white p-2 rounded border border-gray-100 min-h-[80px] focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all resize-y"
  1246. placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'></textarea>
  1247. </div>
  1248. </div>
  1249. <!-- 答案 -->
  1250. <div class="space-y-1">
  1251. <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
  1252. <input type="text" name="answer" id="add-question-answer" class="w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm" placeholder="例如: A">
  1253. </div>
  1254. <!-- 解析 -->
  1255. <div class="space-y-2">
  1256. <div class="flex items-center justify-between">
  1257. <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
  1258. <button type="button" onclick="uploadAddQuestionSolutionImage()" class="btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit">上传图片</button>
  1259. </div>
  1260. <textarea name="solution" id="add-question-solution" class="w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm" placeholder="请输入解析内容或拖拽图片..."></textarea>
  1261. </div>
  1262. </form>
  1263. </div>
  1264. <!-- 右侧预览区域 -->
  1265. <div class="w-[420px] bg-gray-50 border-l border-gray-200 flex flex-col">
  1266. <div id="add-question-preview-content" class="flex-1 p-6 overflow-y-auto bg-gray-50 text-base leading-relaxed">
  1267. <p class="text-sm text-gray-400 text-center">题目预览</p>
  1268. </div>
  1269. </div>
  1270. </div>
  1271. <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-between">
  1272. <button onclick="checkDuplicateForAddQuestion()" class="btn-apple bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 px-4 py-2 flex items-center justify-center gap-2 whitespace-nowrap">
  1273. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1274. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
  1275. </svg>
  1276. <span>查重检测</span>
  1277. </button>
  1278. <div class="flex items-center gap-3">
  1279. <button onclick="hideAddQuestionModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
  1280. <button onclick="submitAddQuestion()" class="btn-apple bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 px-4 py-2">保存并创建</button>
  1281. </div>
  1282. </div>
  1283. </div>
  1284. </div>
  1285. <!-- 题目比对弹窗 -->
  1286. <div id="duplicate-comparison-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10003;">
  1287. <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
  1288. <div class="bg-gradient-to-r from-orange-600 to-red-600 text-white px-6 py-4 flex items-center justify-between">
  1289. <div>
  1290. <h2 class="text-xl font-bold">题目查重比对</h2>
  1291. <p id="duplicate-similarity-info" class="text-sm text-white/90 mt-1"></p>
  1292. </div>
  1293. <button onclick="hideDuplicateComparisonModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
  1294. </div>
  1295. <div class="flex-1 overflow-hidden flex">
  1296. <!-- 左侧:当前录入的题目 -->
  1297. <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
  1298. <div class="mb-4">
  1299. <h3 class="text-lg font-bold text-gray-800 mb-2">当前录入的题目</h3>
  1300. </div>
  1301. <div id="duplicate-current-question" class="space-y-4">
  1302. <!-- 动态填充 -->
  1303. </div>
  1304. </div>
  1305. <!-- 右侧:库中重复的题目 -->
  1306. <div class="flex-1 overflow-y-auto p-6 bg-gray-50">
  1307. <div class="mb-4">
  1308. <h3 class="text-lg font-bold text-gray-800 mb-2">库中重复的题目</h3>
  1309. </div>
  1310. <div id="duplicate-existing-question" class="space-y-4">
  1311. <!-- 动态填充 -->
  1312. </div>
  1313. </div>
  1314. </div>
  1315. <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end">
  1316. <button onclick="hideDuplicateComparisonModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-6 py-2">关闭</button>
  1317. </div>
  1318. </div>
  1319. </div>
  1320. <script>
  1321. // 批量导入相关变量
  1322. let parsedQuestions = [];
  1323. let currentBatchQuestionIndex = 0;
  1324. let batchJsonSyncTimer = null;
  1325. let isSyncingBatchFromJson = false;
  1326. let currentBatchKpCode = null;
  1327. let currentBatchKpName = null;
  1328. function showBatchImportModal(kpCode, kpName) {
  1329. // 处理 'null' 字符串,转换为 null
  1330. if (kpCode === 'null' || kpCode === null) {
  1331. currentBatchKpCode = null;
  1332. currentBatchKpName = '其他题目(未关联知识点)';
  1333. } else {
  1334. currentBatchKpCode = kpCode;
  1335. currentBatchKpName = kpName || '未指定知识点';
  1336. }
  1337. // 保存是否是"其他题目"的状态,用于后续渲染时显示年级选择
  1338. window.isBatchOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
  1339. document.getElementById('batch-import-modal').classList.remove('hidden');
  1340. document.getElementById('batch-json-input').focus();
  1341. }
  1342. function hideBatchImportModal() {
  1343. document.getElementById('batch-import-modal').classList.add('hidden');
  1344. document.getElementById('batch-json-input').value = '';
  1345. document.getElementById('batch-preview').classList.add('hidden');
  1346. document.getElementById('batch-submit-btn').classList.add('hidden');
  1347. parsedQuestions = [];
  1348. currentBatchQuestionIndex = 0;
  1349. }
  1350. function handleBatchJsonInputChange() {
  1351. const jsonInput = document.getElementById('batch-json-input');
  1352. const jsonText = jsonInput.value.trim();
  1353. if (jsonText) {
  1354. try {
  1355. JSON.parse(jsonText);
  1356. jsonInput.classList.remove('border-red-500');
  1357. jsonInput.classList.add('border-gray-300');
  1358. clearTimeout(batchJsonSyncTimer);
  1359. batchJsonSyncTimer = setTimeout(() => {
  1360. if (!isSyncingBatchFromJson) {
  1361. parseBatchJson();
  1362. }
  1363. }, 800);
  1364. } catch (e) {
  1365. jsonInput.classList.remove('border-gray-300');
  1366. jsonInput.classList.add('border-red-500');
  1367. }
  1368. }
  1369. }
  1370. function parseBatchJson() {
  1371. const jsonInput = document.getElementById('batch-json-input');
  1372. const jsonText = jsonInput.value.trim();
  1373. if (!jsonText) return;
  1374. try {
  1375. isSyncingBatchFromJson = true;
  1376. let data = JSON.parse(jsonText);
  1377. if (!Array.isArray(data)) {
  1378. data = [data];
  1379. }
  1380. parsedQuestions = data.filter(q => q && q.number);
  1381. if (parsedQuestions.length === 0) return;
  1382. currentBatchQuestionIndex = 0;
  1383. displayBatchPreview();
  1384. } catch (error) {
  1385. console.warn('JSON格式错误:', error);
  1386. } finally {
  1387. isSyncingBatchFromJson = false;
  1388. }
  1389. }
  1390. function switchBatchQuestion(direction) {
  1391. const newIndex = currentBatchQuestionIndex + direction;
  1392. if (newIndex >= 0 && newIndex < parsedQuestions.length) {
  1393. currentBatchQuestionIndex = newIndex;
  1394. showBatchQuestion(currentBatchQuestionIndex);
  1395. updateBatchNavigation();
  1396. }
  1397. }
  1398. function updateBatchNavigation() {
  1399. const prevBtn = document.getElementById('batch-prev-btn');
  1400. const nextBtn = document.getElementById('batch-next-btn');
  1401. const currentIndexSpan = document.getElementById('current-question-index');
  1402. const totalCountSpan = document.getElementById('total-question-count');
  1403. const questionNumberSpan = document.getElementById('current-question-number');
  1404. if (prevBtn && nextBtn && currentIndexSpan && totalCountSpan) {
  1405. currentIndexSpan.textContent = currentBatchQuestionIndex + 1;
  1406. totalCountSpan.textContent = parsedQuestions.length;
  1407. prevBtn.disabled = currentBatchQuestionIndex === 0;
  1408. nextBtn.disabled = currentBatchQuestionIndex === parsedQuestions.length - 1;
  1409. if (questionNumberSpan && parsedQuestions[currentBatchQuestionIndex]) {
  1410. questionNumberSpan.textContent = parsedQuestions[currentBatchQuestionIndex].number || currentBatchQuestionIndex + 1;
  1411. }
  1412. }
  1413. }
  1414. function showBatchQuestion(index) {
  1415. const questionsList = document.getElementById('questions-list');
  1416. if (!questionsList) return;
  1417. questionsList.querySelectorAll('.batch-question-card').forEach(card => card.classList.add('hidden'));
  1418. const currentCard = document.getElementById(`batch-q-card-${index}`);
  1419. if (currentCard) currentCard.classList.remove('hidden');
  1420. updateBatchFullPreview();
  1421. }
  1422. function hideBatchPreviewBubble() {
  1423. const bubble = document.getElementById('batch-latex-preview-bubble');
  1424. if (bubble) bubble.classList.add('hidden');
  1425. }
  1426. function updateBatchFullPreview() {
  1427. const previewContent = document.getElementById('batch-latex-preview-content');
  1428. const bubble = document.getElementById('batch-latex-preview-bubble');
  1429. if (!previewContent || !bubble) return;
  1430. // 获取当前显示的题目卡片
  1431. const currentCard = document.getElementById(`batch-q-card-${currentBatchQuestionIndex}`);
  1432. if (!currentCard) return;
  1433. // 收集当前题目的所有数据
  1434. const stemTextarea = currentCard.querySelector('.batch-stem');
  1435. const answerInput = currentCard.querySelector('.batch-answer');
  1436. const solutionTextarea = currentCard.querySelector('.batch-solution');
  1437. const optionsPreview = currentCard.querySelector('.batch-options-preview');
  1438. const questionTypeSelect = currentCard.querySelector('.batch-question-type');
  1439. const difficultySelect = currentCard.querySelector('.batch-difficulty');
  1440. let html = '<div class="space-y-6">';
  1441. // 题型和难度信息
  1442. html += '<div class="border-b border-gray-200 pb-3 mb-3">';
  1443. html += '<div class="flex items-center gap-3 text-sm">';
  1444. const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
  1445. const questionType = questionTypeSelect ? questionTypeSelect.value : 'choice';
  1446. html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
  1447. if (difficultySelect && difficultySelect.value) {
  1448. const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
  1449. html += `<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-bold">${diffMap[difficultySelect.value] || difficultySelect.value}</span>`;
  1450. }
  1451. html += '</div>';
  1452. html += '</div>';
  1453. // 题干预览
  1454. html += '<div class="border-b border-gray-200 pb-4">';
  1455. html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
  1456. const stem = stemTextarea ? stemTextarea.value : '';
  1457. if (stem) {
  1458. // 先提取图片标签,替换为占位符
  1459. const imagePlaceholders = [];
  1460. let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  1461. const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
  1462. imagePlaceholders.push(url);
  1463. return placeholder;
  1464. });
  1465. // 转义HTML
  1466. let stemHtml = stemProcessed
  1467. .replace(/&/g, '&amp;')
  1468. .replace(/</g, '&lt;')
  1469. .replace(/>/g, '&gt;')
  1470. .replace(/\n/g, '<br>');
  1471. // 将占位符替换为img标签
  1472. imagePlaceholders.forEach((url, index) => {
  1473. const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
  1474. 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;">`;
  1475. stemHtml = stemHtml.replace(placeholder, imgTag);
  1476. });
  1477. html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
  1478. } else {
  1479. html += '<p class="text-xs text-gray-400">暂无内容</p>';
  1480. }
  1481. html += '</div>';
  1482. // 选项预览(仅选择题)
  1483. if (questionTypeSelect && questionTypeSelect.value === 'choice') {
  1484. html += '<div class="border-b border-gray-200 pb-4">';
  1485. html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
  1486. // 直接从选项输入框读取内容,确保图片标签能正确显示
  1487. let hasOptions = false;
  1488. ['A', 'B', 'C', 'D'].forEach(key => {
  1489. const optionInput = currentCard.querySelector(`.batch-option-${key}`);
  1490. const optionText = optionInput ? optionInput.value : '';
  1491. if (optionText && optionText.trim()) {
  1492. hasOptions = true;
  1493. html += `<div class="mb-3">`;
  1494. html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
  1495. // 处理选项文本,支持图片标签
  1496. // 先提取图片标签,替换为占位符
  1497. const optionImagePlaceholders = [];
  1498. let optionProcessed = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  1499. const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${optionImagePlaceholders.length}__`;
  1500. optionImagePlaceholders.push(url);
  1501. return placeholder;
  1502. });
  1503. // 转义HTML
  1504. let optionHtml = optionProcessed
  1505. .replace(/&/g, '&amp;')
  1506. .replace(/</g, '&lt;')
  1507. .replace(/>/g, '&gt;')
  1508. .replace(/\n/g, '<br>');
  1509. // 将占位符替换为img标签
  1510. optionImagePlaceholders.forEach((url, index) => {
  1511. const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${index}__`;
  1512. 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;">`;
  1513. optionHtml = optionHtml.replace(placeholder, imgTag);
  1514. });
  1515. html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
  1516. html += `</div>`;
  1517. }
  1518. });
  1519. if (!hasOptions) {
  1520. html += '<p class="text-xs text-gray-400">暂无选项</p>';
  1521. }
  1522. html += '</div>';
  1523. }
  1524. // 答案预览
  1525. html += '<div class="border-b border-gray-200 pb-4">';
  1526. html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
  1527. const answer = answerInput ? answerInput.value : '';
  1528. if (answer) {
  1529. html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer)}</div>`;
  1530. } else {
  1531. html += '<p class="text-xs text-gray-400">暂无答案</p>';
  1532. }
  1533. html += '</div>';
  1534. // 解析预览
  1535. html += '<div>';
  1536. html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
  1537. const solution = solutionTextarea ? solutionTextarea.value : '';
  1538. if (solution) {
  1539. // 先提取图片标签,替换为占位符
  1540. const solutionImagePlaceholders = [];
  1541. let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  1542. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
  1543. solutionImagePlaceholders.push(url);
  1544. return placeholder;
  1545. });
  1546. // 转义HTML
  1547. let solutionHtml = solutionProcessed
  1548. .replace(/&/g, '&amp;')
  1549. .replace(/</g, '&lt;')
  1550. .replace(/>/g, '&gt;')
  1551. .replace(/\n/g, '<br>');
  1552. // 将占位符替换为img标签
  1553. solutionImagePlaceholders.forEach((url, index) => {
  1554. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
  1555. 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;">`;
  1556. solutionHtml = solutionHtml.replace(placeholder, imgTag);
  1557. });
  1558. html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
  1559. } else {
  1560. html += '<p class="text-xs text-gray-400">暂无解析</p>';
  1561. }
  1562. html += '</div>';
  1563. html += '</div>';
  1564. previewContent.innerHTML = html;
  1565. // 渲染LaTeX
  1566. if (window.renderMathInElement) {
  1567. try {
  1568. window.renderMathInElement(previewContent, {
  1569. delimiters: [
  1570. {left: "$$", right: "$$", display: true},
  1571. {left: "$", right: "$", display: false},
  1572. {left: "\\(", right: "\\)", display: false},
  1573. {left: "\\[", right: "\\]", display: true}
  1574. ],
  1575. throwOnError: false
  1576. });
  1577. } catch (e) {
  1578. console.warn('LaTeX 渲染失败:', e);
  1579. }
  1580. }
  1581. // 显示预览气泡
  1582. bubble.classList.remove('hidden');
  1583. }
  1584. function displayBatchPreview() {
  1585. const previewDiv = document.getElementById('batch-preview');
  1586. const questionsList = document.getElementById('questions-list');
  1587. previewDiv.classList.remove('hidden');
  1588. document.getElementById('batch-submit-btn').classList.remove('hidden');
  1589. questionsList.innerHTML = '';
  1590. // 创建所有题目卡片(默认隐藏)
  1591. parsedQuestions.forEach((q, index) => {
  1592. const questionId = `batch-q-card-${index}`;
  1593. const questionDiv = document.createElement('div');
  1594. questionDiv.className = `batch-question-card apple-card p-6 space-y-4 ${index === 0 ? '' : 'hidden'}`;
  1595. questionDiv.id = questionId;
  1596. questionDiv.setAttribute('data-index', index);
  1597. // 解析选项
  1598. let optionsJson = '{}';
  1599. let optionA = '', optionB = '', optionC = '', optionD = '';
  1600. if (q.options && typeof q.options === 'object') {
  1601. optionsJson = JSON.stringify(q.options, null, 2);
  1602. optionA = q.options.A || '';
  1603. optionB = q.options.B || '';
  1604. optionC = q.options.C || '';
  1605. optionD = q.options.D || '';
  1606. }
  1607. // 映射题型
  1608. const questionType = mapQuestionType(q.question_type);
  1609. questionDiv.innerHTML = `
  1610. <div class="border-b border-gray-100 pb-3 mb-3">
  1611. <div class="flex items-center gap-2">
  1612. <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">题号 ${q.number || index + 1}</span>
  1613. </div>
  1614. </div>
  1615. <!-- 题型和难度选择 -->
  1616. <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
  1617. <div class="space-y-1">
  1618. <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
  1619. <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">
  1620. <option value="choice" ${questionType === 'choice' ? 'selected' : ''}>选择题</option>
  1621. <option value="fill" ${questionType === 'fill' ? 'selected' : ''}>填空题</option>
  1622. <option value="answer" ${questionType === 'answer' ? 'selected' : ''}>解答题</option>
  1623. </select>
  1624. </div>
  1625. <div class="space-y-1">
  1626. <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
  1627. <div class="flex items-center gap-2">
  1628. <select name="difficulty" class="batch-difficulty flex-1 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
  1629. <option value="">请选择难度</option>
  1630. <option value="0.2" ${q.difficulty == 0.2 || q.difficulty == '0.2' ? 'selected' : ''}>筑基</option>
  1631. <option value="0.4" ${q.difficulty == 0.4 || q.difficulty == '0.4' ? 'selected' : ''}>提分</option>
  1632. <option value="0.7" ${q.difficulty == 0.7 || q.difficulty == '0.7' ? 'selected' : ''}>培优</option>
  1633. </select>
  1634. <button type="button" class="batch-evaluate-difficulty-btn btn-apple bg-gradient-to-r from-purple-500 to-indigo-600 text-white hover:from-purple-600 hover:to-indigo-700 text-xs py-2 px-3 shadow-md whitespace-nowrap" data-index="${index}" onclick="evaluateBatchDifficulty(${index})">
  1635. <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1636. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
  1637. </svg>
  1638. 难度评价
  1639. </button>
  1640. </div>
  1641. </div>
  1642. </div>
  1643. <!-- 年级选择(所有题目必填) -->
  1644. <div class="batch-grade-section space-y-1">
  1645. <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
  1646. <select name="grade" class="batch-grade w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm" required>
  1647. <option value="">请选择年级</option>
  1648. <option value="1" ${q.grade == 1 || q.grade == '1' || (currentGradeFilter === 1 && !q.grade) ? 'selected' : ''}>小学</option>
  1649. <option value="2" ${q.grade == 2 || q.grade == '2' || (currentGradeFilter === 2 && !q.grade) ? 'selected' : ''}>初中</option>
  1650. <option value="3" ${q.grade == 3 || q.grade == '3' || (currentGradeFilter === 3 && !q.grade) ? 'selected' : ''}>高中</option>
  1651. </select>
  1652. </div>
  1653. <!-- 题干编辑 -->
  1654. <div class="space-y-2">
  1655. <div class="flex items-center justify-between">
  1656. <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
  1657. <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>
  1658. </div>
  1659. <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"
  1660. placeholder="请输入题干内容或拖拽图片..."
  1661. data-index="${index}"
  1662. data-type="stem"
  1663. required>${escapeHtml(q.stem || '')}</textarea>
  1664. </div>
  1665. <!-- 选项编辑 -->
  1666. <div class="batch-options-section space-y-2" style="display: ${questionType === 'choice' ? 'block' : 'none'}">
  1667. <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
  1668. <div class="grid grid-cols-2 gap-3">
  1669. <div class="option-item">
  1670. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 A</label>
  1671. <div class="flex gap-1.5">
  1672. <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"
  1673. placeholder="输入选项A的内容或拖拽图片..."
  1674. data-index="${index}" data-option="A" data-type="option">${escapeHtml(optionA)}</textarea>
  1675. <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>
  1676. </div>
  1677. </div>
  1678. <div class="option-item">
  1679. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 B</label>
  1680. <div class="flex gap-1.5">
  1681. <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"
  1682. placeholder="输入选项B的内容或拖拽图片..."
  1683. data-index="${index}" data-option="B" data-type="option">${escapeHtml(optionB)}</textarea>
  1684. <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>
  1685. </div>
  1686. </div>
  1687. <div class="option-item">
  1688. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 C</label>
  1689. <div class="flex gap-1.5">
  1690. <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"
  1691. placeholder="输入选项C的内容或拖拽图片..."
  1692. data-index="${index}" data-option="C" data-type="option">${escapeHtml(optionC)}</textarea>
  1693. <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>
  1694. </div>
  1695. </div>
  1696. <div class="option-item">
  1697. <label class="text-xs font-medium text-gray-600 mb-1 block">选项 D</label>
  1698. <div class="flex gap-1.5">
  1699. <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"
  1700. placeholder="输入选项D的内容或拖拽图片..."
  1701. data-index="${index}" data-option="D" data-type="option">${escapeHtml(optionD)}</textarea>
  1702. <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>
  1703. </div>
  1704. </div>
  1705. </div>
  1706. <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
  1707. <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式,可直接编辑)</label>
  1708. <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"
  1709. data-index="${index}"
  1710. placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'>${escapeHtml(optionsJson)}</textarea>
  1711. </div>
  1712. </div>
  1713. <!-- 答案 -->
  1714. <div class="space-y-1">
  1715. <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
  1716. <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"
  1717. placeholder="例如: A" value="${escapeHtml(q.answer || '')}">
  1718. </div>
  1719. <!-- 解析 -->
  1720. <div class="space-y-2">
  1721. <div class="flex items-center justify-between">
  1722. <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
  1723. <button type="button" class="batch-upload-solution btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit" data-index="${index}">上传图片</button>
  1724. </div>
  1725. <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"
  1726. placeholder="请输入解析内容或拖拽图片..."
  1727. data-index="${index}"
  1728. data-type="solution">${escapeHtml(q.solution || '')}</textarea>
  1729. </div>
  1730. <!-- 查重检测按钮 -->
  1731. <div class="pt-4 border-t border-gray-200">
  1732. <button onclick="checkDuplicateForBatch(${index})" class="btn-apple bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 px-4 py-2 w-full flex items-center justify-center gap-2 whitespace-nowrap">
  1733. <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1734. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
  1735. </svg>
  1736. <span>查重检测</span>
  1737. </button>
  1738. </div>
  1739. `;
  1740. questionsList.appendChild(questionDiv);
  1741. // 设置选项同步逻辑
  1742. setupBatchQuestionEvents(index);
  1743. });
  1744. // 显示当前题并更新导航(不重置索引)
  1745. showBatchQuestion(currentBatchQuestionIndex);
  1746. updateBatchNavigation();
  1747. // 初始化预览
  1748. updateBatchFullPreview();
  1749. }
  1750. function escapeHtml(text) {
  1751. if (!text) return '';
  1752. const div = document.createElement('div');
  1753. div.textContent = text;
  1754. return div.innerHTML;
  1755. }
  1756. function mapQuestionType(type) {
  1757. if (!type) return 'choice';
  1758. const typeMap = {
  1759. '选择题': 'choice', '填空题': 'fill', '解答题': 'answer',
  1760. 'choice': 'choice', 'fill': 'fill', 'answer': 'answer'
  1761. };
  1762. return typeMap[type] || 'choice';
  1763. }
  1764. function setupBatchQuestionEvents(index) {
  1765. // 题型变化时显示/隐藏选项
  1766. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  1767. if (!questionDiv) return;
  1768. const typeSelect = questionDiv.querySelector('.batch-question-type');
  1769. const optionsSection = questionDiv.querySelector('.batch-options-section');
  1770. typeSelect.addEventListener('change', function() {
  1771. if (this.value === 'choice') {
  1772. optionsSection.style.display = 'block';
  1773. } else {
  1774. optionsSection.style.display = 'none';
  1775. }
  1776. updateBatchFullPreview();
  1777. });
  1778. // 选项输入框同步到预览
  1779. ['A', 'B', 'C', 'D'].forEach(opt => {
  1780. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  1781. if (input) {
  1782. input.addEventListener('input', function() {
  1783. updateBatchOptionsPreview(index);
  1784. updateBatchFullPreview();
  1785. });
  1786. }
  1787. });
  1788. // 预览框同步到输入框
  1789. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  1790. if (previewTextarea) {
  1791. previewTextarea.addEventListener('input', function() {
  1792. syncBatchOptionsFromPreview(index);
  1793. updateBatchFullPreview();
  1794. });
  1795. }
  1796. // 题干、答案、解析字段变化时更新预览和拖拽上传
  1797. const stemTextarea = questionDiv.querySelector('.batch-stem');
  1798. if (stemTextarea) {
  1799. stemTextarea.addEventListener('input', updateBatchFullPreview);
  1800. // 拖拽上传功能
  1801. stemTextarea.addEventListener('dragover', function(e) {
  1802. e.preventDefault();
  1803. e.stopPropagation();
  1804. this.classList.add('border-blue-500', 'bg-blue-50');
  1805. });
  1806. stemTextarea.addEventListener('dragleave', function(e) {
  1807. e.preventDefault();
  1808. e.stopPropagation();
  1809. this.classList.remove('border-blue-500', 'bg-blue-50');
  1810. });
  1811. stemTextarea.addEventListener('drop', async function(e) {
  1812. e.preventDefault();
  1813. e.stopPropagation();
  1814. this.classList.remove('border-blue-500', 'bg-blue-50');
  1815. const files = e.dataTransfer.files;
  1816. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  1817. await uploadBatchImageFile(files[0], index, 'stem');
  1818. }
  1819. });
  1820. }
  1821. const answerInput = questionDiv.querySelector('.batch-answer');
  1822. if (answerInput) {
  1823. answerInput.addEventListener('input', updateBatchFullPreview);
  1824. }
  1825. const solutionTextarea = questionDiv.querySelector('.batch-solution');
  1826. if (solutionTextarea) {
  1827. solutionTextarea.addEventListener('input', updateBatchFullPreview);
  1828. // 拖拽上传功能
  1829. solutionTextarea.addEventListener('dragover', function(e) {
  1830. e.preventDefault();
  1831. e.stopPropagation();
  1832. this.classList.add('border-blue-500', 'bg-blue-50');
  1833. });
  1834. solutionTextarea.addEventListener('dragleave', function(e) {
  1835. e.preventDefault();
  1836. e.stopPropagation();
  1837. this.classList.remove('border-blue-500', 'bg-blue-50');
  1838. });
  1839. solutionTextarea.addEventListener('drop', async function(e) {
  1840. e.preventDefault();
  1841. e.stopPropagation();
  1842. this.classList.remove('border-blue-500', 'bg-blue-50');
  1843. const files = e.dataTransfer.files;
  1844. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  1845. await uploadBatchImageFile(files[0], index, 'solution');
  1846. }
  1847. });
  1848. }
  1849. const difficultySelect = questionDiv.querySelector('.batch-difficulty');
  1850. if (difficultySelect) {
  1851. difficultySelect.addEventListener('change', updateBatchFullPreview);
  1852. }
  1853. // 图片上传按钮
  1854. const uploadStemBtn = questionDiv.querySelector('.batch-upload-stem');
  1855. if (uploadStemBtn) {
  1856. uploadStemBtn.addEventListener('click', function() {
  1857. uploadBatchImage(index, 'stem');
  1858. });
  1859. }
  1860. ['A', 'B', 'C', 'D'].forEach(opt => {
  1861. const uploadBtn = questionDiv.querySelector(`.batch-upload-option[data-option="${opt}"]`);
  1862. if (uploadBtn) {
  1863. uploadBtn.addEventListener('click', function() {
  1864. uploadBatchImage(index, 'option', opt);
  1865. });
  1866. }
  1867. });
  1868. const uploadSolutionBtn = questionDiv.querySelector('.batch-upload-solution');
  1869. if (uploadSolutionBtn) {
  1870. uploadSolutionBtn.addEventListener('click', function() {
  1871. uploadBatchImage(index, 'solution');
  1872. });
  1873. }
  1874. // 选项拖拽上传功能
  1875. ['A', 'B', 'C', 'D'].forEach(opt => {
  1876. const optionInput = questionDiv.querySelector(`.batch-option-${opt}`);
  1877. if (optionInput) {
  1878. optionInput.addEventListener('dragover', function(e) {
  1879. e.preventDefault();
  1880. e.stopPropagation();
  1881. this.classList.add('border-blue-500', 'bg-blue-50');
  1882. });
  1883. optionInput.addEventListener('dragleave', function(e) {
  1884. e.preventDefault();
  1885. e.stopPropagation();
  1886. this.classList.remove('border-blue-500', 'bg-blue-50');
  1887. });
  1888. optionInput.addEventListener('drop', async function(e) {
  1889. e.preventDefault();
  1890. e.stopPropagation();
  1891. this.classList.remove('border-blue-500', 'bg-blue-50');
  1892. const files = e.dataTransfer.files;
  1893. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  1894. await uploadBatchImageFile(files[0], index, 'option', opt);
  1895. }
  1896. });
  1897. }
  1898. });
  1899. // 粘贴图片功能
  1900. const allInputs = questionDiv.querySelectorAll('textarea, input[type="text"]');
  1901. allInputs.forEach(input => {
  1902. input.addEventListener('paste', async function(e) {
  1903. const clipboardData = e.clipboardData || window.clipboardData;
  1904. if (!clipboardData) {
  1905. return;
  1906. }
  1907. // 检查是否有图片数据
  1908. const items = clipboardData.items;
  1909. if (!items) {
  1910. return;
  1911. }
  1912. for (let i = 0; i < items.length; i++) {
  1913. const item = items[i];
  1914. // 如果是图片类型
  1915. if (item.type.indexOf('image') !== -1) {
  1916. e.preventDefault(); // 阻止默认粘贴行为
  1917. const file = item.getAsFile();
  1918. if (file) {
  1919. // 直接上传图片并插入到当前输入框
  1920. await uploadBatchImageToInput(file, input, index);
  1921. }
  1922. break;
  1923. }
  1924. }
  1925. });
  1926. });
  1927. }
  1928. function updateBatchOptionsPreview(index) {
  1929. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  1930. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  1931. const optionsObj = {};
  1932. ['A', 'B', 'C', 'D'].forEach(opt => {
  1933. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  1934. if (input && input.value.trim()) {
  1935. optionsObj[opt] = input.value.trim();
  1936. }
  1937. });
  1938. previewTextarea.value = JSON.stringify(optionsObj, null, 2);
  1939. }
  1940. function syncBatchOptionsFromPreview(index) {
  1941. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  1942. const previewTextarea = questionDiv.querySelector('.batch-options-preview');
  1943. try {
  1944. const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
  1945. ['A', 'B', 'C', 'D'].forEach(opt => {
  1946. const input = questionDiv.querySelector(`.batch-option-${opt}`);
  1947. if (input) {
  1948. input.value = optionsObj[opt] || '';
  1949. }
  1950. });
  1951. } catch (error) {
  1952. console.warn('选项预览 JSON 格式错误:', error);
  1953. }
  1954. }
  1955. function uploadBatchImage(index, type, option = null) {
  1956. const fileInput = document.createElement('input');
  1957. fileInput.type = 'file';
  1958. fileInput.accept = 'image/*';
  1959. fileInput.style.display = 'none';
  1960. fileInput.onchange = async (e) => {
  1961. const file = e.target.files[0];
  1962. if (!file) return;
  1963. if (!file.type.startsWith('image/')) {
  1964. if (window.customAlert) {
  1965. window.customAlert('请选择图片文件!');
  1966. } else {
  1967. alert('请选择图片文件!');
  1968. }
  1969. return;
  1970. }
  1971. await uploadBatchImageFile(file, index, type, option);
  1972. };
  1973. document.body.appendChild(fileInput);
  1974. fileInput.click();
  1975. document.body.removeChild(fileInput);
  1976. }
  1977. // 通用图片上传函数:上传图片并插入到指定输入框
  1978. async function uploadBatchImageToInput(file, inputElement, index) {
  1979. if (!inputElement || !file) {
  1980. return;
  1981. }
  1982. // 检查文件类型
  1983. if (!file.type.startsWith('image/')) {
  1984. if (window.customAlert) {
  1985. window.customAlert('请选择图片文件!');
  1986. } else {
  1987. alert('请选择图片文件!');
  1988. }
  1989. return;
  1990. }
  1991. // 显示上传中状态
  1992. const originalPlaceholder = inputElement.placeholder || '';
  1993. const originalOpacity = inputElement.style.opacity || '1';
  1994. inputElement.placeholder = '正在上传图片...';
  1995. inputElement.style.opacity = '0.6';
  1996. inputElement.disabled = true;
  1997. try {
  1998. const formData = new FormData();
  1999. formData.append('file', file);
  2000. const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
  2001. method: 'POST',
  2002. body: formData
  2003. });
  2004. if (!response.ok) {
  2005. throw new Error(`上传失败: ${response.status} ${response.statusText}`);
  2006. }
  2007. const result = await response.json();
  2008. // 检查返回结果,提取URL
  2009. let imageUrl = null;
  2010. if (typeof result === 'string') {
  2011. imageUrl = result;
  2012. } else if (result.url) {
  2013. imageUrl = result.url;
  2014. } else if (result.data && result.data.url) {
  2015. imageUrl = result.data.url;
  2016. } else if (result.data && typeof result.data === 'string') {
  2017. imageUrl = result.data;
  2018. } else {
  2019. const resultStr = JSON.stringify(result);
  2020. const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
  2021. if (urlMatch) {
  2022. imageUrl = urlMatch[0];
  2023. }
  2024. }
  2025. if (!imageUrl) {
  2026. throw new Error('接口返回格式异常,未找到图片URL。返回结果:' + JSON.stringify(result));
  2027. }
  2028. // 构建 image 标签
  2029. const imageTag = `<image src="${imageUrl}"/>`;
  2030. // 获取当前光标位置
  2031. const cursorPos = inputElement.selectionStart || inputElement.value.length;
  2032. const textBefore = inputElement.value.substring(0, cursorPos);
  2033. const textAfter = inputElement.value.substring(cursorPos);
  2034. // 插入 image 标签
  2035. inputElement.value = textBefore + imageTag + textAfter;
  2036. // 设置光标位置到插入内容之后
  2037. const newCursorPos = cursorPos + imageTag.length;
  2038. if (inputElement.setSelectionRange) {
  2039. inputElement.setSelectionRange(newCursorPos, newCursorPos);
  2040. }
  2041. inputElement.focus();
  2042. // 触发input事件,更新预览
  2043. inputElement.dispatchEvent(new Event('input', { bubbles: true }));
  2044. // 如果是选项输入框,更新选项预览
  2045. if (inputElement.classList.contains('batch-option-A') ||
  2046. inputElement.classList.contains('batch-option-B') ||
  2047. inputElement.classList.contains('batch-option-C') ||
  2048. inputElement.classList.contains('batch-option-D')) {
  2049. updateBatchOptionsPreview(index);
  2050. } else if (inputElement.classList.contains('batch-options-preview')) {
  2051. // 如果是在选项预览框中粘贴,需要同步到各个选项输入框
  2052. syncBatchOptionsFromPreview(index);
  2053. }
  2054. // 更新完整预览
  2055. updateBatchFullPreview();
  2056. } catch (error) {
  2057. console.error('上传失败:', error);
  2058. if (window.customAlert) {
  2059. window.customAlert('图片上传失败: ' + error.message);
  2060. } else {
  2061. alert('图片上传失败: ' + error.message);
  2062. }
  2063. } finally {
  2064. inputElement.placeholder = originalPlaceholder;
  2065. inputElement.style.opacity = originalOpacity;
  2066. inputElement.disabled = false;
  2067. }
  2068. }
  2069. // 保留旧函数以兼容拖拽上传
  2070. async function uploadBatchImageFile(file, index, type, option) {
  2071. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  2072. if (!questionDiv) {
  2073. questionDiv = document.querySelector(`[data-index="${index}"]`);
  2074. }
  2075. if (!questionDiv) return;
  2076. let targetInput;
  2077. if (type === 'stem') {
  2078. targetInput = questionDiv.querySelector('.batch-stem');
  2079. } else if (type === 'solution') {
  2080. targetInput = questionDiv.querySelector('.batch-solution');
  2081. } else if (type === 'answer') {
  2082. targetInput = questionDiv.querySelector('.batch-answer');
  2083. } else if (type === 'options-preview') {
  2084. targetInput = questionDiv.querySelector('.batch-options-preview');
  2085. } else if (type === 'option' && option) {
  2086. targetInput = questionDiv.querySelector(`.batch-option-${option}`);
  2087. }
  2088. if (!targetInput) return;
  2089. // 使用新的通用函数
  2090. await uploadBatchImageToInput(file, targetInput, index);
  2091. }
  2092. // 批量导入的难度评价函数
  2093. async function evaluateBatchDifficulty(index) {
  2094. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  2095. if (!questionDiv) return;
  2096. const btn = questionDiv.querySelector('.batch-evaluate-difficulty-btn');
  2097. const difficultySelect = questionDiv.querySelector('.batch-difficulty');
  2098. if (!btn || !difficultySelect) return;
  2099. // 收集题目信息
  2100. const stemTextarea = questionDiv.querySelector('.batch-stem');
  2101. const answerInput = questionDiv.querySelector('.batch-answer');
  2102. const solutionTextarea = questionDiv.querySelector('.batch-solution');
  2103. const optionsPreview = questionDiv.querySelector('.batch-options-preview');
  2104. const questionTypeSelect = questionDiv.querySelector('.batch-question-type');
  2105. const stem = stemTextarea ? stemTextarea.value.trim() : '';
  2106. if (!stem) {
  2107. if (window.customAlert) {
  2108. window.customAlert('请先填写题干内容');
  2109. } else {
  2110. alert('请先填写题干内容');
  2111. }
  2112. return;
  2113. }
  2114. // 构建请求数据
  2115. const requestData = {
  2116. stem: stem,
  2117. answer: answerInput ? answerInput.value.trim() : '',
  2118. solution: solutionTextarea ? solutionTextarea.value.trim() : '',
  2119. question_type: questionTypeSelect ? questionTypeSelect.value : ''
  2120. };
  2121. // 处理选项
  2122. if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
  2123. try {
  2124. requestData.options = JSON.parse(optionsPreview.value.trim());
  2125. } catch (e) {
  2126. console.warn('选项JSON解析失败:', e);
  2127. }
  2128. }
  2129. // 显示加载状态
  2130. const originalText = btn.innerHTML;
  2131. btn.disabled = true;
  2132. 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>评价中...';
  2133. try {
  2134. const response = await fetch('/api/score', {
  2135. method: 'POST',
  2136. headers: {
  2137. 'Content-Type': 'application/json'
  2138. },
  2139. body: JSON.stringify(requestData)
  2140. });
  2141. if (!response.ok) {
  2142. throw new Error(`请求失败: ${response.status} ${response.statusText}`);
  2143. }
  2144. const result = await response.json();
  2145. // 处理返回的 difficulty_level
  2146. let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
  2147. // 映射难度等级到枚举值
  2148. let difficultyValue = '';
  2149. if (difficultyLevel !== undefined && difficultyLevel !== null) {
  2150. const levelStr = String(difficultyLevel).trim();
  2151. if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
  2152. difficultyValue = '0.2';
  2153. } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
  2154. difficultyValue = '0.4';
  2155. } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
  2156. difficultyValue = '0.7';
  2157. } else {
  2158. const levelNum = parseFloat(levelStr);
  2159. if (!isNaN(levelNum)) {
  2160. if (Math.abs(levelNum - 0.2) < 0.1) {
  2161. difficultyValue = '0.2';
  2162. } else if (Math.abs(levelNum - 0.4) < 0.1) {
  2163. difficultyValue = '0.4';
  2164. } else if (Math.abs(levelNum - 0.7) < 0.1) {
  2165. difficultyValue = '0.7';
  2166. }
  2167. }
  2168. }
  2169. }
  2170. if (difficultyValue) {
  2171. difficultySelect.value = difficultyValue;
  2172. difficultySelect.dispatchEvent(new Event('change', { bubbles: true }));
  2173. updateBatchFullPreview();
  2174. } else {
  2175. console.error('无法识别难度等级,完整返回结果:', result);
  2176. if (window.customAlert) {
  2177. window.customAlert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
  2178. } else {
  2179. alert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
  2180. }
  2181. }
  2182. } catch (error) {
  2183. console.error('难度评价失败:', error);
  2184. if (window.customAlert) {
  2185. window.customAlert('难度评价失败: ' + error.message);
  2186. } else {
  2187. alert('难度评价失败: ' + error.message);
  2188. }
  2189. } finally {
  2190. btn.disabled = false;
  2191. btn.innerHTML = originalText;
  2192. }
  2193. }
  2194. async function submitBatchQuestions() {
  2195. const questionDivs = document.querySelectorAll('[data-index]');
  2196. if (questionDivs.length === 0) {
  2197. if (window.customAlert) {
  2198. window.customAlert('没有可提交的题目');
  2199. } else {
  2200. alert('没有可提交的题目');
  2201. }
  2202. return;
  2203. }
  2204. const submitBtn = document.getElementById('batch-submit-btn');
  2205. submitBtn.disabled = true;
  2206. submitBtn.textContent = '提交中...';
  2207. let successCount = 0;
  2208. const userName = localStorage.getItem('user_name') || '';
  2209. for (let i = 0; i < questionDivs.length; i++) {
  2210. const questionDiv = questionDivs[i];
  2211. const index = parseInt(questionDiv.getAttribute('data-index'));
  2212. try {
  2213. const stem = questionDiv.querySelector('.batch-stem').value.trim();
  2214. if (!stem) continue;
  2215. const questionData = {
  2216. stem: stem,
  2217. answer: questionDiv.querySelector('.batch-answer').value.trim(),
  2218. solution: questionDiv.querySelector('.batch-solution').value.trim(),
  2219. question_type: questionDiv.querySelector('.batch-question-type').value
  2220. };
  2221. // 只在有知识点代码时才添加 kp_code
  2222. if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
  2223. questionData.kp_code = currentBatchKpCode;
  2224. }
  2225. // 处理年级(所有题目必填)
  2226. const gradeSelect = questionDiv.querySelector('.batch-grade');
  2227. if (gradeSelect) {
  2228. const grade = gradeSelect.value;
  2229. if (!grade) {
  2230. if (window.customAlert) {
  2231. window.customAlert(`第 ${index + 1} 道题目:请选择年级`);
  2232. } else {
  2233. alert(`第 ${index + 1} 道题目:请选择年级`);
  2234. }
  2235. gradeSelect.focus();
  2236. submitBtn.disabled = false;
  2237. submitBtn.textContent = '批量提交';
  2238. return;
  2239. }
  2240. questionData.grade = parseInt(grade);
  2241. }
  2242. const difficulty = questionDiv.querySelector('.batch-difficulty').value;
  2243. if (difficulty) questionData.difficulty = parseFloat(difficulty);
  2244. const optionsPreview = questionDiv.querySelector('.batch-options-preview');
  2245. if (questionData.question_type === 'choice' && optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
  2246. try {
  2247. const optionsObj = JSON.parse(optionsPreview.value.trim());
  2248. if (Object.keys(optionsObj).length > 0) {
  2249. questionData.options = JSON.stringify(optionsObj);
  2250. }
  2251. } catch (e) {
  2252. console.warn('选项JSON解析失败:', e);
  2253. }
  2254. }
  2255. if (userName) questionData.create_by = userName;
  2256. const response = await fetch('/create_question', {
  2257. method: 'POST',
  2258. headers: {'Content-Type': 'application/json'},
  2259. body: JSON.stringify(questionData)
  2260. });
  2261. const result = await response.json();
  2262. if (result.success) {
  2263. successCount++;
  2264. // 调用接口2确认不重复
  2265. if (result.question_id) {
  2266. try {
  2267. await fetch('/api/confirm_repeat', {
  2268. method: 'POST',
  2269. headers: {'Content-Type': 'application/json'},
  2270. body: JSON.stringify({
  2271. questionId: result.question_id,
  2272. isRepeat: 0
  2273. })
  2274. });
  2275. } catch (error) {
  2276. console.warn('确认查重结果失败:', error);
  2277. }
  2278. }
  2279. }
  2280. } catch (error) {
  2281. console.error('提交失败:', error);
  2282. }
  2283. }
  2284. submitBtn.disabled = false;
  2285. submitBtn.textContent = '批量提交';
  2286. const message = `成功导入 ${successCount} 道题`;
  2287. if (window.customAlert) {
  2288. window.customAlert(message, () => {
  2289. if (successCount > 0) {
  2290. // 只在有知识点代码时才刷新题目列表
  2291. if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
  2292. loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
  2293. }
  2294. hideBatchImportModal();
  2295. }
  2296. });
  2297. } else {
  2298. alert(message);
  2299. if (successCount > 0) {
  2300. // 只在有知识点代码时才刷新题目列表
  2301. if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
  2302. loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
  2303. }
  2304. hideBatchImportModal();
  2305. }
  2306. }
  2307. }
  2308. // ==================== 录入题目弹窗相关函数 ====================
  2309. let currentAddQuestionKpCode = null;
  2310. let currentAddQuestionKpName = null;
  2311. function showAddQuestionModal(kpCode, kpName) {
  2312. // 处理 'null' 字符串,转换为 null
  2313. if (kpCode === 'null' || kpCode === null) {
  2314. currentAddQuestionKpCode = null;
  2315. currentAddQuestionKpName = null;
  2316. } else {
  2317. currentAddQuestionKpCode = kpCode;
  2318. currentAddQuestionKpName = kpName;
  2319. }
  2320. // 判断是否是"其他题目"
  2321. const isOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
  2322. // 设置知识点信息
  2323. if (kpCode && kpCode !== 'null' && kpName && kpName !== 'null') {
  2324. document.getElementById('add-question-kp-name').textContent = kpName;
  2325. document.getElementById('add-question-kp-code').textContent = kpCode;
  2326. } else {
  2327. document.getElementById('add-question-kp-name').textContent = '其他题目(未关联知识点)';
  2328. document.getElementById('add-question-kp-code').textContent = 'N/A';
  2329. }
  2330. // 重置表单
  2331. document.getElementById('add-question-form').reset();
  2332. document.getElementById('add-question-type').value = 'choice';
  2333. document.getElementById('add-question-difficulty').value = '';
  2334. // 如果有年级筛选,自动填充年级(但可以修改)
  2335. if (document.getElementById('add-question-grade')) {
  2336. if (currentGradeFilter !== null) {
  2337. document.getElementById('add-question-grade').value = currentGradeFilter.toString();
  2338. } else {
  2339. document.getElementById('add-question-grade').value = '';
  2340. }
  2341. }
  2342. ['A', 'B', 'C', 'D'].forEach(opt => {
  2343. document.getElementById(`add-option-${opt}`).value = '';
  2344. });
  2345. // 重置选项预览框
  2346. const optionsPreview = document.getElementById('add-options-preview');
  2347. if (optionsPreview) {
  2348. optionsPreview.value = '';
  2349. }
  2350. // 显示选项区域(默认选择题)
  2351. document.getElementById('add-options-section').style.display = 'block';
  2352. // 设置题型变化监听器
  2353. const typeSelect = document.getElementById('add-question-type');
  2354. const optionsSection = document.getElementById('add-options-section');
  2355. typeSelect.onchange = function() {
  2356. if (this.value === 'choice') {
  2357. optionsSection.style.display = 'block';
  2358. } else {
  2359. optionsSection.style.display = 'none';
  2360. }
  2361. updateAddQuestionPreview();
  2362. };
  2363. // 设置预览更新监听器
  2364. setupAddQuestionPreviewListeners();
  2365. // 设置图片上传和粘贴功能
  2366. setupAddQuestionImageUpload();
  2367. // 显示弹窗
  2368. document.getElementById('add-question-modal').classList.remove('hidden');
  2369. // 更新预览和选项预览
  2370. updateAddQuestionOptionsPreview();
  2371. updateAddQuestionPreview();
  2372. // 聚焦到题干输入框
  2373. setTimeout(() => {
  2374. document.getElementById('add-question-stem').focus();
  2375. }, 100);
  2376. }
  2377. function hideAddQuestionPreview() {
  2378. // 预览区域始终显示,这个函数可以用于未来扩展
  2379. }
  2380. // ==================== 图片上传和粘贴功能 ====================
  2381. function setupAddQuestionImageUpload() {
  2382. // 题干图片上传按钮
  2383. const uploadStemBtn = document.getElementById('add-upload-stem-btn');
  2384. if (uploadStemBtn) {
  2385. uploadStemBtn.onclick = function() {
  2386. const fileInput = document.createElement('input');
  2387. fileInput.type = 'file';
  2388. fileInput.accept = 'image/*';
  2389. fileInput.style.display = 'none';
  2390. fileInput.onchange = async (e) => {
  2391. const file = e.target.files[0];
  2392. if (file) {
  2393. await uploadAddQuestionImageToInput(file, document.getElementById('add-question-stem'));
  2394. }
  2395. };
  2396. document.body.appendChild(fileInput);
  2397. fileInput.click();
  2398. document.body.removeChild(fileInput);
  2399. };
  2400. }
  2401. // 题干拖拽上传
  2402. const stemTextarea = document.getElementById('add-question-stem');
  2403. if (stemTextarea) {
  2404. stemTextarea.addEventListener('dragover', function(e) {
  2405. e.preventDefault();
  2406. e.stopPropagation();
  2407. this.classList.add('border-blue-500', 'bg-blue-50');
  2408. });
  2409. stemTextarea.addEventListener('dragleave', function(e) {
  2410. e.preventDefault();
  2411. e.stopPropagation();
  2412. this.classList.remove('border-blue-500', 'bg-blue-50');
  2413. });
  2414. stemTextarea.addEventListener('drop', async function(e) {
  2415. e.preventDefault();
  2416. e.stopPropagation();
  2417. this.classList.remove('border-blue-500', 'bg-blue-50');
  2418. const files = e.dataTransfer.files;
  2419. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  2420. await uploadAddQuestionImageToInput(files[0], this);
  2421. }
  2422. });
  2423. }
  2424. // 选项拖拽上传
  2425. ['A', 'B', 'C', 'D'].forEach(opt => {
  2426. const optionInput = document.getElementById(`add-option-${opt}`);
  2427. if (optionInput) {
  2428. optionInput.addEventListener('dragover', function(e) {
  2429. e.preventDefault();
  2430. e.stopPropagation();
  2431. this.classList.add('border-blue-500', 'bg-blue-50');
  2432. });
  2433. optionInput.addEventListener('dragleave', function(e) {
  2434. e.preventDefault();
  2435. e.stopPropagation();
  2436. this.classList.remove('border-blue-500', 'bg-blue-50');
  2437. });
  2438. optionInput.addEventListener('drop', async function(e) {
  2439. e.preventDefault();
  2440. e.stopPropagation();
  2441. this.classList.remove('border-blue-500', 'bg-blue-50');
  2442. const files = e.dataTransfer.files;
  2443. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  2444. await uploadAddQuestionImageToInput(files[0], this);
  2445. }
  2446. });
  2447. }
  2448. });
  2449. // 解析拖拽上传
  2450. const solutionTextarea = document.getElementById('add-question-solution');
  2451. if (solutionTextarea) {
  2452. solutionTextarea.addEventListener('dragover', function(e) {
  2453. e.preventDefault();
  2454. e.stopPropagation();
  2455. this.classList.add('border-blue-500', 'bg-blue-50');
  2456. });
  2457. solutionTextarea.addEventListener('dragleave', function(e) {
  2458. e.preventDefault();
  2459. e.stopPropagation();
  2460. this.classList.remove('border-blue-500', 'bg-blue-50');
  2461. });
  2462. solutionTextarea.addEventListener('drop', async function(e) {
  2463. e.preventDefault();
  2464. e.stopPropagation();
  2465. this.classList.remove('border-blue-500', 'bg-blue-50');
  2466. const files = e.dataTransfer.files;
  2467. if (files && files.length > 0 && files[0].type.startsWith('image/')) {
  2468. await uploadAddQuestionImageToInput(files[0], this);
  2469. }
  2470. });
  2471. }
  2472. // 为所有输入框添加粘贴图片功能
  2473. const allInputs = document.querySelectorAll('#add-question-form textarea, #add-question-form input[type="text"]');
  2474. allInputs.forEach(input => {
  2475. input.addEventListener('paste', async function(e) {
  2476. const clipboardData = e.clipboardData || window.clipboardData;
  2477. if (!clipboardData) {
  2478. return;
  2479. }
  2480. const items = clipboardData.items;
  2481. if (!items) {
  2482. return;
  2483. }
  2484. for (let i = 0; i < items.length; i++) {
  2485. const item = items[i];
  2486. // 如果是图片类型
  2487. if (item.type.indexOf('image') !== -1) {
  2488. e.preventDefault(); // 阻止默认粘贴行为
  2489. const file = item.getAsFile();
  2490. if (file) {
  2491. // 上传图片并插入到当前输入框
  2492. await uploadAddQuestionImageToInput(file, this);
  2493. }
  2494. break;
  2495. }
  2496. }
  2497. });
  2498. });
  2499. }
  2500. // 通用图片上传函数:上传图片并插入到指定输入框
  2501. async function uploadAddQuestionImageToInput(file, inputElement) {
  2502. if (!inputElement || !file) {
  2503. return;
  2504. }
  2505. // 检查文件类型
  2506. if (!file.type.startsWith('image/')) {
  2507. if (window.customAlert) {
  2508. window.customAlert('请选择图片文件!');
  2509. } else {
  2510. alert('请选择图片文件!');
  2511. }
  2512. return;
  2513. }
  2514. // 显示上传中状态
  2515. const originalPlaceholder = inputElement.placeholder || '';
  2516. const originalOpacity = inputElement.style.opacity || '1';
  2517. inputElement.placeholder = '正在上传图片...';
  2518. inputElement.style.opacity = '0.6';
  2519. inputElement.disabled = true;
  2520. try {
  2521. const formData = new FormData();
  2522. formData.append('file', file);
  2523. const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
  2524. method: 'POST',
  2525. body: formData
  2526. });
  2527. if (!response.ok) {
  2528. throw new Error(`上传失败: ${response.status} ${response.statusText}`);
  2529. }
  2530. const result = await response.json();
  2531. // 检查返回结果,提取URL
  2532. let imageUrl = null;
  2533. if (typeof result === 'string') {
  2534. imageUrl = result;
  2535. } else if (result.url) {
  2536. imageUrl = result.url;
  2537. } else if (result.data && result.data.url) {
  2538. imageUrl = result.data.url;
  2539. } else if (result.data && typeof result.data === 'string') {
  2540. imageUrl = result.data;
  2541. } else {
  2542. const resultStr = JSON.stringify(result);
  2543. const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
  2544. if (urlMatch) {
  2545. imageUrl = urlMatch[0];
  2546. }
  2547. }
  2548. if (!imageUrl) {
  2549. throw new Error('接口返回格式异常,未找到图片URL。返回结果:' + JSON.stringify(result));
  2550. }
  2551. // 构建 image 标签
  2552. const imageTag = `<image src="${imageUrl}"/>`;
  2553. // 获取当前光标位置
  2554. const cursorPos = inputElement.selectionStart || inputElement.value.length;
  2555. const textBefore = inputElement.value.substring(0, cursorPos);
  2556. const textAfter = inputElement.value.substring(cursorPos);
  2557. // 插入 image 标签
  2558. inputElement.value = textBefore + imageTag + textAfter;
  2559. // 设置光标位置到插入内容之后
  2560. const newCursorPos = cursorPos + imageTag.length;
  2561. if (inputElement.setSelectionRange) {
  2562. inputElement.setSelectionRange(newCursorPos, newCursorPos);
  2563. }
  2564. inputElement.focus();
  2565. // 触发input事件,更新预览
  2566. inputElement.dispatchEvent(new Event('input', { bubbles: true }));
  2567. // 更新预览和选项预览
  2568. updateAddQuestionOptionsPreview();
  2569. updateAddQuestionPreview();
  2570. } catch (error) {
  2571. console.error('上传失败:', error);
  2572. if (window.customAlert) {
  2573. window.customAlert('图片上传失败: ' + error.message);
  2574. } else {
  2575. alert('图片上传失败: ' + error.message);
  2576. }
  2577. } finally {
  2578. inputElement.placeholder = originalPlaceholder;
  2579. inputElement.style.opacity = originalOpacity;
  2580. inputElement.disabled = false;
  2581. }
  2582. }
  2583. // 选项图片上传函数
  2584. function uploadAddQuestionOptionImage(optionKey) {
  2585. const fileInput = document.createElement('input');
  2586. fileInput.type = 'file';
  2587. fileInput.accept = 'image/*';
  2588. fileInput.style.display = 'none';
  2589. fileInput.onchange = async (e) => {
  2590. const file = e.target.files[0];
  2591. if (file) {
  2592. await uploadAddQuestionImageToInput(file, document.getElementById(`add-option-${optionKey}`));
  2593. }
  2594. };
  2595. document.body.appendChild(fileInput);
  2596. fileInput.click();
  2597. document.body.removeChild(fileInput);
  2598. }
  2599. // 解析图片上传函数
  2600. function uploadAddQuestionSolutionImage() {
  2601. const fileInput = document.createElement('input');
  2602. fileInput.type = 'file';
  2603. fileInput.accept = 'image/*';
  2604. fileInput.style.display = 'none';
  2605. fileInput.onchange = async (e) => {
  2606. const file = e.target.files[0];
  2607. if (file) {
  2608. await uploadAddQuestionImageToInput(file, document.getElementById('add-question-solution'));
  2609. }
  2610. };
  2611. document.body.appendChild(fileInput);
  2612. fileInput.click();
  2613. document.body.removeChild(fileInput);
  2614. }
  2615. function setupAddQuestionPreviewListeners() {
  2616. // 题干预览
  2617. const stemTextarea = document.getElementById('add-question-stem');
  2618. if (stemTextarea) {
  2619. stemTextarea.addEventListener('input', updateAddQuestionPreview);
  2620. stemTextarea.addEventListener('focus', updateAddQuestionPreview);
  2621. }
  2622. // 选项预览 - 从各个选项输入框自动拼接成JSON
  2623. ['A', 'B', 'C', 'D'].forEach(opt => {
  2624. const optionInput = document.getElementById(`add-option-${opt}`);
  2625. if (optionInput) {
  2626. optionInput.addEventListener('input', function() {
  2627. updateAddQuestionOptionsPreview();
  2628. updateAddQuestionPreview();
  2629. });
  2630. }
  2631. });
  2632. // 选项预览框 - 从JSON同步回各个选项输入框
  2633. const optionsPreview = document.getElementById('add-options-preview');
  2634. if (optionsPreview) {
  2635. optionsPreview.addEventListener('input', function() {
  2636. syncAddQuestionOptionsFromPreview();
  2637. updateAddQuestionPreview();
  2638. });
  2639. }
  2640. // 答案预览
  2641. const answerInput = document.getElementById('add-question-answer');
  2642. if (answerInput) {
  2643. answerInput.addEventListener('input', updateAddQuestionPreview);
  2644. }
  2645. // 解析预览
  2646. const solutionTextarea = document.getElementById('add-question-solution');
  2647. if (solutionTextarea) {
  2648. solutionTextarea.addEventListener('input', updateAddQuestionPreview);
  2649. solutionTextarea.addEventListener('focus', updateAddQuestionPreview);
  2650. }
  2651. // 题型和难度变化
  2652. const typeSelect = document.getElementById('add-question-type');
  2653. if (typeSelect) {
  2654. typeSelect.addEventListener('change', updateAddQuestionPreview);
  2655. }
  2656. const difficultySelect = document.getElementById('add-question-difficulty');
  2657. if (difficultySelect) {
  2658. difficultySelect.addEventListener('change', updateAddQuestionPreview);
  2659. }
  2660. }
  2661. function updateAddQuestionPreview() {
  2662. const previewContent = document.getElementById('add-question-preview-content');
  2663. if (!previewContent) return;
  2664. const stem = document.getElementById('add-question-stem')?.value || '';
  2665. const answer = document.getElementById('add-question-answer')?.value || '';
  2666. const solution = document.getElementById('add-question-solution')?.value || '';
  2667. const questionType = document.getElementById('add-question-type')?.value || 'choice';
  2668. const difficulty = document.getElementById('add-question-difficulty')?.value || '';
  2669. let html = '<div class="space-y-6">';
  2670. // 题型和难度信息
  2671. html += '<div class="border-b border-gray-200 pb-3 mb-3">';
  2672. html += '<div class="flex items-center gap-3 text-sm">';
  2673. const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
  2674. html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
  2675. if (difficulty) {
  2676. const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
  2677. html += `<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-bold">${diffMap[difficulty] || difficulty}</span>`;
  2678. }
  2679. html += '</div>';
  2680. html += '</div>';
  2681. // 题干预览
  2682. html += '<div class="border-b border-gray-200 pb-4">';
  2683. html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
  2684. if (stem) {
  2685. // 处理图片标签
  2686. let stemHtml = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  2687. return `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
  2688. });
  2689. // 转义HTML(但保留图片标签)
  2690. stemHtml = stemHtml
  2691. .replace(/&/g, '&amp;')
  2692. .replace(/</g, '&lt;')
  2693. .replace(/>/g, '&gt;')
  2694. .replace(/\n/g, '<br>');
  2695. // 恢复图片标签
  2696. stemHtml = stemHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
  2697. return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  2698. });
  2699. html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
  2700. } else {
  2701. html += '<p class="text-xs text-gray-400">暂无内容</p>';
  2702. }
  2703. html += '</div>';
  2704. // 选项预览(仅选择题)
  2705. if (questionType === 'choice') {
  2706. html += '<div class="border-b border-gray-200 pb-4">';
  2707. html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
  2708. let hasOptions = false;
  2709. ['A', 'B', 'C', 'D'].forEach(key => {
  2710. const optionText = document.getElementById(`add-option-${key}`)?.value || '';
  2711. if (optionText && optionText.trim()) {
  2712. hasOptions = true;
  2713. html += `<div class="mb-3">`;
  2714. html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
  2715. // 处理选项文本,支持图片标签
  2716. let optionHtml = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  2717. return `<img src="${url}" class="max-w-full max-h-[200px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="选项图片" style="object-fit: contain;">`;
  2718. });
  2719. // 转义HTML
  2720. optionHtml = optionHtml
  2721. .replace(/&/g, '&amp;')
  2722. .replace(/</g, '&lt;')
  2723. .replace(/>/g, '&gt;')
  2724. .replace(/\n/g, '<br>');
  2725. // 恢复图片标签
  2726. optionHtml = optionHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
  2727. return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  2728. });
  2729. html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
  2730. html += `</div>`;
  2731. }
  2732. });
  2733. if (!hasOptions) {
  2734. html += '<p class="text-xs text-gray-400">暂无选项</p>';
  2735. }
  2736. html += '</div>';
  2737. }
  2738. // 答案预览
  2739. html += '<div class="border-b border-gray-200 pb-4">';
  2740. html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
  2741. if (answer) {
  2742. html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer)}</div>`;
  2743. } else {
  2744. html += '<p class="text-xs text-gray-400">暂无答案</p>';
  2745. }
  2746. html += '</div>';
  2747. // 解析预览
  2748. html += '<div>';
  2749. html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
  2750. if (solution) {
  2751. // 处理图片标签
  2752. let solutionHtml = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  2753. return `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="解析图片" style="object-fit: contain;">`;
  2754. });
  2755. // 转义HTML
  2756. solutionHtml = solutionHtml
  2757. .replace(/&/g, '&amp;')
  2758. .replace(/</g, '&lt;')
  2759. .replace(/>/g, '&gt;')
  2760. .replace(/\n/g, '<br>');
  2761. // 恢复图片标签
  2762. solutionHtml = solutionHtml.replace(/&lt;img[^&]*&gt;/g, (match) => {
  2763. return match.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  2764. });
  2765. html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
  2766. } else {
  2767. html += '<p class="text-xs text-gray-400">暂无解析</p>';
  2768. }
  2769. html += '</div>';
  2770. html += '</div>';
  2771. previewContent.innerHTML = html;
  2772. // 渲染LaTeX
  2773. if (window.renderMathInElement) {
  2774. try {
  2775. window.renderMathInElement(previewContent, {
  2776. delimiters: [
  2777. {left: "$$", right: "$$", display: true},
  2778. {left: "$", right: "$", display: false},
  2779. {left: "\\(", right: "\\)", display: false},
  2780. {left: "\\[", right: "\\]", display: true}
  2781. ],
  2782. throwOnError: false
  2783. });
  2784. } catch (e) {
  2785. console.warn('LaTeX 渲染失败:', e);
  2786. }
  2787. }
  2788. }
  2789. // 更新单个录入题目的选项预览(从各个选项输入框自动拼接成JSON)
  2790. function updateAddQuestionOptionsPreview() {
  2791. const previewTextarea = document.getElementById('add-options-preview');
  2792. if (!previewTextarea) return;
  2793. const optionsObj = {};
  2794. ['A', 'B', 'C', 'D'].forEach(opt => {
  2795. const input = document.getElementById(`add-option-${opt}`);
  2796. if (input && input.value.trim()) {
  2797. optionsObj[opt] = input.value.trim();
  2798. }
  2799. });
  2800. previewTextarea.value = JSON.stringify(optionsObj, null, 2);
  2801. }
  2802. // 从选项预览框同步回各个选项输入框(单个录入题目)
  2803. function syncAddQuestionOptionsFromPreview() {
  2804. const previewTextarea = document.getElementById('add-options-preview');
  2805. if (!previewTextarea) return;
  2806. try {
  2807. const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
  2808. ['A', 'B', 'C', 'D'].forEach(opt => {
  2809. const input = document.getElementById(`add-option-${opt}`);
  2810. if (input) {
  2811. input.value = optionsObj[opt] || '';
  2812. }
  2813. });
  2814. } catch (error) {
  2815. console.warn('选项预览 JSON 格式错误:', error);
  2816. }
  2817. }
  2818. function hideAddQuestionModal() {
  2819. document.getElementById('add-question-modal').classList.add('hidden');
  2820. currentAddQuestionKpCode = null;
  2821. currentAddQuestionKpName = null;
  2822. }
  2823. // ==================== 查重检测相关函数 ====================
  2824. // 单独录题的查重检测
  2825. async function checkDuplicateForAddQuestion() {
  2826. const stem = document.getElementById('add-question-stem').value.trim();
  2827. if (!stem) {
  2828. if (window.customAlert) {
  2829. window.customAlert('请先填写题干内容');
  2830. } else {
  2831. alert('请先填写题干内容');
  2832. }
  2833. return;
  2834. }
  2835. // 构建查重请求数据
  2836. const checkData = {
  2837. stem: stem,
  2838. answer: document.getElementById('add-question-answer').value.trim(),
  2839. solution: document.getElementById('add-question-solution').value.trim()
  2840. };
  2841. // 处理选项(仅选择题)
  2842. const questionType = document.getElementById('add-question-type').value;
  2843. if (questionType === 'choice') {
  2844. const optionsObj = {};
  2845. ['A', 'B', 'C', 'D'].forEach(opt => {
  2846. const value = document.getElementById(`add-option-${opt}`).value.trim();
  2847. if (value) {
  2848. optionsObj[opt] = value;
  2849. }
  2850. });
  2851. if (Object.keys(optionsObj).length > 0) {
  2852. checkData.options = JSON.stringify(optionsObj);
  2853. }
  2854. }
  2855. await performDuplicateCheck(checkData, null);
  2856. }
  2857. // 批量导入的查重检测
  2858. async function checkDuplicateForBatch(index) {
  2859. const questionDiv = document.getElementById(`batch-q-card-${index}`);
  2860. if (!questionDiv) return;
  2861. const stem = questionDiv.querySelector('.batch-stem').value.trim();
  2862. if (!stem) {
  2863. if (window.customAlert) {
  2864. window.customAlert('请先填写题干内容');
  2865. } else {
  2866. alert('请先填写题干内容');
  2867. }
  2868. return;
  2869. }
  2870. // 构建查重请求数据
  2871. const checkData = {
  2872. stem: stem,
  2873. answer: questionDiv.querySelector('.batch-answer').value.trim(),
  2874. solution: questionDiv.querySelector('.batch-solution').value.trim()
  2875. };
  2876. // 处理选项(仅选择题)
  2877. const questionType = questionDiv.querySelector('.batch-question-type').value;
  2878. if (questionType === 'choice') {
  2879. const optionsPreview = questionDiv.querySelector('.batch-options-preview');
  2880. if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
  2881. try {
  2882. checkData.options = optionsPreview.value.trim();
  2883. } catch (e) {
  2884. console.warn('选项JSON解析失败:', e);
  2885. }
  2886. }
  2887. }
  2888. await performDuplicateCheck(checkData, questionDiv);
  2889. }
  2890. // 关闭所有 customAlert 弹窗
  2891. function closeAllCustomAlerts() {
  2892. // 查找所有 customAlert 创建的模态框(通过样式特征识别)
  2893. const modals = document.querySelectorAll('div[style*="position:fixed"][style*="z-index:9999"]');
  2894. modals.forEach(modal => {
  2895. // 检查是否是 customAlert 创建的(包含白色背景的 dialog)
  2896. const dialog = modal.querySelector('div[style*="background:white"]');
  2897. if (dialog) {
  2898. document.body.removeChild(modal);
  2899. }
  2900. });
  2901. }
  2902. // 执行查重检测
  2903. async function performDuplicateCheck(checkData, sourceElement) {
  2904. let loadingModal = null;
  2905. try {
  2906. // 显示加载状态
  2907. if (window.customAlert) {
  2908. // 创建 loading 模式的弹窗(不显示按钮)
  2909. loadingModal = document.createElement('div');
  2910. loadingModal.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.4);z-index:9999;display:flex;align-items:center;justify-content:center;';
  2911. const dialog = document.createElement('div');
  2912. dialog.style.cssText = 'background:white;padding:2rem;border-radius:12px;box-shadow:0 10px 40px rgba(0,0,0,0.2);max-width:400px;text-align:center;';
  2913. const msg = document.createElement('div');
  2914. msg.style.cssText = 'margin-bottom:1.5rem;font-size:1rem;color:#333;';
  2915. msg.textContent = '正在检测重复题目...';
  2916. dialog.appendChild(msg);
  2917. loadingModal.appendChild(dialog);
  2918. document.body.appendChild(loadingModal);
  2919. }
  2920. const response = await fetch('/api/check_duplicate', {
  2921. method: 'POST',
  2922. headers: {'Content-Type': 'application/json'},
  2923. body: JSON.stringify(checkData)
  2924. });
  2925. const result = await response.json();
  2926. // 关闭加载弹窗
  2927. if (loadingModal && loadingModal.parentNode) {
  2928. document.body.removeChild(loadingModal);
  2929. loadingModal = null;
  2930. }
  2931. closeAllCustomAlerts(); // 确保所有弹窗都关闭
  2932. if (result.code === -1 && result.result && result.result.repeatIdList && result.result.repeatIdList.length > 0) {
  2933. // 发现重复,显示比对弹窗
  2934. const repeatInfo = result.result.repeatIdList[0];
  2935. await showDuplicateComparison(checkData, repeatInfo, sourceElement);
  2936. } else if (result.code === 0) {
  2937. // 无重复
  2938. if (window.customAlert) {
  2939. window.customAlert('未发现重复题目,可以继续录入');
  2940. } else {
  2941. alert('未发现重复题目,可以继续录入');
  2942. }
  2943. } else {
  2944. throw new Error('查重接口返回异常');
  2945. }
  2946. } catch (error) {
  2947. // 关闭加载弹窗
  2948. if (loadingModal && loadingModal.parentNode) {
  2949. document.body.removeChild(loadingModal);
  2950. loadingModal = null;
  2951. }
  2952. closeAllCustomAlerts(); // 确保所有弹窗都关闭
  2953. console.error('查重检测失败:', error);
  2954. if (window.customAlert) {
  2955. window.customAlert('查重检测失败: ' + error.message);
  2956. } else {
  2957. alert('查重检测失败: ' + error.message);
  2958. }
  2959. }
  2960. }
  2961. // 显示比对弹窗
  2962. async function showDuplicateComparison(currentQuestionData, repeatInfo, sourceElement) {
  2963. const modal = document.getElementById('duplicate-comparison-modal');
  2964. const similarityInfo = document.getElementById('duplicate-similarity-info');
  2965. const currentQuestionDiv = document.getElementById('duplicate-current-question');
  2966. const existingQuestionDiv = document.getElementById('duplicate-existing-question');
  2967. // 显示相似度信息
  2968. similarityInfo.textContent = repeatInfo.repeatMsg || '发现重复题目';
  2969. // 渲染当前录入的题目
  2970. currentQuestionDiv.innerHTML = renderQuestionForComparison(currentQuestionData, sourceElement);
  2971. // 查询库中重复的题目
  2972. try {
  2973. const response = await fetch(`/api/question_by_id/${repeatInfo.questionsId}`);
  2974. const result = await response.json();
  2975. if (result.success && result.question) {
  2976. existingQuestionDiv.innerHTML = renderQuestionForComparison(result.question, null, true);
  2977. } else {
  2978. existingQuestionDiv.innerHTML = '<p class="text-gray-500">无法加载重复题目详情</p>';
  2979. }
  2980. } catch (error) {
  2981. console.error('加载重复题目失败:', error);
  2982. existingQuestionDiv.innerHTML = '<p class="text-red-500">加载重复题目失败: ' + error.message + '</p>';
  2983. }
  2984. // 显示弹窗
  2985. modal.classList.remove('hidden');
  2986. // 渲染LaTeX
  2987. setTimeout(() => {
  2988. [currentQuestionDiv, existingQuestionDiv].forEach(container => {
  2989. if (window.renderMathInElement) {
  2990. try {
  2991. window.renderMathInElement(container, {
  2992. delimiters: [
  2993. {left: "$$", right: "$$", display: true},
  2994. {left: "$", right: "$", display: false},
  2995. {left: "\\(", right: "\\)", display: false},
  2996. {left: "\\[", right: "\\]", display: true}
  2997. ],
  2998. throwOnError: false
  2999. });
  3000. } catch (e) {
  3001. console.warn('LaTeX 渲染失败:', e);
  3002. }
  3003. }
  3004. });
  3005. }, 100);
  3006. }
  3007. // 渲染题目用于比对
  3008. function renderQuestionForComparison(questionData, sourceElement, isExisting = false) {
  3009. let html = '';
  3010. // 题型
  3011. const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
  3012. const questionType = questionData.question_type || '';
  3013. const typeText = typeMap[questionType] || questionType || '未分类';
  3014. html += `<div class="mb-4">
  3015. <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs font-bold">${typeText}</span>
  3016. </div>`;
  3017. // 题干
  3018. html += '<div class="mb-4">';
  3019. html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
  3020. let stem = '';
  3021. if (isExisting) {
  3022. stem = questionData.stem || '';
  3023. } else if (sourceElement) {
  3024. stem = sourceElement.querySelector('.batch-stem').value;
  3025. } else {
  3026. stem = document.getElementById('add-question-stem').value;
  3027. }
  3028. // 处理图片标签
  3029. const imagePlaceholders = [];
  3030. let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  3031. const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
  3032. imagePlaceholders.push(url);
  3033. return placeholder;
  3034. });
  3035. // 转义HTML
  3036. let stemHtml = stemProcessed
  3037. .replace(/&/g, '&amp;')
  3038. .replace(/</g, '&lt;')
  3039. .replace(/>/g, '&gt;')
  3040. .replace(/\n/g, '<br>');
  3041. // 替换图片占位符
  3042. imagePlaceholders.forEach((url, index) => {
  3043. const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
  3044. const imgTag = `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg" alt="题目图片" style="object-fit: contain;">`;
  3045. stemHtml = stemHtml.replace(placeholder, imgTag);
  3046. });
  3047. html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
  3048. html += '</div>';
  3049. // 选项(仅选择题)
  3050. if (questionType === 'choice') {
  3051. html += '<div class="mb-4">';
  3052. html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
  3053. let options = {};
  3054. if (isExisting) {
  3055. if (questionData.options) {
  3056. try {
  3057. options = typeof questionData.options === 'string' ? JSON.parse(questionData.options) : questionData.options;
  3058. } catch (e) {
  3059. options = {};
  3060. }
  3061. }
  3062. } else if (sourceElement) {
  3063. const optionsPreview = sourceElement.querySelector('.batch-options-preview');
  3064. if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
  3065. try {
  3066. options = JSON.parse(optionsPreview.value.trim());
  3067. } catch (e) {
  3068. options = {};
  3069. }
  3070. }
  3071. } else {
  3072. ['A', 'B', 'C', 'D'].forEach(opt => {
  3073. const value = document.getElementById(`add-option-${opt}`).value.trim();
  3074. if (value) {
  3075. options[opt] = value;
  3076. }
  3077. });
  3078. }
  3079. Object.entries(options).forEach(([key, value]) => {
  3080. html += `<div class="mb-2">
  3081. <span class="font-semibold text-gray-700">${key}:</span>
  3082. <span class="text-sm text-gray-600 ml-2">${escapeHtml(value)}</span>
  3083. </div>`;
  3084. });
  3085. html += '</div>';
  3086. }
  3087. // 答案
  3088. html += '<div class="mb-4">';
  3089. html += '<div class="text-xs font-bold text-gray-500 mb-2">答案</div>';
  3090. let answer = '';
  3091. if (isExisting) {
  3092. answer = questionData.answer || '';
  3093. } else if (sourceElement) {
  3094. answer = sourceElement.querySelector('.batch-answer').value;
  3095. } else {
  3096. answer = document.getElementById('add-question-answer').value;
  3097. }
  3098. html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer) || '暂无'}</div>`;
  3099. html += '</div>';
  3100. // 解析
  3101. html += '<div class="mb-4">';
  3102. html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
  3103. let solution = '';
  3104. if (isExisting) {
  3105. solution = questionData.solution || '';
  3106. } else if (sourceElement) {
  3107. solution = sourceElement.querySelector('.batch-solution').value;
  3108. } else {
  3109. solution = document.getElementById('add-question-solution').value;
  3110. }
  3111. if (solution) {
  3112. // 处理图片标签
  3113. const solutionImagePlaceholders = [];
  3114. let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
  3115. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
  3116. solutionImagePlaceholders.push(url);
  3117. return placeholder;
  3118. });
  3119. // 转义HTML
  3120. let solutionHtml = solutionProcessed
  3121. .replace(/&/g, '&amp;')
  3122. .replace(/</g, '&lt;')
  3123. .replace(/>/g, '&gt;')
  3124. .replace(/\n/g, '<br>');
  3125. // 替换图片占位符
  3126. solutionImagePlaceholders.forEach((url, index) => {
  3127. const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
  3128. const imgTag = `<img src="${url}" class="max-w-full max-h-[300px] w-auto h-auto my-2 rounded-lg" alt="解析图片" style="object-fit: contain;">`;
  3129. solutionHtml = solutionHtml.replace(placeholder, imgTag);
  3130. });
  3131. html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
  3132. } else {
  3133. html += '<p class="text-sm text-gray-400">暂无解析</p>';
  3134. }
  3135. html += '</div>';
  3136. return html;
  3137. }
  3138. // 关闭比对弹窗
  3139. function hideDuplicateComparisonModal() {
  3140. document.getElementById('duplicate-comparison-modal').classList.add('hidden');
  3141. }
  3142. async function submitAddQuestion() {
  3143. const form = document.getElementById('add-question-form');
  3144. const stem = document.getElementById('add-question-stem').value.trim();
  3145. // 验证必填项
  3146. if (!stem) {
  3147. if (window.customAlert) {
  3148. window.customAlert('请填写题干');
  3149. } else {
  3150. alert('请填写题干');
  3151. }
  3152. return;
  3153. }
  3154. // 构建提交数据
  3155. const data = {
  3156. stem: stem,
  3157. answer: document.getElementById('add-question-answer').value.trim(),
  3158. solution: document.getElementById('add-question-solution').value.trim(),
  3159. question_type: document.getElementById('add-question-type').value
  3160. };
  3161. // 只在有知识点代码时才添加 kp_code
  3162. if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '') {
  3163. data.kp_code = currentAddQuestionKpCode;
  3164. }
  3165. // 处理年级(所有题目必填)
  3166. const gradeSelect = document.getElementById('add-question-grade');
  3167. if (gradeSelect) {
  3168. const grade = gradeSelect.value;
  3169. if (!grade) {
  3170. if (window.customAlert) {
  3171. window.customAlert('请选择年级');
  3172. } else {
  3173. alert('请选择年级');
  3174. }
  3175. gradeSelect.focus();
  3176. return;
  3177. }
  3178. data.grade = parseInt(grade);
  3179. }
  3180. // 处理难度
  3181. const difficulty = document.getElementById('add-question-difficulty').value;
  3182. if (difficulty) {
  3183. data.difficulty = parseFloat(difficulty);
  3184. }
  3185. // 处理选项(仅选择题)
  3186. if (data.question_type === 'choice') {
  3187. const optionsObj = {};
  3188. ['A', 'B', 'C', 'D'].forEach(opt => {
  3189. const value = document.getElementById(`add-option-${opt}`).value.trim();
  3190. if (value) {
  3191. optionsObj[opt] = value;
  3192. }
  3193. });
  3194. if (Object.keys(optionsObj).length > 0) {
  3195. data.options = JSON.stringify(optionsObj);
  3196. }
  3197. }
  3198. // 添加创建者
  3199. const userName = localStorage.getItem('user_name');
  3200. if (userName && userName.trim()) {
  3201. data.create_by = userName.trim();
  3202. }
  3203. // 提交按钮状态
  3204. const submitBtn = document.querySelector('#add-question-modal button[onclick="submitAddQuestion()"]');
  3205. const originalText = submitBtn.textContent;
  3206. submitBtn.disabled = true;
  3207. submitBtn.textContent = '提交中...';
  3208. try {
  3209. const response = await fetch('/create_question', {
  3210. method: 'POST',
  3211. headers: {'Content-Type': 'application/json'},
  3212. body: JSON.stringify(data)
  3213. });
  3214. const result = await response.json();
  3215. if (result.success) {
  3216. // 调用接口2确认不重复
  3217. if (result.question_id) {
  3218. try {
  3219. await fetch('/api/confirm_repeat', {
  3220. method: 'POST',
  3221. headers: {'Content-Type': 'application/json'},
  3222. body: JSON.stringify({
  3223. questionId: result.question_id,
  3224. isRepeat: 0
  3225. })
  3226. });
  3227. } catch (error) {
  3228. console.warn('确认查重结果失败:', error);
  3229. }
  3230. }
  3231. if (window.customAlert) {
  3232. window.customAlert('题目创建成功!', () => {
  3233. // 只在有知识点代码时才刷新题目列表
  3234. if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
  3235. loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
  3236. }
  3237. hideAddQuestionModal();
  3238. });
  3239. } else {
  3240. alert('题目创建成功!');
  3241. // 只在有知识点代码时才刷新题目列表
  3242. if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
  3243. loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
  3244. }
  3245. hideAddQuestionModal();
  3246. }
  3247. } else {
  3248. if (window.customAlert) {
  3249. window.customAlert('创建失败: ' + (result.error || '未知错误'));
  3250. } else {
  3251. alert('创建失败: ' + (result.error || '未知错误'));
  3252. }
  3253. }
  3254. } catch (error) {
  3255. console.error('提交失败:', error);
  3256. if (window.customAlert) {
  3257. window.customAlert('提交失败: ' + error.message);
  3258. } else {
  3259. alert('提交失败: ' + error.message);
  3260. }
  3261. } finally {
  3262. submitBtn.disabled = false;
  3263. submitBtn.textContent = originalText;
  3264. }
  3265. }
  3266. // 难度评价函数
  3267. async function evaluateAddQuestionDifficulty() {
  3268. const btn = document.getElementById('add-evaluate-difficulty-btn');
  3269. const difficultySelect = document.getElementById('add-question-difficulty');
  3270. const stem = document.getElementById('add-question-stem').value.trim();
  3271. if (!stem) {
  3272. if (window.customAlert) {
  3273. window.customAlert('请先填写题干内容');
  3274. } else {
  3275. alert('请先填写题干内容');
  3276. }
  3277. return;
  3278. }
  3279. const requestData = {
  3280. stem: stem,
  3281. answer: document.getElementById('add-question-answer').value.trim(),
  3282. solution: document.getElementById('add-question-solution').value.trim(),
  3283. question_type: document.getElementById('add-question-type').value
  3284. };
  3285. // 处理选项
  3286. if (requestData.question_type === 'choice') {
  3287. const optionsObj = {};
  3288. ['A', 'B', 'C', 'D'].forEach(opt => {
  3289. const value = document.getElementById(`add-option-${opt}`).value.trim();
  3290. if (value) {
  3291. optionsObj[opt] = value;
  3292. }
  3293. });
  3294. if (Object.keys(optionsObj).length > 0) {
  3295. requestData.options = optionsObj;
  3296. }
  3297. }
  3298. const originalText = btn.innerHTML;
  3299. btn.disabled = true;
  3300. 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>评价中...';
  3301. try {
  3302. const response = await fetch('/api/score', {
  3303. method: 'POST',
  3304. headers: {'Content-Type': 'application/json'},
  3305. body: JSON.stringify(requestData)
  3306. });
  3307. if (!response.ok) {
  3308. throw new Error(`请求失败: ${response.status}`);
  3309. }
  3310. const result = await response.json();
  3311. let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
  3312. let difficultyValue = '';
  3313. if (difficultyLevel !== undefined && difficultyLevel !== null) {
  3314. const levelStr = String(difficultyLevel).trim();
  3315. if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
  3316. difficultyValue = '0.2';
  3317. } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
  3318. difficultyValue = '0.4';
  3319. } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
  3320. difficultyValue = '0.7';
  3321. } else {
  3322. const levelNum = parseFloat(levelStr);
  3323. if (!isNaN(levelNum)) {
  3324. if (Math.abs(levelNum - 0.2) < 0.1) {
  3325. difficultyValue = '0.2';
  3326. } else if (Math.abs(levelNum - 0.4) < 0.1) {
  3327. difficultyValue = '0.4';
  3328. } else if (Math.abs(levelNum - 0.7) < 0.1) {
  3329. difficultyValue = '0.7';
  3330. }
  3331. }
  3332. }
  3333. }
  3334. if (difficultyValue) {
  3335. difficultySelect.value = difficultyValue;
  3336. } else {
  3337. console.error('无法识别难度等级:', result);
  3338. if (window.customAlert) {
  3339. window.customAlert('无法识别返回的难度等级');
  3340. }
  3341. }
  3342. } catch (error) {
  3343. console.error('难度评价失败:', error);
  3344. if (window.customAlert) {
  3345. window.customAlert('难度评价失败: ' + error.message);
  3346. } else {
  3347. alert('难度评价失败: ' + error.message);
  3348. }
  3349. } finally {
  3350. btn.disabled = false;
  3351. btn.innerHTML = originalText;
  3352. }
  3353. }
  3354. </script>
  3355. {% endblock %}