question_management.html 172 KB

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