| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753 |
- {% extends "layout.html" %}
- {% block page_title %}题目管理{% endblock %}
- {% block content %}
- {% set is_audit_mode = is_audit_mode|default(false) %}
- <div class="flex gap-6">
- <!-- 左侧目录索引 -->
- <div class="w-96 flex-shrink-0">
- <div class="apple-card p-6 sticky top-4 max-h-[calc(100vh-2rem)] overflow-y-auto">
- <div class="flex items-center justify-between mb-6 pb-3 border-b border-gray-200">
- <h2 class="text-lg font-bold text-gray-800">{% if is_audit_mode %}未审核知识点{% else %}知识点目录{% endif %}</h2>
- </div>
- <nav class="space-y-1">
- {% macro render_kp_node(node, level) %}
- <div class="kp-node-item mb-1" data-kp-code="{{ node.kp_code }}" data-level="{{ level }}">
- <div class="flex items-center gap-1 group">
- {% if node.children|length > 0 %}
- <button
- onclick="toggleKpNode('{{ node.kp_code }}'); event.stopPropagation();"
- 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"
- data-expanded="{% if level == 0 %}true{% else %}false{% endif %}"
- data-kp-code="{{ node.kp_code }}">
- {% if level == 0 %}
- <i class="ri-subtract-line text-sm"></i>
- {% else %}
- <i class="ri-add-line text-sm"></i>
- {% endif %}
- </button>
- {% else %}
- <div class="w-6 h-6 flex items-center justify-center flex-shrink-0">
- <div class="w-1.5 h-1.5 rounded-full bg-gray-400"></div>
- </div>
- {% endif %}
- <a href="javascript:void(0)"
- onclick="loadQuestionsByKp('{{ node.kp_code }}', '{{ node.name }}', this); return false;"
- data-kp-code="{{ node.kp_code }}"
- data-kp-name="{{ node.name }}"
- 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">
- <div class="flex items-center gap-2 flex-nowrap">
- {% if level == 0 %}
- <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>
- {% elif level == 1 %}
- <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>
- {% else %}
- <span class="bg-gray-200 text-gray-700 px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0">小节</span>
- {% endif %}
- <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>
- {% set total_count = node.total_question_count|default(node.question_count|default(0)) %}
- {% if total_count > 0 %}
- <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>
- {% endif %}
- </div>
- </a>
- </div>
- {% if node.children|length > 0 %}
- <div class="kp-children ml-8 mt-1 {% if level >= 1 %}hidden{% endif %}" id="kp-children-{{ node.kp_code }}" data-level="{{ level }}">
- {% for child in node.children %}
- {{ render_kp_node(child, level + 1) }}
- {% endfor %}
- </div>
- {% endif %}
- </div>
- {% endmacro %}
-
- <!-- 其他题目节点 -->
- <div class="kp-node-item mb-2 pb-2 border-b border-gray-200" data-kp-code="null" data-level="-1">
- <a href="javascript:void(0)"
- onclick="loadQuestionsByKp('null', '其他题目', this); return false;"
- data-kp-code="null"
- data-kp-name="其他题目"
- 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">
- <div class="flex items-center gap-2 flex-nowrap">
- <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>
- <span class="text-sm font-bold text-gray-800 group-hover:text-purple-600 transition-colors flex-1 min-w-0 truncate">其他题目</span>
- {% if other_questions_count|default(0) > 0 %}
- <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>
- {% endif %}
- </div>
- </a>
- </div>
-
- {% if kp_tree %}
- {% for root_node in kp_tree %}
- {{ render_kp_node(root_node, 0) }}
- {% endfor %}
- {% else %}
- <div class="text-sm text-gray-500 text-center py-8">暂无知识点数据</div>
- {% endif %}
- </nav>
- </div>
- </div>
-
- <!-- 右侧题目列表区域 -->
- <div class="flex-1">
- <!-- 年级筛选栏 -->
- <div class="mb-4 flex items-center gap-3">
- <span class="text-sm font-semibold text-gray-700">年级筛选:</span>
- <div class="flex items-center gap-2">
- <button
- id="grade-filter-all"
- onclick="setGradeFilter(null)"
- 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">
- 全部
- </button>
- <button
- id="grade-filter-1"
- onclick="setGradeFilter(1)"
- 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">
- 小学
- </button>
- <button
- id="grade-filter-2"
- onclick="setGradeFilter(2)"
- 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">
- 初中
- </button>
- <button
- id="grade-filter-3"
- onclick="setGradeFilter(3)"
- 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">
- 高中
- </button>
- </div>
- <span id="grade-filter-indicator" class="text-xs text-gray-500 ml-2 hidden">
- <span id="grade-filter-text"></span>
- </span>
- </div>
-
- <div id="questions-container" class="space-y-4">
- <div class="apple-card p-12 text-center">
- <div class="text-gray-400 mb-4">
- <i class="ri-file-list-line text-6xl"></i>
- </div>
- <h3 class="text-lg font-bold text-gray-600 mb-2">请选择左侧知识点</h3>
- <p class="text-sm text-gray-500 mb-6">点击知识点查看该知识点下的题目</p>
- <div class="flex items-center justify-center gap-3">
- <button onclick="showAddQuestionModal(null, null)"
- 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">
- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
- </svg>
- 录入题目
- </button>
- <button onclick="showBatchImportModal(null, null)"
- 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">
- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <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"/>
- </svg>
- 批量导入
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- <script>
- // 知识点树形数据(从服务器端传递)
- const kpTreeData = {{ kp_tree|tojson|safe }};
- // 当前选中的年级筛选(null表示全部,1=小学,2=初中,3=高中)
- let currentGradeFilter = null;
- // 设置年级筛选
- function setGradeFilter(grade) {
- currentGradeFilter = grade;
-
- // 更新按钮样式
- document.querySelectorAll('.grade-filter-btn').forEach(btn => {
- btn.classList.remove('active', 'bg-pink-100', 'bg-blue-100', 'bg-purple-100', 'border-pink-500', 'border-blue-500', 'border-purple-500');
- btn.classList.add('border-gray-300', 'bg-white');
- });
-
- // 设置当前选中按钮的样式
- const indicator = document.getElementById('grade-filter-indicator');
- const indicatorText = document.getElementById('grade-filter-text');
-
- if (grade === null) {
- document.getElementById('grade-filter-all').classList.add('active', 'bg-gray-100', 'border-gray-500');
- indicator.classList.add('hidden');
- } else {
- const gradeNames = { 1: '小学', 2: '初中', 3: '高中' };
- const gradeColors = {
- 1: { bg: 'bg-pink-100', border: 'border-pink-500' },
- 2: { bg: 'bg-blue-100', border: 'border-blue-500' },
- 3: { bg: 'bg-purple-100', border: 'border-purple-500' }
- };
-
- const btn = document.getElementById(`grade-filter-${grade}`);
- btn.classList.add('active', gradeColors[grade].bg, gradeColors[grade].border);
- btn.classList.remove('border-gray-300', 'bg-white');
-
- indicator.classList.remove('hidden');
- indicatorText.textContent = `当前筛选:${gradeNames[grade]}`;
- }
-
- // 如果当前有加载的题目列表,重新加载(根据年级筛选)
- if (currentKpCode) {
- loadQuestionsByKp(currentKpCode, currentKpName);
- }
- }
- // 页面加载时初始化年级筛选按钮样式
- document.addEventListener('DOMContentLoaded', function() {
- // 默认选中"全部"
- setGradeFilter(null);
- });
- // 知识点目录折叠/展开功能
- function toggleKpNode(kpCode) {
- const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
- const expandBtn = document.querySelector(`.kp-expand-btn[data-kp-code="${kpCode}"]`);
-
- if (!childrenContainer || !expandBtn) return;
-
- const isExpanded = expandBtn.getAttribute('data-expanded') === 'true';
- const icon = expandBtn.querySelector('i');
-
- if (isExpanded) {
- // 折叠
- childrenContainer.classList.add('hidden');
- expandBtn.setAttribute('data-expanded', 'false');
- if (icon) {
- icon.className = 'ri-add-line text-sm';
- }
- } else {
- // 展开
- childrenContainer.classList.remove('hidden');
- expandBtn.setAttribute('data-expanded', 'true');
- if (icon) {
- icon.className = 'ri-subtract-line text-sm';
- }
- }
- }
- // 存储当前知识点的代码和名称(用于构建返回链接)
- let currentKpCode = null;
- let currentKpName = null;
- // 加载指定知识点的题目列表(带页码)
- function loadQuestionsByKpPage(kpCode, page) {
- // 更新URL参数,但不刷新页面
- const url = new URL(window.location);
- url.searchParams.set('kp_code', kpCode);
- if (page > 1) {
- url.searchParams.set('page', page);
- } else {
- url.searchParams.delete('page');
- }
- window.history.pushState({}, '', url);
-
- // 重新加载题目列表
- const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
- const kpName = kpLink ? (kpLink.getAttribute('data-kp-name') || kpCode) : kpCode;
- loadQuestionsByKp(kpCode, kpName, kpLink, page);
- }
- // 加载指定知识点的题目列表
- function loadQuestionsByKp(kpCode, kpName, linkElement, page = null) {
- const container = document.getElementById('questions-container');
- if (!container) return;
-
- // 保存当前知识点信息
- currentKpCode = kpCode;
- currentKpName = kpName;
-
- // 更新选中状态
- document.querySelectorAll('.kp-link').forEach(link => {
- link.classList.remove('bg-blue-50', 'border-blue-400');
- });
- if (linkElement) {
- linkElement.classList.add('bg-blue-50', 'border-blue-400');
- }
-
- // 显示加载状态
- container.innerHTML = `
- <div class="apple-card p-12 text-center">
- <div class="text-blue-500 mb-4">
- <i class="ri-loader-4-line text-6xl animate-spin"></i>
- </div>
- <p class="text-gray-600">正在加载题目...</p>
- </div>
- `;
-
- // 如果没有指定页码,从URL参数获取
- if (page === null) {
- const urlParams = new URLSearchParams(window.location.search);
- const pageParam = urlParams.get('page');
- page = pageParam ? parseInt(pageParam) : 1;
- }
-
- // 构建请求URL(如果有年级筛选或页码,添加参数)
- let apiUrl = `/api/questions_by_kp/${encodeURIComponent(kpCode)}`;
- const params = [];
- if (currentGradeFilter !== null) {
- params.push(`grade=${currentGradeFilter}`);
- }
- if (page > 1) {
- params.push(`page=${page}`);
- }
- if (params.length > 0) {
- apiUrl += '?' + params.join('&');
- }
-
- // 请求题目列表
- fetch(apiUrl)
- .then(response => response.json())
- .then(data => {
- if (!data.success) {
- throw new Error(data.error || '加载失败');
- }
-
- const questions = data.questions || [];
- const kpName = data.kp_name || kpCode;
-
- // 获取统计数据(即使没有题目也要显示)
- const stats = data.stats || {};
- const auditStats = stats.audit || {pass: 0, fail: 0, pending: 0, pass_rate: 0, audit_rate: 0};
- const difficultyStats = stats.difficulty || {jichu: 0, tifen: 0, peiyou: 0, unknown: 0};
-
- // 构建录入题目URL
- const addQuestionUrl = `/add_question?kp_code=${encodeURIComponent(kpCode)}`;
-
- // 渲染题目列表
- let html = '';
-
- // 如果是"其他题目",只显示按钮,不显示横幅和统计数据
- if (kpCode === 'null' || kpCode === '') {
- html = `
- <div class="mb-6 flex items-center gap-2 flex-wrap">
- <button onclick="showAddQuestionModal(null, null)"
- 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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
- </svg>
- <span>录入题目</span>
- </button>
- <button onclick="showBatchImportModal(null, null)"
- 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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <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"/>
- </svg>
- <span>批量导入</span>
- </button>
- </div>
- `;
- } else {
- // 其他知识点显示完整的横幅和统计数据
- html = `
- <div class="mb-6">
- <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">
- <div class="mb-4">
- <div class="flex items-center justify-between mb-3">
- <div class="flex-1 min-w-0">
- <h2 class="text-xl font-bold mb-2 truncate">${kpName}</h2>
- <p class="text-sm text-white/80">共 ${stats.total || questions.length} 道题目</p>
- </div>
- </div>
- <div class="flex items-center gap-2 flex-wrap">
- <button onclick="showAddQuestionModal('${kpCode}', '${kpName}')"
- 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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
- </svg>
- <span>录入题目</span>
- </button>
- <button onclick="showBatchImportModal('${kpCode}', '${kpName}')"
- 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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <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"/>
- </svg>
- <span>批量导入</span>
- </button>
- </div>
- </div>
-
- <!-- 统计数据 -->
- <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4 pt-4 border-t border-white/20">
- <!-- 审核统计 -->
- <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
- <div class="text-xs text-white/70 mb-1">审核状态</div>
- <div class="space-y-1">
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">合格</span>
- <span class="font-bold text-green-200">${auditStats.pass || 0}</span>
- </div>
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">不合格</span>
- <span class="font-bold text-red-200">${auditStats.fail || 0}</span>
- </div>
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">待审核</span>
- <span class="font-bold text-orange-200">${auditStats.pending || 0}</span>
- </div>
- </div>
- </div>
-
- <!-- 难度统计 -->
- <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
- <div class="text-xs text-white/70 mb-1">难度分布</div>
- <div class="space-y-1">
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">筑基</span>
- <span class="font-bold text-green-200">${difficultyStats.jichu || 0}</span>
- </div>
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">提分</span>
- <span class="font-bold text-yellow-200">${difficultyStats.tifen || 0}</span>
- </div>
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">培优</span>
- <span class="font-bold text-orange-200">${difficultyStats.peiyou || 0}</span>
- </div>
- ${(difficultyStats.unknown || 0) > 0 ? `
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90">未设置</span>
- <span class="font-bold text-gray-300">${difficultyStats.unknown || 0}</span>
- </div>
- ` : ''}
- </div>
- </div>
-
- <!-- 审核率 -->
- <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
- <div class="text-xs text-white/70 mb-1">审核进度</div>
- <div class="space-y-2">
- <div>
- <div class="flex items-center justify-between text-xs mb-1">
- <span class="text-white/90">审核率</span>
- <span class="font-bold text-white">${auditStats.audit_rate || 0}%</span>
- </div>
- <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
- <div class="h-full bg-blue-300 rounded-full transition-all" style="width: ${auditStats.audit_rate || 0}%"></div>
- </div>
- </div>
- <div>
- <div class="flex items-center justify-between text-xs mb-1">
- <span class="text-white/90">通过率</span>
- <span class="font-bold text-white">${auditStats.pass_rate || 0}%</span>
- </div>
- <div class="w-full h-1.5 bg-white/20 rounded-full overflow-hidden">
- <div class="h-full bg-green-300 rounded-full transition-all" style="width: ${auditStats.pass_rate || 0}%"></div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 题型统计 -->
- <div class="bg-white/10 backdrop-blur-sm rounded-lg p-3">
- <div class="text-xs text-white/70 mb-1">题型分布</div>
- <div class="space-y-1 max-h-20 overflow-y-auto">
- ${Object.keys(stats.question_type || {}).length > 0 ? Object.entries(stats.question_type || {}).map(([type, count]) => {
- // 题型映射:英文转中文
- const typeMap = {
- 'choice': '选择题',
- 'fill': '填空题',
- 'answer': '解答题',
- '选择题': '选择题',
- '填空题': '填空题',
- '解答题': '解答题'
- };
- const typeName = typeMap[type] || type;
- return `
- <div class="flex items-center justify-between text-xs">
- <span class="text-white/90 truncate">${typeName}</span>
- <span class="font-bold text-white ml-2">${count}</span>
- </div>
- `;
- }).join('') : '<div class="text-xs text-white/60">暂无数据</div>'}
- </div>
- </div>
- </div>
- </div>
- `;
- }
-
- html += `<div class="space-y-3 ${kpCode === 'null' || kpCode === '' ? '' : 'mt-6'}">`;
-
- // 如果没有题目,显示提示信息
- if (questions.length === 0) {
- html += `
- <div class="apple-card p-12 text-center">
- <div class="text-gray-400 mb-4">
- <i class="ri-file-list-line text-6xl"></i>
- </div>
- <h3 class="text-lg font-bold text-gray-600 mb-2">该知识点下暂无题目</h3>
- <p class="text-sm text-gray-500 mb-6">点击上方"录入题目"或"批量导入"按钮开始添加题目</p>
- </div>
- `;
- } else {
- // 获取分页信息(从API返回)
- const pagination = data.pagination || {};
- const currentPage = pagination.page || 1;
- const totalPages = pagination.total_pages || 1;
- const totalCount = pagination.total_count || questions.length;
- const pageSize = pagination.page_size || 20;
- const startIndex = (currentPage - 1) * pageSize;
- const endIndex = Math.min(startIndex + pageSize, totalCount);
-
- // 有题目时,渲染题目列表
- questions.forEach(q => {
- // 审核状态
- let auditBadge = '';
- if (q.audit_reason === '合格') {
- auditBadge = '<span class="bg-green-100 text-green-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">合格</span>';
- } else if (q.audit_reason === '不合格') {
- auditBadge = '<span class="bg-red-100 text-red-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">不合格</span>';
- } else {
- auditBadge = '<span class="bg-orange-100 text-orange-700 px-2 py-0.5 rounded text-xs font-bold whitespace-nowrap">待审核</span>';
- }
-
- // 难度标签
- let difficultyBadge = '';
- if (q.difficulty !== null && q.difficulty !== undefined) {
- const diff = parseFloat(q.difficulty);
- if (diff === 0.2 || Math.abs(diff - 0.2) < 0.1) {
- 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>';
- } else if (diff === 0.4 || Math.abs(diff - 0.4) < 0.1) {
- 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>';
- } else if (diff === 0.7 || Math.abs(diff - 0.7) < 0.1) {
- 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>';
- }
- }
-
- // 题型标签
- const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
- const questionTypeText = typeMap[q.question_type] || q.question_type || '未分类';
-
- // 年级标签
- let gradeBadge = '';
- if (q.grade !== null && q.grade !== undefined) {
- const grade = parseInt(q.grade);
- if (grade === 1) {
- 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>';
- } else if (grade === 2) {
- 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>';
- } else if (grade === 3) {
- 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>';
- }
- }
-
- // 题干预览(去除HTML标签,只显示文本)
- const stemText = (q.stem || '').replace(/<[^>]*>/g, '').substring(0, 150);
-
- html += `
- <a href="/detail/${q.question_code}${currentKpCode ? '?kp_code=' + encodeURIComponent(currentKpCode) : ''}"
- class="apple-card p-4 block group hover:shadow-lg transition-all border-l-4 border-transparent hover:border-blue-500">
- <div class="flex items-center gap-4">
- <!-- 左侧:题号 -->
- <div class="flex-shrink-0">
- <span class="text-xs font-mono text-gray-500 bg-gray-100 px-3 py-1.5 rounded font-semibold">${q.question_code}</span>
- </div>
-
- <!-- 中间:题干内容 -->
- <div class="flex-1 min-w-0">
- <div class="text-sm text-gray-800 group-hover:text-blue-600 transition-colors line-clamp-1">
- ${stemText}${stemText.length >= 150 ? '...' : ''}
- </div>
- </div>
- <!-- 右侧:标签和操作 -->
- <div class="flex items-center gap-3 flex-shrink-0">
- <span class="text-xs text-gray-500 bg-gray-50 px-2 py-1 rounded">${questionTypeText}</span>
- ${gradeBadge}
- ${difficultyBadge}
- ${auditBadge}
- <span class="text-xs text-blue-600 font-medium opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">查看详情 →</span>
- </div>
- </div>
- </a>
- `;
- });
-
- // 添加翻页控件
- if (totalPages > 1) {
- html += `
- <div class="mt-6 flex items-center justify-between">
- <div class="text-sm text-gray-600">
- 显示第 ${startIndex + 1}-${endIndex} 题,共 ${totalCount} 题
- </div>
- <div class="flex items-center gap-2">
- <button
- onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage - 1})"
- ${currentPage === 1 ? 'disabled' : ''}
- class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
- currentPage === 1
- ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
- : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
- }">
- <i class="ri-arrow-left-s-line"></i> 上一页
- </button>
-
- <div class="flex items-center gap-1">
- ${Array.from({length: totalPages}, (_, i) => i + 1).map(page => {
- if (page === 1 || page === totalPages || (page >= currentPage - 2 && page <= currentPage + 2)) {
- return `
- <button
- onclick="loadQuestionsByKpPage('${kpCode}', ${page})"
- class="px-3 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
- page === currentPage
- ? 'border-blue-500 bg-blue-500 text-white'
- : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50'
- }">
- ${page}
- </button>
- `;
- } else if (page === currentPage - 3 || page === currentPage + 3) {
- return '<span class="px-2 text-gray-400">...</span>';
- }
- return '';
- }).join('')}
- </div>
-
- <button
- onclick="loadQuestionsByKpPage('${kpCode}', ${currentPage + 1})"
- ${currentPage === totalPages ? 'disabled' : ''}
- class="px-4 py-2 rounded-lg text-sm font-medium transition-all border-2 ${
- currentPage === totalPages
- ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
- : 'border-blue-300 bg-white text-blue-700 hover:bg-blue-50'
- }">
- 下一页 <i class="ri-arrow-right-s-line"></i>
- </button>
- </div>
- </div>
- `;
- }
- }
-
- html += '</div>';
- container.innerHTML = html;
-
- // 渲染数学公式
- if (window.renderMathInElement) {
- container.querySelectorAll('.math-render').forEach(el => {
- try {
- window.renderMathInElement(el, {
- delimiters: [
- {left: "$$", right: "$$", display: true},
- {left: "$", right: "$", display: false},
- {left: "\\(", right: "\\)", display: false},
- {left: "\\[", right: "\\]", display: true}
- ],
- throwOnError: false
- });
- } catch (e) {
- console.warn('数学公式渲染失败:', e);
- }
- });
- }
- })
- .catch(error => {
- container.innerHTML = `
- <div class="apple-card p-12 text-center">
- <div class="text-red-400 mb-4">
- <i class="ri-error-warning-line text-6xl"></i>
- </div>
- <h3 class="text-lg font-bold text-gray-600 mb-2">加载失败</h3>
- <p class="text-sm text-red-500">${error.message || '未知错误'}</p>
- </div>
- `;
- });
- }
- // 页面加载时,设置进度条宽度和初始化知识点目录
- document.addEventListener('DOMContentLoaded', function() {
- // 设置进度条宽度
- document.querySelectorAll('.progress-gradient[data-width]').forEach(function(el) {
- const width = parseFloat(el.getAttribute('data-width')) || 0;
- el.style.width = width + '%';
- });
-
- // 初始化知识点目录:默认展开第一级节点
- const firstLevelNodes = document.querySelectorAll('.kp-node-item[data-level="0"]');
- firstLevelNodes.forEach(node => {
- const kpCode = node.getAttribute('data-kp-code');
- const expandBtn = node.querySelector('.kp-expand-btn');
- if (expandBtn && expandBtn.getAttribute('data-expanded') === 'true') {
- const childrenContainer = document.getElementById(`kp-children-${kpCode}`);
- if (childrenContainer) {
- childrenContainer.classList.remove('hidden');
- }
- }
- });
-
- // 如果 URL 中有锚点(hash),自动滚动到对应知识点
- const hash = window.location.hash;
- if (hash && hash.startsWith('#kp-')) {
- const targetId = hash.substring(1); // 去掉 # 号
- const targetElement = document.getElementById(targetId);
- if (targetElement) {
- // 延迟一下,确保页面完全渲染
- setTimeout(() => {
- targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
- // 高亮一下,让用户知道定位到了
- targetElement.style.transition = 'box-shadow 0.3s';
- targetElement.style.boxShadow = '0 0 20px rgba(59, 130, 246, 0.5)';
- setTimeout(() => {
- targetElement.style.boxShadow = '';
- }, 2000);
- }, 100);
- }
- }
-
- // 如果 URL 中有 kp_code 参数,自动加载对应知识点的题目列表
- const urlParams = new URLSearchParams(window.location.search);
- const kpCode = urlParams.get('kp_code');
- if (kpCode) {
- // 延迟一下,确保页面完全渲染
- setTimeout(() => {
- // 查找对应的知识点链接
- const kpLink = document.querySelector(`.kp-link[data-kp-code="${kpCode}"]`);
- if (kpLink) {
- // 获取知识点名称(从链接文本或data属性)
- const kpName = kpLink.getAttribute('data-kp-name') || kpLink.textContent.trim() || kpCode;
-
- // 展开父节点(如果需要)
- let parent = kpLink.closest('.kp-node-item');
- while (parent) {
- const parentKpCode = parent.getAttribute('data-kp-code');
- if (parentKpCode) {
- const expandBtn = parent.querySelector('.kp-expand-btn');
- if (expandBtn && expandBtn.getAttribute('data-expanded') === 'false') {
- toggleKpNode(parentKpCode);
- }
- }
- parent = parent.parentElement?.closest('.kp-node-item');
- }
-
- // 滚动到知识点链接
- setTimeout(() => {
- kpLink.scrollIntoView({ behavior: 'smooth', block: 'center' });
- // 加载题目列表
- loadQuestionsByKp(kpCode, kpName, kpLink);
- }, 200);
- } else {
- // 如果找不到链接,直接加载题目(可能是通过API获取知识点名称)
- fetch(`/api/questions_by_kp/${encodeURIComponent(kpCode)}`)
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- const kpName = data.kp_name || kpCode;
- loadQuestionsByKp(kpCode, kpName, null);
- }
- })
- .catch(error => {
- console.error('加载知识点信息失败:', error);
- // 即使失败也尝试加载题目列表
- loadQuestionsByKp(kpCode, kpCode, null);
- });
- }
- }, 300);
- }
- });
- // 显示添加知识点弹窗
- function showAddKpModal() {
- const modal = document.createElement('div');
- modal.id = 'add-kp-modal';
- 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;';
-
- const dialog = document.createElement('div');
- 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%;';
-
- const title = document.createElement('div');
- title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
- title.textContent = '添加知识点';
-
- // Chapter 选择
- const chapterLabel = document.createElement('label');
- chapterLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
- chapterLabel.textContent = '选择章节 *';
-
- const chapterSelect = document.createElement('select');
- chapterSelect.id = 'add-kp-chapter-select';
- 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;';
- chapterSelect.innerHTML = '<option value="">请选择章节</option>';
-
- // 填充章节选项(从知识点树形数据中提取)
- function extractChaptersFromTree(tree) {
- const chapters = [];
- tree.forEach(function(node) {
- chapters.push({
- id: node.kp_code,
- label: node.name
- });
- });
- return chapters;
- }
-
- const chapters = extractChaptersFromTree(kpTreeData || []);
- chapters.forEach(function(chapter) {
- const option = document.createElement('option');
- option.value = chapter.id;
- option.textContent = chapter.label;
- chapterSelect.appendChild(option);
- });
-
- // 类型选择
- const typeLabel = document.createElement('label');
- typeLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
- typeLabel.textContent = '添加类型 *';
-
- const typeSelect = document.createElement('select');
- typeSelect.id = 'add-kp-type-select';
- 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;';
- typeSelect.innerHTML = '<option value="">请选择类型</option><option value="section">节 (Section)</option><option value="subsection">小节 (Subsection)</option>';
-
- // Section 选择(仅当添加 subsection 时显示)
- const sectionLabel = document.createElement('label');
- sectionLabel.id = 'add-kp-section-label';
- sectionLabel.style.cssText = 'display:none;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
- sectionLabel.textContent = '选择节 *';
-
- const sectionSelect = document.createElement('select');
- sectionSelect.id = 'add-kp-section-select';
- 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;';
- sectionSelect.innerHTML = '<option value="">请选择节</option>';
-
- // 监听类型变化,更新 section 选择框
- typeSelect.addEventListener('change', function() {
- if (this.value === 'subsection') {
- sectionLabel.style.display = 'block';
- sectionSelect.style.display = 'block';
- sectionSelect.required = true;
- updateSectionOptions(chapterSelect.value);
- } else {
- sectionLabel.style.display = 'none';
- sectionSelect.style.display = 'none';
- sectionSelect.required = false;
- }
- });
-
- // 监听章节变化,更新 section 选项
- chapterSelect.addEventListener('change', function() {
- if (typeSelect.value === 'subsection') {
- updateSectionOptions(this.value);
- }
- });
-
- function updateSectionOptions(chapterId) {
- sectionSelect.innerHTML = '<option value="">请选择节</option>';
- if (!chapterId) return;
-
- // 从 kpTreeData 中查找对应章节的子节点(sections)
- function findNodeByCode(tree, code) {
- for (let node of tree) {
- if (node.kp_code === code) {
- return node;
- }
- if (node.children && node.children.length > 0) {
- const found = findNodeByCode(node.children, code);
- if (found) return found;
- }
- }
- return null;
- }
-
- const chapter = findNodeByCode(kpTreeData || [], chapterId);
- if (chapter && chapter.children) {
- chapter.children.forEach(function(section) {
- const option = document.createElement('option');
- option.value = section.kp_code;
- option.textContent = section.name;
- sectionSelect.appendChild(option);
- });
- }
- }
-
- // 名称输入
- const nameLabel = document.createElement('label');
- nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
- nameLabel.textContent = '名称 *';
-
- const nameInput = document.createElement('input');
- nameInput.type = 'text';
- nameInput.id = 'add-kp-name-input';
- nameInput.placeholder = '请输入名称';
- nameInput.required = true;
- 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;';
- nameInput.addEventListener('focus', function() {
- this.style.borderColor = '#3b82f6';
- });
- nameInput.addEventListener('blur', function() {
- this.style.borderColor = '#e5e7eb';
- });
-
- // 按钮容器
- const btnContainer = document.createElement('div');
- btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
-
- const cancelBtn = document.createElement('button');
- 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;';
- cancelBtn.textContent = '取消';
- cancelBtn.addEventListener('mouseenter', function() {
- this.style.background = '#e5e7eb';
- });
- cancelBtn.addEventListener('mouseleave', function() {
- this.style.background = '#f3f4f6';
- });
-
- const confirmBtn = document.createElement('button');
- 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;';
- confirmBtn.textContent = '确定';
- confirmBtn.addEventListener('mouseenter', function() {
- this.style.background = '#2563eb';
- });
- confirmBtn.addEventListener('mouseleave', function() {
- this.style.background = '#3b82f6';
- });
-
- const handleCancel = () => {
- document.body.removeChild(modal);
- };
-
- const handleConfirm = async () => {
- const chapterId = chapterSelect.value;
- const type = typeSelect.value;
- const sectionId = sectionSelect.value;
- const name = nameInput.value.trim();
-
- if (!chapterId || !type || !name) {
- if (window.customAlert) {
- window.customAlert('请填写所有必填项!');
- } else {
- alert('请填写所有必填项!');
- }
- return;
- }
-
- if (type === 'subsection' && !sectionId) {
- if (window.customAlert) {
- window.customAlert('添加小节时必须选择节!');
- } else {
- alert('添加小节时必须选择节!');
- }
- return;
- }
-
- // 禁用按钮
- confirmBtn.disabled = true;
- confirmBtn.textContent = '添加中...';
-
- try {
- const response = await fetch('/add_kp_node', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({
- chapter_id: parseInt(chapterId),
- type: type,
- section_id: sectionId ? parseInt(sectionId) : null,
- name: name
- })
- });
-
- const result = await response.json();
-
- if (result.success) {
- if (window.customAlert) {
- window.customAlert('添加成功!页面即将刷新。', () => {
- window.location.reload();
- });
- } else {
- alert('添加成功!');
- window.location.reload();
- }
- } else {
- if (window.customAlert) {
- window.customAlert('添加失败: ' + result.error);
- } else {
- alert('添加失败: ' + result.error);
- }
- confirmBtn.disabled = false;
- confirmBtn.textContent = '确定';
- }
- } catch (error) {
- console.error('添加失败:', error);
- if (window.customAlert) {
- window.customAlert('添加失败: ' + error.message);
- } else {
- alert('添加失败: ' + error.message);
- }
- confirmBtn.disabled = false;
- confirmBtn.textContent = '确定';
- }
- };
-
- cancelBtn.onclick = handleCancel;
- confirmBtn.onclick = handleConfirm;
-
- // 点击背景关闭
- modal.onclick = (e) => {
- if (e.target === modal) {
- handleCancel();
- }
- };
-
- dialog.appendChild(title);
- dialog.appendChild(chapterLabel);
- dialog.appendChild(chapterSelect);
- dialog.appendChild(typeLabel);
- dialog.appendChild(typeSelect);
- dialog.appendChild(sectionLabel);
- dialog.appendChild(sectionSelect);
- dialog.appendChild(nameLabel);
- dialog.appendChild(nameInput);
- btnContainer.appendChild(cancelBtn);
- btnContainer.appendChild(confirmBtn);
- dialog.appendChild(btnContainer);
- modal.appendChild(dialog);
- document.body.appendChild(modal);
-
- // 聚焦第一个输入框
- setTimeout(() => chapterSelect.focus(), 100);
- }
- // 显示编辑知识点名称弹窗
- function showEditKpModal(nodeId, nodeType, currentName) {
- const modal = document.createElement('div');
- modal.id = 'edit-kp-modal';
- 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;';
-
- const dialog = document.createElement('div');
- 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%;';
-
- const title = document.createElement('div');
- title.style.cssText = 'font-size:1.25rem;font-weight:bold;color:#333;margin-bottom:1.5rem;';
- const typeName = nodeType === 'chapter' ? '章节' : nodeType === 'section' ? '节' : '小节';
- title.textContent = '编辑' + typeName + '名称';
-
- // 名称输入
- const nameLabel = document.createElement('label');
- nameLabel.style.cssText = 'display:block;font-size:0.875rem;font-weight:600;color:#4b5563;margin-bottom:0.5rem;';
- nameLabel.textContent = '名称 *';
-
- const nameInput = document.createElement('input');
- nameInput.type = 'text';
- nameInput.id = 'edit-kp-name-input';
- nameInput.value = currentName;
- nameInput.required = true;
- 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;';
- nameInput.addEventListener('focus', function() {
- this.style.borderColor = '#3b82f6';
- });
- nameInput.addEventListener('blur', function() {
- this.style.borderColor = '#e5e7eb';
- });
-
- // 按钮容器
- const btnContainer = document.createElement('div');
- btnContainer.style.cssText = 'display:flex;gap:1rem;justify-content:flex-end;';
-
- const cancelBtn = document.createElement('button');
- 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;';
- cancelBtn.textContent = '取消';
- cancelBtn.addEventListener('mouseenter', function() {
- this.style.background = '#e5e7eb';
- });
- cancelBtn.addEventListener('mouseleave', function() {
- this.style.background = '#f3f4f6';
- });
-
- const confirmBtn = document.createElement('button');
- 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;';
- confirmBtn.textContent = '确定';
- confirmBtn.addEventListener('mouseenter', function() {
- this.style.background = '#2563eb';
- });
- confirmBtn.addEventListener('mouseleave', function() {
- this.style.background = '#3b82f6';
- });
-
- const handleCancel = () => {
- document.body.removeChild(modal);
- };
-
- const handleConfirm = async () => {
- const name = nameInput.value.trim();
-
- if (!name) {
- if (window.customAlert) {
- window.customAlert('请输入名称!');
- } else {
- alert('请输入名称!');
- }
- return;
- }
-
- // 禁用按钮
- confirmBtn.disabled = true;
- confirmBtn.textContent = '保存中...';
-
- try {
- const response = await fetch('/update_kp_node', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({
- node_id: nodeId,
- node_type: nodeType,
- name: name
- })
- });
-
- const result = await response.json();
-
- if (result.success) {
- // 更新页面上的显示
- const labelElement = document.getElementById(nodeType + '-label-' + nodeId);
- if (labelElement) {
- labelElement.textContent = name;
- }
-
- if (window.customAlert) {
- window.customAlert('修改成功!', () => {
- document.body.removeChild(modal);
- });
- } else {
- alert('修改成功!');
- document.body.removeChild(modal);
- }
- } else {
- if (window.customAlert) {
- window.customAlert('修改失败: ' + result.error);
- } else {
- alert('修改失败: ' + result.error);
- }
- confirmBtn.disabled = false;
- confirmBtn.textContent = '确定';
- }
- } catch (error) {
- console.error('修改失败:', error);
- if (window.customAlert) {
- window.customAlert('修改失败: ' + error.message);
- } else {
- alert('修改失败: ' + error.message);
- }
- confirmBtn.disabled = false;
- confirmBtn.textContent = '确定';
- }
- };
-
- cancelBtn.onclick = handleCancel;
- confirmBtn.onclick = handleConfirm;
-
- // 点击背景关闭
- modal.onclick = (e) => {
- if (e.target === modal) {
- handleCancel();
- }
- };
-
- // Enter 键确认
- nameInput.onkeypress = function(e) {
- if (e.key === 'Enter') {
- handleConfirm();
- }
- };
-
- dialog.appendChild(title);
- dialog.appendChild(nameLabel);
- dialog.appendChild(nameInput);
- btnContainer.appendChild(cancelBtn);
- btnContainer.appendChild(confirmBtn);
- dialog.appendChild(btnContainer);
- modal.appendChild(dialog);
- document.body.appendChild(modal);
-
- // 聚焦输入框并选中所有文本
- setTimeout(() => {
- nameInput.focus();
- nameInput.select();
- }, 100);
- }
- </script>
- <!-- 批量导入模态框 -->
- <div id="batch-import-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
- <div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl max-h-[95vh] overflow-hidden flex flex-col">
- <div class="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4 flex items-center justify-between">
- <h2 class="text-xl font-bold">批量导入题目</h2>
- <button onclick="hideBatchImportModal()" class="text-white hover:text-gray-200 text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
- </div>
- <div class="flex-1 overflow-hidden flex flex-col">
- <!-- JSON输入区域 -->
- <div class="p-6 border-b border-gray-200">
- <label class="block text-sm font-bold text-gray-700 mb-2">粘贴JSON数据(每道题以number字段切分)</label>
- <textarea id="batch-json-input"
- class="w-full h-32 p-3 border border-gray-300 rounded-lg font-mono text-xs focus:border-green-500 focus:ring-2 focus:ring-green-500/10 outline-none"
- placeholder='[{"number": "1", "stem": "...", "options": {"A": "...", "B": "..."}, "answer": "A", "question_type": "选择题", "solution": "..."}, ...]'
- oninput="handleBatchJsonInputChange()"></textarea>
- <p class="text-xs text-gray-500 mt-2">支持数组格式或单个对象格式,每道题必须包含number字段。粘贴后自动填充到下方表单</p>
- </div>
-
- <!-- 题目卡片区域 -->
- <div id="batch-preview" class="hidden flex-1 overflow-hidden flex flex-col">
- <!-- 题目导航 -->
- <div class="px-6 py-3 bg-gray-50 border-b border-gray-200 flex items-center justify-between">
- <div class="flex items-center gap-3">
- <button id="batch-prev-btn" onclick="switchBatchQuestion(-1)" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-3 py-1.5 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
- </svg>
- </button>
- <span class="text-sm font-medium text-gray-700">
- 第 <span id="current-question-index">1</span> / <span id="total-question-count">0</span> 题
- </span>
- <button id="batch-next-btn" onclick="switchBatchQuestion(1)" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-3 py-1.5 disabled:opacity-50 disabled:cursor-not-allowed">
- <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
- </svg>
- </button>
- </div>
- <div class="text-xs text-gray-500">题号: <span id="current-question-number">-</span></div>
- </div>
-
- <!-- 题目表单卡片容器 -->
- <div class="flex-1 overflow-y-auto p-6 relative">
- <div id="questions-list" class="relative"></div>
- </div>
- </div>
- </div>
-
- <!-- LaTeX 实时预览气泡 -->
- <div id="batch-latex-preview-bubble" class="fixed right-8 top-24 w-[420px] max-h-[75vh] bg-white rounded-2xl shadow-2xl border border-gray-200 z-[60] overflow-hidden flex flex-col hidden" style="box-shadow: 0 20px 60px rgba(0,0,0,0.15);">
- <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white px-4 py-3 flex items-center justify-between">
- <span class="text-sm font-bold">题目预览</span>
- <button type="button" onclick="hideBatchPreviewBubble()" class="text-white hover:text-gray-200 text-xl leading-none w-6 h-6 flex items-center justify-center rounded-full hover:bg-white/20 transition-colors">×</button>
- </div>
- <div id="batch-latex-preview-content" class="flex-1 p-6 overflow-y-auto bg-gray-50 text-base leading-relaxed" style="min-height: 200px;">
- <p class="text-sm text-gray-400 text-center">题目预览</p>
- </div>
- </div>
- <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end gap-3">
- <button onclick="hideBatchImportModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
- <button id="batch-submit-btn" onclick="submitBatchQuestions()" class="btn-apple bg-gradient-to-r from-green-600 to-emerald-600 text-white hover:from-green-700 hover:to-emerald-700 px-4 py-2 hidden">批量提交</button>
- </div>
- </div>
- </div>
- <!-- 录入题目模态框 -->
- <div id="add-question-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10002;">
- <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
- <div class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-6 py-4 flex items-center justify-between">
- <div>
- <h2 class="text-xl font-bold">录入新题目</h2>
- <div class="mt-1 flex items-center gap-2 text-sm text-white/90">
- <span id="add-question-kp-name" class="font-semibold"></span>
- <span class="text-white/70">|</span>
- <span class="font-mono text-xs bg-white/20 px-2 py-0.5 rounded" id="add-question-kp-code"></span>
- </div>
- </div>
- <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>
- </div>
- <div class="flex-1 overflow-hidden flex">
- <!-- 左侧表单区域 -->
- <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
- <form id="add-question-form" class="space-y-4">
- <p class="text-gray-400 text-xs mb-4">填写题目信息,保存后自动生成题号并创建新题目</p>
-
- <!-- 题型和难度选择 -->
- <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
- <select name="question_type" id="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">
- <option value="choice" selected>选择题</option>
- <option value="fill">填空题</option>
- <option value="answer">解答题</option>
- </select>
- </div>
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
- <div class="flex items-center gap-2">
- <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">
- <option value="">请选择难度</option>
- <option value="0.2">筑基</option>
- <option value="0.4">提分</option>
- <option value="0.7">培优</option>
- </select>
- <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">
- <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
- </svg>
- 难度评价
- </button>
- </div>
- </div>
- </div>
-
- <!-- 年级选择(所有题目必填) -->
- <div id="add-question-grade-section" class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
- <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">
- <option value="">请选择年级</option>
- <option value="1">小学</option>
- <option value="2">初中</option>
- <option value="3">高中</option>
- </select>
- </div>
-
- <!-- 题干编辑 -->
- <div class="space-y-2">
- <div class="flex items-center justify-between">
- <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
- <button type="button" id="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>
- </div>
- <textarea name="stem" id="add-question-stem" required
- class="w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm"
- placeholder="请输入题干内容或拖拽图片..."></textarea>
- </div>
-
- <!-- 选项编辑(仅选择题显示) -->
- <div id="add-options-section" class="space-y-2">
- <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
- <div class="grid grid-cols-2 gap-3">
- <div class="space-y-1">
- <label class="text-xs font-medium text-gray-600">选项 A</label>
- <div class="flex gap-1.5">
- <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>
- <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>
- </div>
- </div>
- <div class="space-y-1">
- <label class="text-xs font-medium text-gray-600">选项 B</label>
- <div class="flex gap-1.5">
- <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>
- <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>
- </div>
- </div>
- <div class="space-y-1">
- <label class="text-xs font-medium text-gray-600">选项 C</label>
- <div class="flex gap-1.5">
- <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>
- <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>
- </div>
- </div>
- <div class="space-y-1">
- <label class="text-xs font-medium text-gray-600">选项 D</label>
- <div class="flex gap-1.5">
- <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>
- <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>
- </div>
- </div>
- </div>
- <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
- <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式,可直接编辑)</label>
- <textarea id="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"
- placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'></textarea>
- </div>
- </div>
-
- <!-- 答案 -->
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
- <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">
- </div>
-
- <!-- 解析 -->
- <div class="space-y-2">
- <div class="flex items-center justify-between">
- <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
- <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>
- </div>
- <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>
- </div>
- </form>
- </div>
-
- <!-- 右侧预览区域 -->
- <div class="w-[420px] bg-gray-50 border-l border-gray-200 flex flex-col">
- <div id="add-question-preview-content" class="flex-1 p-6 overflow-y-auto bg-gray-50 text-base leading-relaxed">
- <p class="text-sm text-gray-400 text-center">题目预览</p>
- </div>
- </div>
- </div>
- <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-between">
- <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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <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"/>
- </svg>
- <span>查重检测</span>
- </button>
- <div class="flex items-center gap-3">
- <button onclick="hideAddQuestionModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-4 py-2">取消</button>
- <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>
- </div>
- </div>
- </div>
- </div>
- <!-- 题目比对弹窗 -->
- <div id="duplicate-comparison-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center" style="z-index: 10003;">
- <div class="bg-white rounded-2xl shadow-2xl w-full max-w-7xl max-h-[95vh] overflow-hidden flex flex-col">
- <div class="bg-gradient-to-r from-orange-600 to-red-600 text-white px-6 py-4 flex items-center justify-between">
- <div>
- <h2 class="text-xl font-bold">题目查重比对</h2>
- <p id="duplicate-similarity-info" class="text-sm text-white/90 mt-1"></p>
- </div>
- <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>
- </div>
- <div class="flex-1 overflow-hidden flex">
- <!-- 左侧:当前录入的题目 -->
- <div class="flex-1 overflow-y-auto p-6 border-r border-gray-200">
- <div class="mb-4">
- <h3 class="text-lg font-bold text-gray-800 mb-2">当前录入的题目</h3>
- </div>
- <div id="duplicate-current-question" class="space-y-4">
- <!-- 动态填充 -->
- </div>
- </div>
- <!-- 右侧:库中重复的题目 -->
- <div class="flex-1 overflow-y-auto p-6 bg-gray-50">
- <div class="mb-4">
- <h3 class="text-lg font-bold text-gray-800 mb-2">库中重复的题目</h3>
- </div>
- <div id="duplicate-existing-question" class="space-y-4">
- <!-- 动态填充 -->
- </div>
- </div>
- </div>
- <div class="border-t border-gray-200 px-6 py-4 flex items-center justify-end">
- <button onclick="hideDuplicateComparisonModal()" class="btn-apple bg-gray-100 text-gray-700 hover:bg-gray-200 px-6 py-2">关闭</button>
- </div>
- </div>
- </div>
- <script>
- // 批量导入相关变量
- let parsedQuestions = [];
- let currentBatchQuestionIndex = 0;
- let batchJsonSyncTimer = null;
- let isSyncingBatchFromJson = false;
- let currentBatchKpCode = null;
- let currentBatchKpName = null;
- function showBatchImportModal(kpCode, kpName) {
- // 处理 'null' 字符串,转换为 null
- if (kpCode === 'null' || kpCode === null) {
- currentBatchKpCode = null;
- currentBatchKpName = '其他题目(未关联知识点)';
- } else {
- currentBatchKpCode = kpCode;
- currentBatchKpName = kpName || '未指定知识点';
- }
- // 保存是否是"其他题目"的状态,用于后续渲染时显示年级选择
- window.isBatchOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
- document.getElementById('batch-import-modal').classList.remove('hidden');
- document.getElementById('batch-json-input').focus();
- }
- function hideBatchImportModal() {
- document.getElementById('batch-import-modal').classList.add('hidden');
- document.getElementById('batch-json-input').value = '';
- document.getElementById('batch-preview').classList.add('hidden');
- document.getElementById('batch-submit-btn').classList.add('hidden');
- parsedQuestions = [];
- currentBatchQuestionIndex = 0;
- }
- function handleBatchJsonInputChange() {
- const jsonInput = document.getElementById('batch-json-input');
- const jsonText = jsonInput.value.trim();
-
- if (jsonText) {
- try {
- JSON.parse(jsonText);
- jsonInput.classList.remove('border-red-500');
- jsonInput.classList.add('border-gray-300');
-
- clearTimeout(batchJsonSyncTimer);
- batchJsonSyncTimer = setTimeout(() => {
- if (!isSyncingBatchFromJson) {
- parseBatchJson();
- }
- }, 800);
- } catch (e) {
- jsonInput.classList.remove('border-gray-300');
- jsonInput.classList.add('border-red-500');
- }
- }
- }
- function parseBatchJson() {
- const jsonInput = document.getElementById('batch-json-input');
- const jsonText = jsonInput.value.trim();
-
- if (!jsonText) return;
-
- try {
- isSyncingBatchFromJson = true;
- let data = JSON.parse(jsonText);
- if (!Array.isArray(data)) {
- data = [data];
- }
-
- parsedQuestions = data.filter(q => q && q.number);
- if (parsedQuestions.length === 0) return;
-
- currentBatchQuestionIndex = 0;
- displayBatchPreview();
- } catch (error) {
- console.warn('JSON格式错误:', error);
- } finally {
- isSyncingBatchFromJson = false;
- }
- }
- function switchBatchQuestion(direction) {
- const newIndex = currentBatchQuestionIndex + direction;
- if (newIndex >= 0 && newIndex < parsedQuestions.length) {
- currentBatchQuestionIndex = newIndex;
- showBatchQuestion(currentBatchQuestionIndex);
- updateBatchNavigation();
- }
- }
- function updateBatchNavigation() {
- const prevBtn = document.getElementById('batch-prev-btn');
- const nextBtn = document.getElementById('batch-next-btn');
- const currentIndexSpan = document.getElementById('current-question-index');
- const totalCountSpan = document.getElementById('total-question-count');
- const questionNumberSpan = document.getElementById('current-question-number');
-
- if (prevBtn && nextBtn && currentIndexSpan && totalCountSpan) {
- currentIndexSpan.textContent = currentBatchQuestionIndex + 1;
- totalCountSpan.textContent = parsedQuestions.length;
- prevBtn.disabled = currentBatchQuestionIndex === 0;
- nextBtn.disabled = currentBatchQuestionIndex === parsedQuestions.length - 1;
- if (questionNumberSpan && parsedQuestions[currentBatchQuestionIndex]) {
- questionNumberSpan.textContent = parsedQuestions[currentBatchQuestionIndex].number || currentBatchQuestionIndex + 1;
- }
- }
- }
- function showBatchQuestion(index) {
- const questionsList = document.getElementById('questions-list');
- if (!questionsList) return;
-
- questionsList.querySelectorAll('.batch-question-card').forEach(card => card.classList.add('hidden'));
- const currentCard = document.getElementById(`batch-q-card-${index}`);
- if (currentCard) currentCard.classList.remove('hidden');
- updateBatchFullPreview();
- }
- function hideBatchPreviewBubble() {
- const bubble = document.getElementById('batch-latex-preview-bubble');
- if (bubble) bubble.classList.add('hidden');
- }
- function updateBatchFullPreview() {
- const previewContent = document.getElementById('batch-latex-preview-content');
- const bubble = document.getElementById('batch-latex-preview-bubble');
- if (!previewContent || !bubble) return;
-
- // 获取当前显示的题目卡片
- const currentCard = document.getElementById(`batch-q-card-${currentBatchQuestionIndex}`);
- if (!currentCard) return;
-
- // 收集当前题目的所有数据
- const stemTextarea = currentCard.querySelector('.batch-stem');
- const answerInput = currentCard.querySelector('.batch-answer');
- const solutionTextarea = currentCard.querySelector('.batch-solution');
- const optionsPreview = currentCard.querySelector('.batch-options-preview');
- const questionTypeSelect = currentCard.querySelector('.batch-question-type');
- const difficultySelect = currentCard.querySelector('.batch-difficulty');
-
- let html = '<div class="space-y-6">';
-
- // 题型和难度信息
- html += '<div class="border-b border-gray-200 pb-3 mb-3">';
- html += '<div class="flex items-center gap-3 text-sm">';
- const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
- const questionType = questionTypeSelect ? questionTypeSelect.value : 'choice';
- html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
- if (difficultySelect && difficultySelect.value) {
- const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
- 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>`;
- }
- html += '</div>';
- html += '</div>';
-
- // 题干预览
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
- const stem = stemTextarea ? stemTextarea.value : '';
- if (stem) {
- // 先提取图片标签,替换为占位符
- const imagePlaceholders = [];
- let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
- imagePlaceholders.push(url);
- return placeholder;
- });
-
- // 转义HTML
- let stemHtml = stemProcessed
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 将占位符替换为img标签
- imagePlaceholders.forEach((url, index) => {
- const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
- const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
- stemHtml = stemHtml.replace(placeholder, imgTag);
- });
-
- html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无内容</p>';
- }
- html += '</div>';
-
- // 选项预览(仅选择题)
- if (questionTypeSelect && questionTypeSelect.value === 'choice') {
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
-
- // 直接从选项输入框读取内容,确保图片标签能正确显示
- let hasOptions = false;
- ['A', 'B', 'C', 'D'].forEach(key => {
- const optionInput = currentCard.querySelector(`.batch-option-${key}`);
- const optionText = optionInput ? optionInput.value : '';
-
- if (optionText && optionText.trim()) {
- hasOptions = true;
- html += `<div class="mb-3">`;
- html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
-
- // 处理选项文本,支持图片标签
- // 先提取图片标签,替换为占位符
- const optionImagePlaceholders = [];
- let optionProcessed = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${optionImagePlaceholders.length}__`;
- optionImagePlaceholders.push(url);
- return placeholder;
- });
-
- // 转义HTML
- let optionHtml = optionProcessed
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 将占位符替换为img标签
- optionImagePlaceholders.forEach((url, index) => {
- const placeholder = `__OPTION_IMAGE_PLACEHOLDER_${index}__`;
- const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
- optionHtml = optionHtml.replace(placeholder, imgTag);
- });
-
- html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
- html += `</div>`;
- }
- });
-
- if (!hasOptions) {
- html += '<p class="text-xs text-gray-400">暂无选项</p>';
- }
- html += '</div>';
- }
-
- // 答案预览
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
- const answer = answerInput ? answerInput.value : '';
- if (answer) {
- html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer)}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无答案</p>';
- }
- html += '</div>';
-
- // 解析预览
- html += '<div>';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
- const solution = solutionTextarea ? solutionTextarea.value : '';
- if (solution) {
- // 先提取图片标签,替换为占位符
- const solutionImagePlaceholders = [];
- let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
- solutionImagePlaceholders.push(url);
- return placeholder;
- });
-
- // 转义HTML
- let solutionHtml = solutionProcessed
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 将占位符替换为img标签
- solutionImagePlaceholders.forEach((url, index) => {
- const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
- const imgTag = `<img src="${url}" class="max-w-[400px] max-h-[300px] w-auto h-auto my-2 rounded-lg mx-auto block" alt="题目图片" style="object-fit: contain;">`;
- solutionHtml = solutionHtml.replace(placeholder, imgTag);
- });
-
- html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无解析</p>';
- }
- html += '</div>';
-
- html += '</div>';
-
- previewContent.innerHTML = html;
-
- // 渲染LaTeX
- if (window.renderMathInElement) {
- try {
- window.renderMathInElement(previewContent, {
- delimiters: [
- {left: "$$", right: "$$", display: true},
- {left: "$", right: "$", display: false},
- {left: "\\(", right: "\\)", display: false},
- {left: "\\[", right: "\\]", display: true}
- ],
- throwOnError: false
- });
- } catch (e) {
- console.warn('LaTeX 渲染失败:', e);
- }
- }
-
- // 显示预览气泡
- bubble.classList.remove('hidden');
- }
- function displayBatchPreview() {
- const previewDiv = document.getElementById('batch-preview');
- const questionsList = document.getElementById('questions-list');
-
- previewDiv.classList.remove('hidden');
- document.getElementById('batch-submit-btn').classList.remove('hidden');
- questionsList.innerHTML = '';
-
- // 创建所有题目卡片(默认隐藏)
- parsedQuestions.forEach((q, index) => {
- const questionId = `batch-q-card-${index}`;
- const questionDiv = document.createElement('div');
- questionDiv.className = `batch-question-card apple-card p-6 space-y-4 ${index === 0 ? '' : 'hidden'}`;
- questionDiv.id = questionId;
- questionDiv.setAttribute('data-index', index);
-
- // 解析选项
- let optionsJson = '{}';
- let optionA = '', optionB = '', optionC = '', optionD = '';
- if (q.options && typeof q.options === 'object') {
- optionsJson = JSON.stringify(q.options, null, 2);
- optionA = q.options.A || '';
- optionB = q.options.B || '';
- optionC = q.options.C || '';
- optionD = q.options.D || '';
- }
-
- // 映射题型
- const questionType = mapQuestionType(q.question_type);
-
- questionDiv.innerHTML = `
- <div class="border-b border-gray-100 pb-3 mb-3">
- <div class="flex items-center gap-2">
- <span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">题号 ${q.number || index + 1}</span>
- </div>
- </div>
-
- <!-- 题型和难度选择 -->
- <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">题型</label>
- <select name="question_type" class="batch-question-type w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm">
- <option value="choice" ${questionType === 'choice' ? 'selected' : ''}>选择题</option>
- <option value="fill" ${questionType === 'fill' ? 'selected' : ''}>填空题</option>
- <option value="answer" ${questionType === 'answer' ? 'selected' : ''}>解答题</option>
- </select>
- </div>
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">难度</label>
- <div class="flex items-center gap-2">
- <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">
- <option value="">请选择难度</option>
- <option value="0.2" ${q.difficulty == 0.2 || q.difficulty == '0.2' ? 'selected' : ''}>筑基</option>
- <option value="0.4" ${q.difficulty == 0.4 || q.difficulty == '0.4' ? 'selected' : ''}>提分</option>
- <option value="0.7" ${q.difficulty == 0.7 || q.difficulty == '0.7' ? 'selected' : ''}>培优</option>
- </select>
- <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})">
- <svg class="w-3 h-3 inline-block mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
- </svg>
- 难度评价
- </button>
- </div>
- </div>
- </div>
-
- <!-- 年级选择(所有题目必填) -->
- <div class="batch-grade-section space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">年级 <span class="text-red-500">*</span></label>
- <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>
- <option value="">请选择年级</option>
- <option value="1" ${q.grade == 1 || q.grade == '1' || (currentGradeFilter === 1 && !q.grade) ? 'selected' : ''}>小学</option>
- <option value="2" ${q.grade == 2 || q.grade == '2' || (currentGradeFilter === 2 && !q.grade) ? 'selected' : ''}>初中</option>
- <option value="3" ${q.grade == 3 || q.grade == '3' || (currentGradeFilter === 3 && !q.grade) ? 'selected' : ''}>高中</option>
- </select>
- </div>
-
- <!-- 题干编辑 -->
- <div class="space-y-2">
- <div class="flex items-center justify-between">
- <label class="text-xs font-bold text-gray-400 uppercase">题干 <span class="text-red-500">*</span> (支持 LaTeX 和 HTML/SVG)</label>
- <button type="button" class="batch-upload-stem btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-3 h-fit" data-index="${index}">上传图片</button>
- </div>
- <textarea name="stem" class="batch-stem w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm"
- placeholder="请输入题干内容或拖拽图片..."
- data-index="${index}"
- data-type="stem"
- required>${escapeHtml(q.stem || '')}</textarea>
- </div>
-
- <!-- 选项编辑 -->
- <div class="batch-options-section space-y-2" style="display: ${questionType === 'choice' ? 'block' : 'none'}">
- <label class="text-xs font-bold text-gray-400 uppercase">选项</label>
- <div class="grid grid-cols-2 gap-3">
- <div class="option-item">
- <label class="text-xs font-medium text-gray-600 mb-1 block">选项 A</label>
- <div class="flex gap-1.5">
- <textarea class="batch-option-A flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
- placeholder="输入选项A的内容或拖拽图片..."
- data-index="${index}" data-option="A" data-type="option">${escapeHtml(optionA)}</textarea>
- <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="A">上传图片</button>
- </div>
- </div>
- <div class="option-item">
- <label class="text-xs font-medium text-gray-600 mb-1 block">选项 B</label>
- <div class="flex gap-1.5">
- <textarea class="batch-option-B flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
- placeholder="输入选项B的内容或拖拽图片..."
- data-index="${index}" data-option="B" data-type="option">${escapeHtml(optionB)}</textarea>
- <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="B">上传图片</button>
- </div>
- </div>
- <div class="option-item">
- <label class="text-xs font-medium text-gray-600 mb-1 block">选项 C</label>
- <div class="flex gap-1.5">
- <textarea class="batch-option-C flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
- placeholder="输入选项C的内容或拖拽图片..."
- data-index="${index}" data-option="C" data-type="option">${escapeHtml(optionC)}</textarea>
- <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="C">上传图片</button>
- </div>
- </div>
- <div class="option-item">
- <label class="text-xs font-medium text-gray-600 mb-1 block">选项 D</label>
- <div class="flex gap-1.5">
- <textarea class="batch-option-D flex-1 h-12 p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-1 focus:ring-blue-500/10 outline-none transition-all text-xs"
- placeholder="输入选项D的内容或拖拽图片..."
- data-index="${index}" data-option="D" data-type="option">${escapeHtml(optionD)}</textarea>
- <button type="button" class="batch-upload-option btn-apple bg-blue-600 text-white hover:bg-blue-700 text-xs py-1.5 px-2 h-fit self-start" data-index="${index}" data-option="D">上传图片</button>
- </div>
- </div>
- </div>
- <div class="mt-2 p-2 rounded-lg bg-gray-50 border border-gray-200">
- <label class="text-xs font-bold text-gray-600 mb-1 block">选项预览 (JSON格式,可直接编辑)</label>
- <textarea class="batch-options-preview w-full text-xs text-gray-700 font-mono bg-white p-2 rounded border border-gray-100 min-h-[80px] focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all resize-y"
- data-index="${index}"
- placeholder='{"A": "选项A内容", "B": "选项B内容", ...}'>${escapeHtml(optionsJson)}</textarea>
- </div>
- </div>
-
- <!-- 答案 -->
- <div class="space-y-1">
- <label class="text-xs font-bold text-gray-400 uppercase">正确答案</label>
- <input type="text" name="answer" class="batch-answer w-full p-2 rounded-lg bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all text-sm"
- placeholder="例如: A" value="${escapeHtml(q.answer || '')}">
- </div>
-
- <!-- 解析 -->
- <div class="space-y-2">
- <div class="flex items-center justify-between">
- <label class="text-xs font-bold text-gray-400 uppercase">解析</label>
- <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>
- </div>
- <textarea name="solution" class="batch-solution w-full h-32 p-3 rounded-xl bg-gray-50 border border-gray-100 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/10 outline-none transition-all font-mono text-sm"
- placeholder="请输入解析内容或拖拽图片..."
- data-index="${index}"
- data-type="solution">${escapeHtml(q.solution || '')}</textarea>
- </div>
-
- <!-- 查重检测按钮 -->
- <div class="pt-4 border-t border-gray-200">
- <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">
- <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <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"/>
- </svg>
- <span>查重检测</span>
- </button>
- </div>
- `;
-
- questionsList.appendChild(questionDiv);
-
- // 设置选项同步逻辑
- setupBatchQuestionEvents(index);
- });
-
- // 显示当前题并更新导航(不重置索引)
- showBatchQuestion(currentBatchQuestionIndex);
- updateBatchNavigation();
-
- // 初始化预览
- updateBatchFullPreview();
- }
- function escapeHtml(text) {
- if (!text) return '';
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
- }
- function mapQuestionType(type) {
- if (!type) return 'choice';
- const typeMap = {
- '选择题': 'choice', '填空题': 'fill', '解答题': 'answer',
- 'choice': 'choice', 'fill': 'fill', 'answer': 'answer'
- };
- return typeMap[type] || 'choice';
- }
- function setupBatchQuestionEvents(index) {
- // 题型变化时显示/隐藏选项
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- if (!questionDiv) return;
-
- const typeSelect = questionDiv.querySelector('.batch-question-type');
- const optionsSection = questionDiv.querySelector('.batch-options-section');
-
- typeSelect.addEventListener('change', function() {
- if (this.value === 'choice') {
- optionsSection.style.display = 'block';
- } else {
- optionsSection.style.display = 'none';
- }
- updateBatchFullPreview();
- });
-
- // 选项输入框同步到预览
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const input = questionDiv.querySelector(`.batch-option-${opt}`);
- if (input) {
- input.addEventListener('input', function() {
- updateBatchOptionsPreview(index);
- updateBatchFullPreview();
- });
- }
- });
-
- // 预览框同步到输入框
- const previewTextarea = questionDiv.querySelector('.batch-options-preview');
- if (previewTextarea) {
- previewTextarea.addEventListener('input', function() {
- syncBatchOptionsFromPreview(index);
- updateBatchFullPreview();
- });
- }
-
- // 题干、答案、解析字段变化时更新预览和拖拽上传
- const stemTextarea = questionDiv.querySelector('.batch-stem');
- if (stemTextarea) {
- stemTextarea.addEventListener('input', updateBatchFullPreview);
- // 拖拽上传功能
- stemTextarea.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- stemTextarea.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- stemTextarea.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadBatchImageFile(files[0], index, 'stem');
- }
- });
- }
-
- const answerInput = questionDiv.querySelector('.batch-answer');
- if (answerInput) {
- answerInput.addEventListener('input', updateBatchFullPreview);
- }
-
- const solutionTextarea = questionDiv.querySelector('.batch-solution');
- if (solutionTextarea) {
- solutionTextarea.addEventListener('input', updateBatchFullPreview);
- // 拖拽上传功能
- solutionTextarea.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- solutionTextarea.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- solutionTextarea.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadBatchImageFile(files[0], index, 'solution');
- }
- });
- }
-
- const difficultySelect = questionDiv.querySelector('.batch-difficulty');
- if (difficultySelect) {
- difficultySelect.addEventListener('change', updateBatchFullPreview);
- }
-
- // 图片上传按钮
- const uploadStemBtn = questionDiv.querySelector('.batch-upload-stem');
- if (uploadStemBtn) {
- uploadStemBtn.addEventListener('click', function() {
- uploadBatchImage(index, 'stem');
- });
- }
-
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const uploadBtn = questionDiv.querySelector(`.batch-upload-option[data-option="${opt}"]`);
- if (uploadBtn) {
- uploadBtn.addEventListener('click', function() {
- uploadBatchImage(index, 'option', opt);
- });
- }
- });
-
- const uploadSolutionBtn = questionDiv.querySelector('.batch-upload-solution');
- if (uploadSolutionBtn) {
- uploadSolutionBtn.addEventListener('click', function() {
- uploadBatchImage(index, 'solution');
- });
- }
-
- // 选项拖拽上传功能
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const optionInput = questionDiv.querySelector(`.batch-option-${opt}`);
- if (optionInput) {
- optionInput.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- optionInput.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- optionInput.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadBatchImageFile(files[0], index, 'option', opt);
- }
- });
- }
- });
-
- // 粘贴图片功能
- const allInputs = questionDiv.querySelectorAll('textarea, input[type="text"]');
- allInputs.forEach(input => {
- input.addEventListener('paste', async function(e) {
- const clipboardData = e.clipboardData || window.clipboardData;
- if (!clipboardData) {
- return;
- }
-
- // 检查是否有图片数据
- const items = clipboardData.items;
- if (!items) {
- return;
- }
-
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
-
- // 如果是图片类型
- if (item.type.indexOf('image') !== -1) {
- e.preventDefault(); // 阻止默认粘贴行为
-
- const file = item.getAsFile();
- if (file) {
- // 直接上传图片并插入到当前输入框
- await uploadBatchImageToInput(file, input, index);
- }
- break;
- }
- }
- });
- });
- }
- function updateBatchOptionsPreview(index) {
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- const previewTextarea = questionDiv.querySelector('.batch-options-preview');
- const optionsObj = {};
-
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const input = questionDiv.querySelector(`.batch-option-${opt}`);
- if (input && input.value.trim()) {
- optionsObj[opt] = input.value.trim();
- }
- });
-
- previewTextarea.value = JSON.stringify(optionsObj, null, 2);
- }
- function syncBatchOptionsFromPreview(index) {
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- const previewTextarea = questionDiv.querySelector('.batch-options-preview');
-
- try {
- const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const input = questionDiv.querySelector(`.batch-option-${opt}`);
- if (input) {
- input.value = optionsObj[opt] || '';
- }
- });
- } catch (error) {
- console.warn('选项预览 JSON 格式错误:', error);
- }
- }
- function uploadBatchImage(index, type, option = null) {
- const fileInput = document.createElement('input');
- fileInput.type = 'file';
- fileInput.accept = 'image/*';
- fileInput.style.display = 'none';
-
- fileInput.onchange = async (e) => {
- const file = e.target.files[0];
- if (!file) return;
-
- if (!file.type.startsWith('image/')) {
- if (window.customAlert) {
- window.customAlert('请选择图片文件!');
- } else {
- alert('请选择图片文件!');
- }
- return;
- }
-
- await uploadBatchImageFile(file, index, type, option);
- };
-
- document.body.appendChild(fileInput);
- fileInput.click();
- document.body.removeChild(fileInput);
- }
- // 通用图片上传函数:上传图片并插入到指定输入框
- async function uploadBatchImageToInput(file, inputElement, index) {
- if (!inputElement || !file) {
- return;
- }
-
- // 检查文件类型
- if (!file.type.startsWith('image/')) {
- if (window.customAlert) {
- window.customAlert('请选择图片文件!');
- } else {
- alert('请选择图片文件!');
- }
- return;
- }
-
- // 显示上传中状态
- const originalPlaceholder = inputElement.placeholder || '';
- const originalOpacity = inputElement.style.opacity || '1';
- inputElement.placeholder = '正在上传图片...';
- inputElement.style.opacity = '0.6';
- inputElement.disabled = true;
-
- try {
- const formData = new FormData();
- formData.append('file', file);
-
- const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
- method: 'POST',
- body: formData
- });
-
- if (!response.ok) {
- throw new Error(`上传失败: ${response.status} ${response.statusText}`);
- }
-
- const result = await response.json();
-
- // 检查返回结果,提取URL
- let imageUrl = null;
- if (typeof result === 'string') {
- imageUrl = result;
- } else if (result.url) {
- imageUrl = result.url;
- } else if (result.data && result.data.url) {
- imageUrl = result.data.url;
- } else if (result.data && typeof result.data === 'string') {
- imageUrl = result.data;
- } else {
- const resultStr = JSON.stringify(result);
- const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
- if (urlMatch) {
- imageUrl = urlMatch[0];
- }
- }
-
- if (!imageUrl) {
- throw new Error('接口返回格式异常,未找到图片URL。返回结果:' + JSON.stringify(result));
- }
-
- // 构建 image 标签
- const imageTag = `<image src="${imageUrl}"/>`;
-
- // 获取当前光标位置
- const cursorPos = inputElement.selectionStart || inputElement.value.length;
- const textBefore = inputElement.value.substring(0, cursorPos);
- const textAfter = inputElement.value.substring(cursorPos);
-
- // 插入 image 标签
- inputElement.value = textBefore + imageTag + textAfter;
-
- // 设置光标位置到插入内容之后
- const newCursorPos = cursorPos + imageTag.length;
- if (inputElement.setSelectionRange) {
- inputElement.setSelectionRange(newCursorPos, newCursorPos);
- }
- inputElement.focus();
-
- // 触发input事件,更新预览
- inputElement.dispatchEvent(new Event('input', { bubbles: true }));
-
- // 如果是选项输入框,更新选项预览
- if (inputElement.classList.contains('batch-option-A') ||
- inputElement.classList.contains('batch-option-B') ||
- inputElement.classList.contains('batch-option-C') ||
- inputElement.classList.contains('batch-option-D')) {
- updateBatchOptionsPreview(index);
- } else if (inputElement.classList.contains('batch-options-preview')) {
- // 如果是在选项预览框中粘贴,需要同步到各个选项输入框
- syncBatchOptionsFromPreview(index);
- }
-
- // 更新完整预览
- updateBatchFullPreview();
-
- } catch (error) {
- console.error('上传失败:', error);
- if (window.customAlert) {
- window.customAlert('图片上传失败: ' + error.message);
- } else {
- alert('图片上传失败: ' + error.message);
- }
- } finally {
- inputElement.placeholder = originalPlaceholder;
- inputElement.style.opacity = originalOpacity;
- inputElement.disabled = false;
- }
- }
- // 保留旧函数以兼容拖拽上传
- async function uploadBatchImageFile(file, index, type, option) {
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- if (!questionDiv) {
- questionDiv = document.querySelector(`[data-index="${index}"]`);
- }
- if (!questionDiv) return;
-
- let targetInput;
-
- if (type === 'stem') {
- targetInput = questionDiv.querySelector('.batch-stem');
- } else if (type === 'solution') {
- targetInput = questionDiv.querySelector('.batch-solution');
- } else if (type === 'answer') {
- targetInput = questionDiv.querySelector('.batch-answer');
- } else if (type === 'options-preview') {
- targetInput = questionDiv.querySelector('.batch-options-preview');
- } else if (type === 'option' && option) {
- targetInput = questionDiv.querySelector(`.batch-option-${option}`);
- }
-
- if (!targetInput) return;
-
- // 使用新的通用函数
- await uploadBatchImageToInput(file, targetInput, index);
- }
- // 批量导入的难度评价函数
- async function evaluateBatchDifficulty(index) {
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- if (!questionDiv) return;
-
- const btn = questionDiv.querySelector('.batch-evaluate-difficulty-btn');
- const difficultySelect = questionDiv.querySelector('.batch-difficulty');
-
- if (!btn || !difficultySelect) return;
-
- // 收集题目信息
- const stemTextarea = questionDiv.querySelector('.batch-stem');
- const answerInput = questionDiv.querySelector('.batch-answer');
- const solutionTextarea = questionDiv.querySelector('.batch-solution');
- const optionsPreview = questionDiv.querySelector('.batch-options-preview');
- const questionTypeSelect = questionDiv.querySelector('.batch-question-type');
-
- const stem = stemTextarea ? stemTextarea.value.trim() : '';
-
- if (!stem) {
- if (window.customAlert) {
- window.customAlert('请先填写题干内容');
- } else {
- alert('请先填写题干内容');
- }
- return;
- }
-
- // 构建请求数据
- const requestData = {
- stem: stem,
- answer: answerInput ? answerInput.value.trim() : '',
- solution: solutionTextarea ? solutionTextarea.value.trim() : '',
- question_type: questionTypeSelect ? questionTypeSelect.value : ''
- };
-
- // 处理选项
- if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
- try {
- requestData.options = JSON.parse(optionsPreview.value.trim());
- } catch (e) {
- console.warn('选项JSON解析失败:', e);
- }
- }
-
- // 显示加载状态
- const originalText = btn.innerHTML;
- btn.disabled = true;
- btn.innerHTML = '<svg class="w-3 h-3 inline-block mr-1 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>评价中...';
-
- try {
- const response = await fetch('/api/score', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(requestData)
- });
-
- if (!response.ok) {
- throw new Error(`请求失败: ${response.status} ${response.statusText}`);
- }
-
- const result = await response.json();
-
- // 处理返回的 difficulty_level
- let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
-
- // 映射难度等级到枚举值
- let difficultyValue = '';
-
- if (difficultyLevel !== undefined && difficultyLevel !== null) {
- const levelStr = String(difficultyLevel).trim();
-
- if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
- difficultyValue = '0.2';
- } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
- difficultyValue = '0.4';
- } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
- difficultyValue = '0.7';
- } else {
- const levelNum = parseFloat(levelStr);
- if (!isNaN(levelNum)) {
- if (Math.abs(levelNum - 0.2) < 0.1) {
- difficultyValue = '0.2';
- } else if (Math.abs(levelNum - 0.4) < 0.1) {
- difficultyValue = '0.4';
- } else if (Math.abs(levelNum - 0.7) < 0.1) {
- difficultyValue = '0.7';
- }
- }
- }
- }
-
- if (difficultyValue) {
- difficultySelect.value = difficultyValue;
- difficultySelect.dispatchEvent(new Event('change', { bubbles: true }));
- updateBatchFullPreview();
- } else {
- console.error('无法识别难度等级,完整返回结果:', result);
- if (window.customAlert) {
- window.customAlert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
- } else {
- alert('无法识别返回的难度等级。返回数据:' + JSON.stringify(result));
- }
- }
-
- } catch (error) {
- console.error('难度评价失败:', error);
- if (window.customAlert) {
- window.customAlert('难度评价失败: ' + error.message);
- } else {
- alert('难度评价失败: ' + error.message);
- }
- } finally {
- btn.disabled = false;
- btn.innerHTML = originalText;
- }
- }
- async function submitBatchQuestions() {
- const questionDivs = document.querySelectorAll('[data-index]');
- if (questionDivs.length === 0) {
- if (window.customAlert) {
- window.customAlert('没有可提交的题目');
- } else {
- alert('没有可提交的题目');
- }
- return;
- }
-
- const submitBtn = document.getElementById('batch-submit-btn');
- submitBtn.disabled = true;
- submitBtn.textContent = '提交中...';
-
- let successCount = 0;
- const userName = localStorage.getItem('user_name') || '';
-
- for (let i = 0; i < questionDivs.length; i++) {
- const questionDiv = questionDivs[i];
- const index = parseInt(questionDiv.getAttribute('data-index'));
-
- try {
- const stem = questionDiv.querySelector('.batch-stem').value.trim();
- if (!stem) continue;
-
- const questionData = {
- stem: stem,
- answer: questionDiv.querySelector('.batch-answer').value.trim(),
- solution: questionDiv.querySelector('.batch-solution').value.trim(),
- question_type: questionDiv.querySelector('.batch-question-type').value
- };
-
- // 只在有知识点代码时才添加 kp_code
- if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
- questionData.kp_code = currentBatchKpCode;
- }
-
- // 处理年级(所有题目必填)
- const gradeSelect = questionDiv.querySelector('.batch-grade');
- if (gradeSelect) {
- const grade = gradeSelect.value;
- if (!grade) {
- if (window.customAlert) {
- window.customAlert(`第 ${index + 1} 道题目:请选择年级`);
- } else {
- alert(`第 ${index + 1} 道题目:请选择年级`);
- }
- gradeSelect.focus();
- submitBtn.disabled = false;
- submitBtn.textContent = '批量提交';
- return;
- }
- questionData.grade = parseInt(grade);
- }
-
- const difficulty = questionDiv.querySelector('.batch-difficulty').value;
- if (difficulty) questionData.difficulty = parseFloat(difficulty);
-
- const optionsPreview = questionDiv.querySelector('.batch-options-preview');
- if (questionData.question_type === 'choice' && optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
- try {
- const optionsObj = JSON.parse(optionsPreview.value.trim());
- if (Object.keys(optionsObj).length > 0) {
- questionData.options = JSON.stringify(optionsObj);
- }
- } catch (e) {
- console.warn('选项JSON解析失败:', e);
- }
- }
-
- if (userName) questionData.create_by = userName;
-
- const response = await fetch('/create_question', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(questionData)
- });
-
- const result = await response.json();
- if (result.success) {
- successCount++;
- // 调用接口2确认不重复
- if (result.question_id) {
- try {
- await fetch('/api/confirm_repeat', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({
- questionId: result.question_id,
- isRepeat: 0
- })
- });
- } catch (error) {
- console.warn('确认查重结果失败:', error);
- }
- }
- }
- } catch (error) {
- console.error('提交失败:', error);
- }
- }
-
- submitBtn.disabled = false;
- submitBtn.textContent = '批量提交';
-
- const message = `成功导入 ${successCount} 道题`;
- if (window.customAlert) {
- window.customAlert(message, () => {
- if (successCount > 0) {
- // 只在有知识点代码时才刷新题目列表
- if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
- loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
- }
- hideBatchImportModal();
- }
- });
- } else {
- alert(message);
- if (successCount > 0) {
- // 只在有知识点代码时才刷新题目列表
- if (currentBatchKpCode && currentBatchKpCode !== 'null' && currentBatchKpCode !== '') {
- loadQuestionsByKp(currentBatchKpCode, currentBatchKpName);
- }
- hideBatchImportModal();
- }
- }
- }
- // ==================== 录入题目弹窗相关函数 ====================
- let currentAddQuestionKpCode = null;
- let currentAddQuestionKpName = null;
- function showAddQuestionModal(kpCode, kpName) {
- // 处理 'null' 字符串,转换为 null
- if (kpCode === 'null' || kpCode === null) {
- currentAddQuestionKpCode = null;
- currentAddQuestionKpName = null;
- } else {
- currentAddQuestionKpCode = kpCode;
- currentAddQuestionKpName = kpName;
- }
-
- // 判断是否是"其他题目"
- const isOtherQuestions = !kpCode || kpCode === 'null' || kpCode === '';
-
- // 设置知识点信息
- if (kpCode && kpCode !== 'null' && kpName && kpName !== 'null') {
- document.getElementById('add-question-kp-name').textContent = kpName;
- document.getElementById('add-question-kp-code').textContent = kpCode;
- } else {
- document.getElementById('add-question-kp-name').textContent = '其他题目(未关联知识点)';
- document.getElementById('add-question-kp-code').textContent = 'N/A';
- }
-
- // 重置表单
- document.getElementById('add-question-form').reset();
- document.getElementById('add-question-type').value = 'choice';
- document.getElementById('add-question-difficulty').value = '';
-
- // 如果有年级筛选,自动填充年级(但可以修改)
- if (document.getElementById('add-question-grade')) {
- if (currentGradeFilter !== null) {
- document.getElementById('add-question-grade').value = currentGradeFilter.toString();
- } else {
- document.getElementById('add-question-grade').value = '';
- }
- }
- ['A', 'B', 'C', 'D'].forEach(opt => {
- document.getElementById(`add-option-${opt}`).value = '';
- });
- // 重置选项预览框
- const optionsPreview = document.getElementById('add-options-preview');
- if (optionsPreview) {
- optionsPreview.value = '';
- }
-
- // 显示选项区域(默认选择题)
- document.getElementById('add-options-section').style.display = 'block';
-
- // 设置题型变化监听器
- const typeSelect = document.getElementById('add-question-type');
- const optionsSection = document.getElementById('add-options-section');
- typeSelect.onchange = function() {
- if (this.value === 'choice') {
- optionsSection.style.display = 'block';
- } else {
- optionsSection.style.display = 'none';
- }
- updateAddQuestionPreview();
- };
-
- // 设置预览更新监听器
- setupAddQuestionPreviewListeners();
-
- // 设置图片上传和粘贴功能
- setupAddQuestionImageUpload();
-
- // 显示弹窗
- document.getElementById('add-question-modal').classList.remove('hidden');
-
- // 更新预览和选项预览
- updateAddQuestionOptionsPreview();
- updateAddQuestionPreview();
-
- // 聚焦到题干输入框
- setTimeout(() => {
- document.getElementById('add-question-stem').focus();
- }, 100);
- }
- function hideAddQuestionPreview() {
- // 预览区域始终显示,这个函数可以用于未来扩展
- }
- // ==================== 图片上传和粘贴功能 ====================
- function setupAddQuestionImageUpload() {
- // 题干图片上传按钮
- const uploadStemBtn = document.getElementById('add-upload-stem-btn');
- if (uploadStemBtn) {
- uploadStemBtn.onclick = function() {
- const fileInput = document.createElement('input');
- fileInput.type = 'file';
- fileInput.accept = 'image/*';
- fileInput.style.display = 'none';
- fileInput.onchange = async (e) => {
- const file = e.target.files[0];
- if (file) {
- await uploadAddQuestionImageToInput(file, document.getElementById('add-question-stem'));
- }
- };
- document.body.appendChild(fileInput);
- fileInput.click();
- document.body.removeChild(fileInput);
- };
- }
-
- // 题干拖拽上传
- const stemTextarea = document.getElementById('add-question-stem');
- if (stemTextarea) {
- stemTextarea.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- stemTextarea.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- stemTextarea.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadAddQuestionImageToInput(files[0], this);
- }
- });
- }
-
- // 选项拖拽上传
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const optionInput = document.getElementById(`add-option-${opt}`);
- if (optionInput) {
- optionInput.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- optionInput.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- optionInput.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadAddQuestionImageToInput(files[0], this);
- }
- });
- }
- });
-
- // 解析拖拽上传
- const solutionTextarea = document.getElementById('add-question-solution');
- if (solutionTextarea) {
- solutionTextarea.addEventListener('dragover', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.add('border-blue-500', 'bg-blue-50');
- });
- solutionTextarea.addEventListener('dragleave', function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- });
- solutionTextarea.addEventListener('drop', async function(e) {
- e.preventDefault();
- e.stopPropagation();
- this.classList.remove('border-blue-500', 'bg-blue-50');
- const files = e.dataTransfer.files;
- if (files && files.length > 0 && files[0].type.startsWith('image/')) {
- await uploadAddQuestionImageToInput(files[0], this);
- }
- });
- }
-
- // 为所有输入框添加粘贴图片功能
- const allInputs = document.querySelectorAll('#add-question-form textarea, #add-question-form input[type="text"]');
- allInputs.forEach(input => {
- input.addEventListener('paste', async function(e) {
- const clipboardData = e.clipboardData || window.clipboardData;
- if (!clipboardData) {
- return;
- }
-
- const items = clipboardData.items;
- if (!items) {
- return;
- }
-
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
-
- // 如果是图片类型
- if (item.type.indexOf('image') !== -1) {
- e.preventDefault(); // 阻止默认粘贴行为
-
- const file = item.getAsFile();
- if (file) {
- // 上传图片并插入到当前输入框
- await uploadAddQuestionImageToInput(file, this);
- }
- break;
- }
- }
- });
- });
- }
- // 通用图片上传函数:上传图片并插入到指定输入框
- async function uploadAddQuestionImageToInput(file, inputElement) {
- if (!inputElement || !file) {
- return;
- }
-
- // 检查文件类型
- if (!file.type.startsWith('image/')) {
- if (window.customAlert) {
- window.customAlert('请选择图片文件!');
- } else {
- alert('请选择图片文件!');
- }
- return;
- }
-
- // 显示上传中状态
- const originalPlaceholder = inputElement.placeholder || '';
- const originalOpacity = inputElement.style.opacity || '1';
- inputElement.placeholder = '正在上传图片...';
- inputElement.style.opacity = '0.6';
- inputElement.disabled = true;
-
- try {
- const formData = new FormData();
- formData.append('file', file);
-
- const response = await fetch('https://crmapi.dcjxb.yunzhixue.cn/file/upload', {
- method: 'POST',
- body: formData
- });
-
- if (!response.ok) {
- throw new Error(`上传失败: ${response.status} ${response.statusText}`);
- }
-
- const result = await response.json();
-
- // 检查返回结果,提取URL
- let imageUrl = null;
- if (typeof result === 'string') {
- imageUrl = result;
- } else if (result.url) {
- imageUrl = result.url;
- } else if (result.data && result.data.url) {
- imageUrl = result.data.url;
- } else if (result.data && typeof result.data === 'string') {
- imageUrl = result.data;
- } else {
- const resultStr = JSON.stringify(result);
- const urlMatch = resultStr.match(/https?:\/\/[^\s"']+/);
- if (urlMatch) {
- imageUrl = urlMatch[0];
- }
- }
-
- if (!imageUrl) {
- throw new Error('接口返回格式异常,未找到图片URL。返回结果:' + JSON.stringify(result));
- }
-
- // 构建 image 标签
- const imageTag = `<image src="${imageUrl}"/>`;
-
- // 获取当前光标位置
- const cursorPos = inputElement.selectionStart || inputElement.value.length;
- const textBefore = inputElement.value.substring(0, cursorPos);
- const textAfter = inputElement.value.substring(cursorPos);
-
- // 插入 image 标签
- inputElement.value = textBefore + imageTag + textAfter;
-
- // 设置光标位置到插入内容之后
- const newCursorPos = cursorPos + imageTag.length;
- if (inputElement.setSelectionRange) {
- inputElement.setSelectionRange(newCursorPos, newCursorPos);
- }
- inputElement.focus();
-
- // 触发input事件,更新预览
- inputElement.dispatchEvent(new Event('input', { bubbles: true }));
-
- // 更新预览和选项预览
- updateAddQuestionOptionsPreview();
- updateAddQuestionPreview();
-
- } catch (error) {
- console.error('上传失败:', error);
- if (window.customAlert) {
- window.customAlert('图片上传失败: ' + error.message);
- } else {
- alert('图片上传失败: ' + error.message);
- }
- } finally {
- inputElement.placeholder = originalPlaceholder;
- inputElement.style.opacity = originalOpacity;
- inputElement.disabled = false;
- }
- }
- // 选项图片上传函数
- function uploadAddQuestionOptionImage(optionKey) {
- const fileInput = document.createElement('input');
- fileInput.type = 'file';
- fileInput.accept = 'image/*';
- fileInput.style.display = 'none';
- fileInput.onchange = async (e) => {
- const file = e.target.files[0];
- if (file) {
- await uploadAddQuestionImageToInput(file, document.getElementById(`add-option-${optionKey}`));
- }
- };
- document.body.appendChild(fileInput);
- fileInput.click();
- document.body.removeChild(fileInput);
- }
- // 解析图片上传函数
- function uploadAddQuestionSolutionImage() {
- const fileInput = document.createElement('input');
- fileInput.type = 'file';
- fileInput.accept = 'image/*';
- fileInput.style.display = 'none';
- fileInput.onchange = async (e) => {
- const file = e.target.files[0];
- if (file) {
- await uploadAddQuestionImageToInput(file, document.getElementById('add-question-solution'));
- }
- };
- document.body.appendChild(fileInput);
- fileInput.click();
- document.body.removeChild(fileInput);
- }
- function setupAddQuestionPreviewListeners() {
- // 题干预览
- const stemTextarea = document.getElementById('add-question-stem');
- if (stemTextarea) {
- stemTextarea.addEventListener('input', updateAddQuestionPreview);
- stemTextarea.addEventListener('focus', updateAddQuestionPreview);
- }
-
- // 选项预览 - 从各个选项输入框自动拼接成JSON
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const optionInput = document.getElementById(`add-option-${opt}`);
- if (optionInput) {
- optionInput.addEventListener('input', function() {
- updateAddQuestionOptionsPreview();
- updateAddQuestionPreview();
- });
- }
- });
-
- // 选项预览框 - 从JSON同步回各个选项输入框
- const optionsPreview = document.getElementById('add-options-preview');
- if (optionsPreview) {
- optionsPreview.addEventListener('input', function() {
- syncAddQuestionOptionsFromPreview();
- updateAddQuestionPreview();
- });
- }
-
- // 答案预览
- const answerInput = document.getElementById('add-question-answer');
- if (answerInput) {
- answerInput.addEventListener('input', updateAddQuestionPreview);
- }
-
- // 解析预览
- const solutionTextarea = document.getElementById('add-question-solution');
- if (solutionTextarea) {
- solutionTextarea.addEventListener('input', updateAddQuestionPreview);
- solutionTextarea.addEventListener('focus', updateAddQuestionPreview);
- }
-
- // 题型和难度变化
- const typeSelect = document.getElementById('add-question-type');
- if (typeSelect) {
- typeSelect.addEventListener('change', updateAddQuestionPreview);
- }
-
- const difficultySelect = document.getElementById('add-question-difficulty');
- if (difficultySelect) {
- difficultySelect.addEventListener('change', updateAddQuestionPreview);
- }
- }
- function updateAddQuestionPreview() {
- const previewContent = document.getElementById('add-question-preview-content');
- if (!previewContent) return;
-
- const stem = document.getElementById('add-question-stem')?.value || '';
- const answer = document.getElementById('add-question-answer')?.value || '';
- const solution = document.getElementById('add-question-solution')?.value || '';
- const questionType = document.getElementById('add-question-type')?.value || 'choice';
- const difficulty = document.getElementById('add-question-difficulty')?.value || '';
-
- let html = '<div class="space-y-6">';
-
- // 题型和难度信息
- html += '<div class="border-b border-gray-200 pb-3 mb-3">';
- html += '<div class="flex items-center gap-3 text-sm">';
- const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
- html += `<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-xs font-bold">${typeMap[questionType] || questionType}</span>`;
- if (difficulty) {
- const diffMap = {'0.2': '筑基', '0.4': '提分', '0.7': '培优'};
- html += `<span class="bg-purple-100 text-purple-700 px-2 py-0.5 rounded text-xs font-bold">${diffMap[difficulty] || difficulty}</span>`;
- }
- html += '</div>';
- html += '</div>';
-
- // 题干预览
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
- if (stem) {
- // 处理图片标签
- let stemHtml = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- 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;">`;
- });
-
- // 转义HTML(但保留图片标签)
- stemHtml = stemHtml
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 恢复图片标签
- stemHtml = stemHtml.replace(/<img[^&]*>/g, (match) => {
- return match.replace(/</g, '<').replace(/>/g, '>');
- });
-
- html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无内容</p>';
- }
- html += '</div>';
-
- // 选项预览(仅选择题)
- if (questionType === 'choice') {
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
- let hasOptions = false;
- ['A', 'B', 'C', 'D'].forEach(key => {
- const optionText = document.getElementById(`add-option-${key}`)?.value || '';
- if (optionText && optionText.trim()) {
- hasOptions = true;
- html += `<div class="mb-3">`;
- html += `<div class="text-xs font-bold text-gray-500 mb-1">选项 ${key}</div>`;
-
- // 处理选项文本,支持图片标签
- let optionHtml = optionText.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- 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;">`;
- });
-
- // 转义HTML
- optionHtml = optionHtml
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 恢复图片标签
- optionHtml = optionHtml.replace(/<img[^&]*>/g, (match) => {
- return match.replace(/</g, '<').replace(/>/g, '>');
- });
-
- html += `<div class="text-sm leading-relaxed">${optionHtml}</div>`;
- html += `</div>`;
- }
- });
- if (!hasOptions) {
- html += '<p class="text-xs text-gray-400">暂无选项</p>';
- }
- html += '</div>';
- }
-
- // 答案预览
- html += '<div class="border-b border-gray-200 pb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">正确答案</div>';
- if (answer) {
- html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer)}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无答案</p>';
- }
- html += '</div>';
-
- // 解析预览
- html += '<div>';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
- if (solution) {
- // 处理图片标签
- let solutionHtml = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- 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;">`;
- });
-
- // 转义HTML
- solutionHtml = solutionHtml
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 恢复图片标签
- solutionHtml = solutionHtml.replace(/<img[^&]*>/g, (match) => {
- return match.replace(/</g, '<').replace(/>/g, '>');
- });
-
- html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
- } else {
- html += '<p class="text-xs text-gray-400">暂无解析</p>';
- }
- html += '</div>';
-
- html += '</div>';
-
- previewContent.innerHTML = html;
-
- // 渲染LaTeX
- if (window.renderMathInElement) {
- try {
- window.renderMathInElement(previewContent, {
- delimiters: [
- {left: "$$", right: "$$", display: true},
- {left: "$", right: "$", display: false},
- {left: "\\(", right: "\\)", display: false},
- {left: "\\[", right: "\\]", display: true}
- ],
- throwOnError: false
- });
- } catch (e) {
- console.warn('LaTeX 渲染失败:', e);
- }
- }
- }
- // 更新单个录入题目的选项预览(从各个选项输入框自动拼接成JSON)
- function updateAddQuestionOptionsPreview() {
- const previewTextarea = document.getElementById('add-options-preview');
- if (!previewTextarea) return;
-
- const optionsObj = {};
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const input = document.getElementById(`add-option-${opt}`);
- if (input && input.value.trim()) {
- optionsObj[opt] = input.value.trim();
- }
- });
-
- previewTextarea.value = JSON.stringify(optionsObj, null, 2);
- }
- // 从选项预览框同步回各个选项输入框(单个录入题目)
- function syncAddQuestionOptionsFromPreview() {
- const previewTextarea = document.getElementById('add-options-preview');
- if (!previewTextarea) return;
-
- try {
- const optionsObj = JSON.parse(previewTextarea.value.trim() || '{}');
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const input = document.getElementById(`add-option-${opt}`);
- if (input) {
- input.value = optionsObj[opt] || '';
- }
- });
- } catch (error) {
- console.warn('选项预览 JSON 格式错误:', error);
- }
- }
- function hideAddQuestionModal() {
- document.getElementById('add-question-modal').classList.add('hidden');
- currentAddQuestionKpCode = null;
- currentAddQuestionKpName = null;
- }
- // ==================== 查重检测相关函数 ====================
- // 单独录题的查重检测
- async function checkDuplicateForAddQuestion() {
- const stem = document.getElementById('add-question-stem').value.trim();
-
- if (!stem) {
- if (window.customAlert) {
- window.customAlert('请先填写题干内容');
- } else {
- alert('请先填写题干内容');
- }
- return;
- }
-
- // 构建查重请求数据
- const checkData = {
- stem: stem,
- answer: document.getElementById('add-question-answer').value.trim(),
- solution: document.getElementById('add-question-solution').value.trim()
- };
-
- // 处理选项(仅选择题)
- const questionType = document.getElementById('add-question-type').value;
- if (questionType === 'choice') {
- const optionsObj = {};
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const value = document.getElementById(`add-option-${opt}`).value.trim();
- if (value) {
- optionsObj[opt] = value;
- }
- });
- if (Object.keys(optionsObj).length > 0) {
- checkData.options = JSON.stringify(optionsObj);
- }
- }
-
- await performDuplicateCheck(checkData, null);
- }
- // 批量导入的查重检测
- async function checkDuplicateForBatch(index) {
- const questionDiv = document.getElementById(`batch-q-card-${index}`);
- if (!questionDiv) return;
-
- const stem = questionDiv.querySelector('.batch-stem').value.trim();
- if (!stem) {
- if (window.customAlert) {
- window.customAlert('请先填写题干内容');
- } else {
- alert('请先填写题干内容');
- }
- return;
- }
-
- // 构建查重请求数据
- const checkData = {
- stem: stem,
- answer: questionDiv.querySelector('.batch-answer').value.trim(),
- solution: questionDiv.querySelector('.batch-solution').value.trim()
- };
-
- // 处理选项(仅选择题)
- const questionType = questionDiv.querySelector('.batch-question-type').value;
- if (questionType === 'choice') {
- const optionsPreview = questionDiv.querySelector('.batch-options-preview');
- if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
- try {
- checkData.options = optionsPreview.value.trim();
- } catch (e) {
- console.warn('选项JSON解析失败:', e);
- }
- }
- }
-
- await performDuplicateCheck(checkData, questionDiv);
- }
- // 关闭所有 customAlert 弹窗
- function closeAllCustomAlerts() {
- // 查找所有 customAlert 创建的模态框(通过样式特征识别)
- const modals = document.querySelectorAll('div[style*="position:fixed"][style*="z-index:9999"]');
- modals.forEach(modal => {
- // 检查是否是 customAlert 创建的(包含白色背景的 dialog)
- const dialog = modal.querySelector('div[style*="background:white"]');
- if (dialog) {
- document.body.removeChild(modal);
- }
- });
- }
- // 执行查重检测
- async function performDuplicateCheck(checkData, sourceElement) {
- let loadingModal = null;
- try {
- // 显示加载状态
- if (window.customAlert) {
- // 创建 loading 模式的弹窗(不显示按钮)
- loadingModal = document.createElement('div');
- 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;';
-
- const dialog = document.createElement('div');
- 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;';
-
- const msg = document.createElement('div');
- msg.style.cssText = 'margin-bottom:1.5rem;font-size:1rem;color:#333;';
- msg.textContent = '正在检测重复题目...';
-
- dialog.appendChild(msg);
- loadingModal.appendChild(dialog);
- document.body.appendChild(loadingModal);
- }
-
- const response = await fetch('/api/check_duplicate', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(checkData)
- });
-
- const result = await response.json();
-
- // 关闭加载弹窗
- if (loadingModal && loadingModal.parentNode) {
- document.body.removeChild(loadingModal);
- loadingModal = null;
- }
- closeAllCustomAlerts(); // 确保所有弹窗都关闭
-
- if (result.code === -1 && result.result && result.result.repeatIdList && result.result.repeatIdList.length > 0) {
- // 发现重复,显示比对弹窗
- const repeatInfo = result.result.repeatIdList[0];
- await showDuplicateComparison(checkData, repeatInfo, sourceElement);
- } else if (result.code === 0) {
- // 无重复
- if (window.customAlert) {
- window.customAlert('未发现重复题目,可以继续录入');
- } else {
- alert('未发现重复题目,可以继续录入');
- }
- } else {
- throw new Error('查重接口返回异常');
- }
- } catch (error) {
- // 关闭加载弹窗
- if (loadingModal && loadingModal.parentNode) {
- document.body.removeChild(loadingModal);
- loadingModal = null;
- }
- closeAllCustomAlerts(); // 确保所有弹窗都关闭
-
- console.error('查重检测失败:', error);
- if (window.customAlert) {
- window.customAlert('查重检测失败: ' + error.message);
- } else {
- alert('查重检测失败: ' + error.message);
- }
- }
- }
- // 显示比对弹窗
- async function showDuplicateComparison(currentQuestionData, repeatInfo, sourceElement) {
- const modal = document.getElementById('duplicate-comparison-modal');
- const similarityInfo = document.getElementById('duplicate-similarity-info');
- const currentQuestionDiv = document.getElementById('duplicate-current-question');
- const existingQuestionDiv = document.getElementById('duplicate-existing-question');
-
- // 显示相似度信息
- similarityInfo.textContent = repeatInfo.repeatMsg || '发现重复题目';
-
- // 渲染当前录入的题目
- currentQuestionDiv.innerHTML = renderQuestionForComparison(currentQuestionData, sourceElement);
-
- // 查询库中重复的题目
- try {
- const response = await fetch(`/api/question_by_id/${repeatInfo.questionsId}`);
- const result = await response.json();
-
- if (result.success && result.question) {
- existingQuestionDiv.innerHTML = renderQuestionForComparison(result.question, null, true);
- } else {
- existingQuestionDiv.innerHTML = '<p class="text-gray-500">无法加载重复题目详情</p>';
- }
- } catch (error) {
- console.error('加载重复题目失败:', error);
- existingQuestionDiv.innerHTML = '<p class="text-red-500">加载重复题目失败: ' + error.message + '</p>';
- }
-
- // 显示弹窗
- modal.classList.remove('hidden');
-
- // 渲染LaTeX
- setTimeout(() => {
- [currentQuestionDiv, existingQuestionDiv].forEach(container => {
- if (window.renderMathInElement) {
- try {
- window.renderMathInElement(container, {
- delimiters: [
- {left: "$$", right: "$$", display: true},
- {left: "$", right: "$", display: false},
- {left: "\\(", right: "\\)", display: false},
- {left: "\\[", right: "\\]", display: true}
- ],
- throwOnError: false
- });
- } catch (e) {
- console.warn('LaTeX 渲染失败:', e);
- }
- }
- });
- }, 100);
- }
- // 渲染题目用于比对
- function renderQuestionForComparison(questionData, sourceElement, isExisting = false) {
- let html = '';
-
- // 题型
- const typeMap = {'choice': '选择题', 'fill': '填空题', 'answer': '解答题'};
- const questionType = questionData.question_type || '';
- const typeText = typeMap[questionType] || questionType || '未分类';
-
- html += `<div class="mb-4">
- <span class="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs font-bold">${typeText}</span>
- </div>`;
-
- // 题干
- html += '<div class="mb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">题干</div>';
- let stem = '';
- if (isExisting) {
- stem = questionData.stem || '';
- } else if (sourceElement) {
- stem = sourceElement.querySelector('.batch-stem').value;
- } else {
- stem = document.getElementById('add-question-stem').value;
- }
-
- // 处理图片标签
- const imagePlaceholders = [];
- let stemProcessed = stem.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- const placeholder = `__IMAGE_PLACEHOLDER_${imagePlaceholders.length}__`;
- imagePlaceholders.push(url);
- return placeholder;
- });
-
- // 转义HTML
- let stemHtml = stemProcessed
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 替换图片占位符
- imagePlaceholders.forEach((url, index) => {
- const placeholder = `__IMAGE_PLACEHOLDER_${index}__`;
- 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;">`;
- stemHtml = stemHtml.replace(placeholder, imgTag);
- });
-
- html += `<div class="text-sm leading-relaxed">${stemHtml}</div>`;
- html += '</div>';
-
- // 选项(仅选择题)
- if (questionType === 'choice') {
- html += '<div class="mb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">选项</div>';
-
- let options = {};
- if (isExisting) {
- if (questionData.options) {
- try {
- options = typeof questionData.options === 'string' ? JSON.parse(questionData.options) : questionData.options;
- } catch (e) {
- options = {};
- }
- }
- } else if (sourceElement) {
- const optionsPreview = sourceElement.querySelector('.batch-options-preview');
- if (optionsPreview && optionsPreview.value.trim() && optionsPreview.value.trim() !== '{}') {
- try {
- options = JSON.parse(optionsPreview.value.trim());
- } catch (e) {
- options = {};
- }
- }
- } else {
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const value = document.getElementById(`add-option-${opt}`).value.trim();
- if (value) {
- options[opt] = value;
- }
- });
- }
-
- Object.entries(options).forEach(([key, value]) => {
- html += `<div class="mb-2">
- <span class="font-semibold text-gray-700">${key}:</span>
- <span class="text-sm text-gray-600 ml-2">${escapeHtml(value)}</span>
- </div>`;
- });
-
- html += '</div>';
- }
-
- // 答案
- html += '<div class="mb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">答案</div>';
- let answer = '';
- if (isExisting) {
- answer = questionData.answer || '';
- } else if (sourceElement) {
- answer = sourceElement.querySelector('.batch-answer').value;
- } else {
- answer = document.getElementById('add-question-answer').value;
- }
- html += `<div class="text-sm font-bold text-blue-600">${escapeHtml(answer) || '暂无'}</div>`;
- html += '</div>';
-
- // 解析
- html += '<div class="mb-4">';
- html += '<div class="text-xs font-bold text-gray-500 mb-2">解析</div>';
- let solution = '';
- if (isExisting) {
- solution = questionData.solution || '';
- } else if (sourceElement) {
- solution = sourceElement.querySelector('.batch-solution').value;
- } else {
- solution = document.getElementById('add-question-solution').value;
- }
-
- if (solution) {
- // 处理图片标签
- const solutionImagePlaceholders = [];
- let solutionProcessed = solution.replace(/<image\s+src="([^"]+)"\s*\/?>/gi, (match, url) => {
- const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${solutionImagePlaceholders.length}__`;
- solutionImagePlaceholders.push(url);
- return placeholder;
- });
-
- // 转义HTML
- let solutionHtml = solutionProcessed
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/\n/g, '<br>');
-
- // 替换图片占位符
- solutionImagePlaceholders.forEach((url, index) => {
- const placeholder = `__SOLUTION_IMAGE_PLACEHOLDER_${index}__`;
- 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;">`;
- solutionHtml = solutionHtml.replace(placeholder, imgTag);
- });
-
- html += `<div class="text-sm leading-relaxed">${solutionHtml}</div>`;
- } else {
- html += '<p class="text-sm text-gray-400">暂无解析</p>';
- }
- html += '</div>';
-
- return html;
- }
- // 关闭比对弹窗
- function hideDuplicateComparisonModal() {
- document.getElementById('duplicate-comparison-modal').classList.add('hidden');
- }
- async function submitAddQuestion() {
- const form = document.getElementById('add-question-form');
- const stem = document.getElementById('add-question-stem').value.trim();
-
- // 验证必填项
- if (!stem) {
- if (window.customAlert) {
- window.customAlert('请填写题干');
- } else {
- alert('请填写题干');
- }
- return;
- }
-
- // 构建提交数据
- const data = {
- stem: stem,
- answer: document.getElementById('add-question-answer').value.trim(),
- solution: document.getElementById('add-question-solution').value.trim(),
- question_type: document.getElementById('add-question-type').value
- };
-
- // 只在有知识点代码时才添加 kp_code
- if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '') {
- data.kp_code = currentAddQuestionKpCode;
- }
-
- // 处理年级(所有题目必填)
- const gradeSelect = document.getElementById('add-question-grade');
- if (gradeSelect) {
- const grade = gradeSelect.value;
- if (!grade) {
- if (window.customAlert) {
- window.customAlert('请选择年级');
- } else {
- alert('请选择年级');
- }
- gradeSelect.focus();
- return;
- }
- data.grade = parseInt(grade);
- }
-
- // 处理难度
- const difficulty = document.getElementById('add-question-difficulty').value;
- if (difficulty) {
- data.difficulty = parseFloat(difficulty);
- }
-
- // 处理选项(仅选择题)
- if (data.question_type === 'choice') {
- const optionsObj = {};
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const value = document.getElementById(`add-option-${opt}`).value.trim();
- if (value) {
- optionsObj[opt] = value;
- }
- });
- if (Object.keys(optionsObj).length > 0) {
- data.options = JSON.stringify(optionsObj);
- }
- }
-
- // 添加创建者
- const userName = localStorage.getItem('user_name');
- if (userName && userName.trim()) {
- data.create_by = userName.trim();
- }
-
- // 提交按钮状态
- const submitBtn = document.querySelector('#add-question-modal button[onclick="submitAddQuestion()"]');
- const originalText = submitBtn.textContent;
- submitBtn.disabled = true;
- submitBtn.textContent = '提交中...';
-
- try {
- const response = await fetch('/create_question', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(data)
- });
-
- const result = await response.json();
-
- if (result.success) {
- // 调用接口2确认不重复
- if (result.question_id) {
- try {
- await fetch('/api/confirm_repeat', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({
- questionId: result.question_id,
- isRepeat: 0
- })
- });
- } catch (error) {
- console.warn('确认查重结果失败:', error);
- }
- }
-
- if (window.customAlert) {
- window.customAlert('题目创建成功!', () => {
- // 只在有知识点代码时才刷新题目列表
- if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
- loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
- }
- hideAddQuestionModal();
- });
- } else {
- alert('题目创建成功!');
- // 只在有知识点代码时才刷新题目列表
- if (currentAddQuestionKpCode && currentAddQuestionKpCode !== 'null' && currentAddQuestionKpCode !== '' && currentAddQuestionKpName) {
- loadQuestionsByKp(currentAddQuestionKpCode, currentAddQuestionKpName);
- }
- hideAddQuestionModal();
- }
- } else {
- if (window.customAlert) {
- window.customAlert('创建失败: ' + (result.error || '未知错误'));
- } else {
- alert('创建失败: ' + (result.error || '未知错误'));
- }
- }
- } catch (error) {
- console.error('提交失败:', error);
- if (window.customAlert) {
- window.customAlert('提交失败: ' + error.message);
- } else {
- alert('提交失败: ' + error.message);
- }
- } finally {
- submitBtn.disabled = false;
- submitBtn.textContent = originalText;
- }
- }
- // 难度评价函数
- async function evaluateAddQuestionDifficulty() {
- const btn = document.getElementById('add-evaluate-difficulty-btn');
- const difficultySelect = document.getElementById('add-question-difficulty');
- const stem = document.getElementById('add-question-stem').value.trim();
-
- if (!stem) {
- if (window.customAlert) {
- window.customAlert('请先填写题干内容');
- } else {
- alert('请先填写题干内容');
- }
- return;
- }
-
- const requestData = {
- stem: stem,
- answer: document.getElementById('add-question-answer').value.trim(),
- solution: document.getElementById('add-question-solution').value.trim(),
- question_type: document.getElementById('add-question-type').value
- };
-
- // 处理选项
- if (requestData.question_type === 'choice') {
- const optionsObj = {};
- ['A', 'B', 'C', 'D'].forEach(opt => {
- const value = document.getElementById(`add-option-${opt}`).value.trim();
- if (value) {
- optionsObj[opt] = value;
- }
- });
- if (Object.keys(optionsObj).length > 0) {
- requestData.options = optionsObj;
- }
- }
-
- const originalText = btn.innerHTML;
- btn.disabled = true;
- btn.innerHTML = '<svg class="w-3 h-3 inline-block mr-1 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>评价中...';
-
- try {
- const response = await fetch('/api/score', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify(requestData)
- });
-
- if (!response.ok) {
- throw new Error(`请求失败: ${response.status}`);
- }
-
- const result = await response.json();
- let difficultyLevel = result.data?.difficulty_level || result.difficulty_level || result.difficulty || result.level;
-
- let difficultyValue = '';
- if (difficultyLevel !== undefined && difficultyLevel !== null) {
- const levelStr = String(difficultyLevel).trim();
- if (levelStr === '筑基' || levelStr === '0.2' || levelStr === '0.20') {
- difficultyValue = '0.2';
- } else if (levelStr === '提分' || levelStr === '0.4' || levelStr === '0.40') {
- difficultyValue = '0.4';
- } else if (levelStr === '培优' || levelStr === '0.7' || levelStr === '0.70') {
- difficultyValue = '0.7';
- } else {
- const levelNum = parseFloat(levelStr);
- if (!isNaN(levelNum)) {
- if (Math.abs(levelNum - 0.2) < 0.1) {
- difficultyValue = '0.2';
- } else if (Math.abs(levelNum - 0.4) < 0.1) {
- difficultyValue = '0.4';
- } else if (Math.abs(levelNum - 0.7) < 0.1) {
- difficultyValue = '0.7';
- }
- }
- }
- }
-
- if (difficultyValue) {
- difficultySelect.value = difficultyValue;
- } else {
- console.error('无法识别难度等级:', result);
- if (window.customAlert) {
- window.customAlert('无法识别返回的难度等级');
- }
- }
- } catch (error) {
- console.error('难度评价失败:', error);
- if (window.customAlert) {
- window.customAlert('难度评价失败: ' + error.message);
- } else {
- alert('难度评价失败: ' + error.message);
- }
- } finally {
- btn.disabled = false;
- btn.innerHTML = originalText;
- }
- }
- </script>
- {% endblock %}
|