LearningAnalyticsService.php 170 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370
  1. <?php
  2. namespace App\Services;
  3. use Exception;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\DB;
  7. use App\Services\ExamTypeStrategy;
  8. use App\Services\QuestionExpansionService;
  9. /**
  10. * 学习分析服务(本地化重构版)
  11. *
  12. * 原先调用外部 LearningAnalytics API (localhost:5016)
  13. * 现已重构为使用本地服务:MasteryCalculator、KnowledgeMasteryService 等
  14. */
  15. class LearningAnalyticsService
  16. {
  17. protected string $baseUrl;
  18. protected int $timeout = 10;
  19. protected ?QuestionExpansionService $questionExpansionService;
  20. protected ?MasteryCalculator $masteryCalculator;
  21. protected ?LocalAIAnalysisService $aiAnalysisService;
  22. public function __construct(
  23. ?QuestionExpansionService $questionExpansionService = null,
  24. ?MasteryCalculator $masteryCalculator = null,
  25. ?LocalAIAnalysisService $aiAnalysisService = null
  26. ) {
  27. // 保留baseUrl用于兼容,但不再实际调用
  28. $this->baseUrl = config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016'));
  29. $this->questionExpansionService = $questionExpansionService;
  30. $this->masteryCalculator = $masteryCalculator ?? app(MasteryCalculator::class);
  31. $this->aiAnalysisService = $aiAnalysisService ?? app(LocalAIAnalysisService::class);
  32. }
  33. /**
  34. * 获取学生掌握度(本地化)
  35. */
  36. public function getStudentMastery(string $studentId, string $kpCode = null): array
  37. {
  38. try {
  39. Log::info('LearningAnalyticsService: 获取学生掌握度 (本地)', [
  40. 'student_id' => $studentId,
  41. 'kp_code' => $kpCode
  42. ]);
  43. if ($kpCode) {
  44. // 获取特定知识点掌握度
  45. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  46. return [
  47. 'student_id' => $studentId,
  48. 'kp_code' => $kpCode,
  49. 'mastery_level' => $result['mastery'],
  50. 'confidence' => $result['confidence'],
  51. 'trend' => $result['trend'],
  52. 'total_attempts' => $result['total_attempts'],
  53. 'correct_attempts' => $result['correct_attempts'],
  54. ];
  55. }
  56. // 获取全部知识点掌握度概览
  57. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  58. return [
  59. 'student_id' => $studentId,
  60. 'total_knowledge_points' => $overview['total_knowledge_points'],
  61. 'average_mastery' => $overview['average_mastery_level'],
  62. 'mastered_count' => $overview['mastered_knowledge_points'],
  63. 'good_count' => $overview['good_knowledge_points'],
  64. 'weak_count' => $overview['weak_knowledge_points'],
  65. 'weak_list' => $overview['weak_knowledge_points_list'],
  66. 'details' => $overview['details'],
  67. ];
  68. } catch (\Exception $e) {
  69. Log::error('LearningAnalyticsService: 获取掌握度失败', [
  70. 'student_id' => $studentId,
  71. 'error' => $e->getMessage(),
  72. ]);
  73. return [
  74. 'error' => true,
  75. 'message' => $e->getMessage()
  76. ];
  77. }
  78. }
  79. /**
  80. * 更新学生掌握度(本地化)
  81. */
  82. public function updateMastery(array $data): array
  83. {
  84. try {
  85. $studentId = $data['student_id'];
  86. $kpCode = $data['kp_code'];
  87. $isCorrect = $data['is_correct'] ?? false;
  88. $difficulty = $data['difficulty_level'] ?? 0.5;
  89. Log::info('LearningAnalyticsService: 更新掌握度 (本地)', [
  90. 'student_id' => $studentId,
  91. 'kp_code' => $kpCode,
  92. ]);
  93. // 获取当前掌握度
  94. $currentMastery = DB::table('student_knowledge_mastery')
  95. ->where('student_id', $studentId)
  96. ->where('kp_code', $kpCode)
  97. ->value('mastery_level') ?? 0.5;
  98. // 使用LocalAIAnalysisService更新掌握度
  99. $result = $this->aiAnalysisService->updateMastery(
  100. $studentId,
  101. $kpCode,
  102. $currentMastery,
  103. $isCorrect,
  104. $difficulty
  105. );
  106. return [
  107. 'success' => true,
  108. 'data' => $result
  109. ];
  110. } catch (\Exception $e) {
  111. Log::error('LearningAnalyticsService: 更新掌握度失败', [
  112. 'data' => $data,
  113. 'error' => $e->getMessage(),
  114. ]);
  115. return [
  116. 'error' => true,
  117. 'message' => $e->getMessage()
  118. ];
  119. }
  120. }
  121. /**
  122. * 获取老师名下的所有学生
  123. */
  124. public function getTeacherStudents(string $teacherId): array
  125. {
  126. try {
  127. // 从本地MySQL获取学生
  128. $students = DB::table('students as s')
  129. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  130. ->where('s.teacher_id', $teacherId)
  131. ->select(
  132. 's.student_id',
  133. 's.name',
  134. 's.grade',
  135. 's.class_name',
  136. 'u.username',
  137. 'u.email'
  138. )
  139. ->get()
  140. ->toArray();
  141. return $students;
  142. } catch (\Exception $e) {
  143. Log::error('Get Teacher Students Error', [
  144. 'teacher_id' => $teacherId,
  145. 'error' => $e->getMessage()
  146. ]);
  147. return [];
  148. }
  149. }
  150. /**
  151. * 获取学生学习分析
  152. */
  153. public function getStudentAnalysis(string $studentId): array
  154. {
  155. // 从LearningAnalytics获取掌握度
  156. $masteryData = $this->getStudentMastery($studentId);
  157. // 从MySQL获取练习历史
  158. $exercises = DB::table('student_exercises')
  159. ->where('student_id', $studentId)
  160. ->orderBy('created_at', 'desc')
  161. ->limit(50)
  162. ->get()
  163. ->toArray();
  164. // 从MySQL获取掌握度记录
  165. $masteryRecords = DB::table('student_mastery')
  166. ->where('student_id', $studentId)
  167. ->get()
  168. ->toArray();
  169. return [
  170. 'student_id' => $studentId,
  171. 'mastery_from_la' => $masteryData,
  172. 'exercises' => $exercises,
  173. 'mastery_records' => $masteryRecords,
  174. 'total_exercises' => count($exercises),
  175. 'total_mastery_records' => count($masteryRecords),
  176. ];
  177. }
  178. /**
  179. * 生成学习测试数据
  180. */
  181. public function generateLearningData(string $studentId, array $params): array
  182. {
  183. $results = [];
  184. foreach ($params as $param) {
  185. $data = [
  186. 'student_id' => $studentId,
  187. 'kp_code' => $param['kp_code'],
  188. 'is_correct' => $param['is_correct'],
  189. 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
  190. 'difficulty_level' => $param['difficulty_level'] ?? 3,
  191. ];
  192. $result = $this->updateMastery($data);
  193. $results[] = $result;
  194. }
  195. return $results;
  196. }
  197. /**
  198. * 获取学习推荐
  199. */
  200. public function getLearningRecommendations(string $studentId): array
  201. {
  202. try {
  203. Log::info('LearningAnalytics Request: Get Learning Recommendations', [
  204. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend"
  205. ]);
  206. $response = Http::timeout($this->timeout)
  207. ->post($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
  208. Log::info('LearningAnalytics Response: Get Learning Recommendations', [
  209. 'status' => $response->status(),
  210. 'body' => $response->json()
  211. ]);
  212. if ($response->successful()) {
  213. return $response->json();
  214. }
  215. return ['error' => true, 'message' => 'Failed to fetch recommendations'];
  216. } catch (\Exception $e) {
  217. return ['error' => true, 'message' => $e->getMessage()];
  218. }
  219. }
  220. /**
  221. * 获取知识点列表(从知识图谱API)
  222. */
  223. public function getKnowledgePoints(array $filters = []): array
  224. {
  225. try {
  226. $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
  227. Log::info('LearningAnalytics Request: Get Knowledge Points', [
  228. 'url' => $kgBaseUrl . '/knowledge-points/',
  229. 'filters' => $filters
  230. ]);
  231. $response = Http::timeout($this->timeout)
  232. ->get($kgBaseUrl . '/knowledge-points/', $filters);
  233. Log::info('LearningAnalytics Response: Get Knowledge Points', [
  234. 'status' => $response->status(),
  235. 'count' => count($response->json()['data'] ?? [])
  236. ]);
  237. if ($response->successful()) {
  238. return $response->json()['data'] ?? [];
  239. }
  240. return [];
  241. } catch (\Exception $e) {
  242. Log::error('LearningAnalytics Knowledge Points Error', [
  243. 'error' => $e->getMessage()
  244. ]);
  245. return [];
  246. }
  247. }
  248. /**
  249. * 获取学生技能熟练度
  250. */
  251. public function getStudentSkillProficiency(string $studentId): array
  252. {
  253. try {
  254. Log::info('LearningAnalytics Request: Get Student Skill Proficiency', [
  255. 'url' => $this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}"
  256. ]);
  257. $response = Http::timeout($this->timeout)
  258. ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
  259. Log::info('LearningAnalytics Response: Get Student Skill Proficiency', [
  260. 'status' => $response->status(),
  261. 'body' => $response->json()
  262. ]);
  263. if ($response->successful()) {
  264. return $response->json();
  265. }
  266. Log::warning('LearningAnalytics Skill Proficiency API Error', [
  267. 'student_id' => $studentId,
  268. 'status' => $response->status(),
  269. 'response' => $response->body()
  270. ]);
  271. // API失败时返回空数据,不报错
  272. return [
  273. 'student_id' => $studentId,
  274. 'total_count' => 0,
  275. 'data' => []
  276. ];
  277. } catch (\Exception $e) {
  278. Log::warning('LearningAnalytics Skill Proficiency API Exception', [
  279. 'student_id' => $studentId,
  280. 'error' => $e->getMessage()
  281. ]);
  282. // 发生异常时返回空数据,不报错
  283. return [
  284. 'student_id' => $studentId,
  285. 'total_count' => 0,
  286. 'data' => []
  287. ];
  288. }
  289. }
  290. /**
  291. * 获取学生掌握度列表(别名方法)
  292. */
  293. public function getStudentMasteryList(string $studentId): array
  294. {
  295. return $this->getStudentMastery($studentId);
  296. }
  297. /**
  298. * 获取知识点依赖关系
  299. */
  300. public function getKnowledgeDependencies(): array
  301. {
  302. try {
  303. Log::info('LearningAnalytics Request: Get Knowledge Dependencies', [
  304. 'url' => $this->baseUrl . '/knowledge-dependencies/'
  305. ]);
  306. $response = Http::timeout($this->timeout)
  307. ->get($this->baseUrl . '/knowledge-dependencies/');
  308. Log::info('LearningAnalytics Response: Get Knowledge Dependencies', [
  309. 'status' => $response->status(),
  310. 'count' => count($response->json()['data'] ?? [])
  311. ]);
  312. if ($response->successful()) {
  313. return $response->json()['data'] ?? [];
  314. }
  315. return [];
  316. } catch (\Exception $e) {
  317. Log::error('LearningAnalytics Knowledge Dependencies Error', [
  318. 'error' => $e->getMessage()
  319. ]);
  320. return [];
  321. }
  322. }
  323. /**
  324. * 提交学生答题记录
  325. */
  326. public function submitAttempt(string $studentId, array $attemptData): array
  327. {
  328. try {
  329. Log::info('LearningAnalytics Request: Submit Attempt', [
  330. 'url' => $this->baseUrl . "/api/v1/attempts/student/{$studentId}",
  331. 'data' => $attemptData
  332. ]);
  333. $response = Http::timeout($this->timeout)
  334. ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
  335. Log::info('LearningAnalytics Response: Submit Attempt', [
  336. 'status' => $response->status(),
  337. 'body' => $response->json()
  338. ]);
  339. if ($response->successful()) {
  340. return $response->json();
  341. }
  342. Log::error('Submit Attempt Error', [
  343. 'student_id' => $studentId,
  344. 'data' => $attemptData,
  345. 'status' => $response->status(),
  346. 'response' => $response->body()
  347. ]);
  348. return [
  349. 'error' => true,
  350. 'message' => 'Failed to submit attempt'
  351. ];
  352. } catch (\Exception $e) {
  353. Log::error('Submit Attempt Exception', [
  354. 'student_id' => $studentId,
  355. 'error' => $e->getMessage(),
  356. 'data' => $attemptData
  357. ]);
  358. return [
  359. 'error' => true,
  360. 'message' => $e->getMessage()
  361. ];
  362. }
  363. }
  364. /**
  365. * 批量提交学生答题记录
  366. */
  367. public function submitBatchAttempts(string $studentId, array $data): array
  368. {
  369. try {
  370. Log::info('LearningAnalytics Request: Submit Batch Attempts', [
  371. 'url' => $this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}",
  372. 'data_count' => count($data['answers'] ?? []),
  373. 'paper_id' => $data['paper_id'] ?? null
  374. ]);
  375. $response = Http::timeout($this->timeout)
  376. ->post($this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}", $data);
  377. Log::info('LearningAnalytics Response: Submit Batch Attempts', [
  378. 'status' => $response->status(),
  379. 'body' => $response->json()
  380. ]);
  381. if ($response->successful()) {
  382. return $response->json();
  383. }
  384. Log::error('Submit Batch Attempts Error', [
  385. 'student_id' => $studentId,
  386. 'data_count' => count($data['answers'] ?? []),
  387. 'status' => $response->status(),
  388. 'response' => $response->body()
  389. ]);
  390. return [
  391. 'error' => true,
  392. 'message' => 'Failed to submit batch attempts: ' . $response->body()
  393. ];
  394. } catch (\Exception $e) {
  395. Log::error('Submit Batch Attempts Exception', [
  396. 'student_id' => $studentId,
  397. 'error' => $e->getMessage()
  398. ]);
  399. return [
  400. 'error' => true,
  401. 'message' => $e->getMessage()
  402. ];
  403. }
  404. }
  405. /**
  406. * 提交OCR分析请求
  407. */
  408. public function submitOCRAnalysis(array $data): array
  409. {
  410. Log::warning('submitOCRAnalysis 已停用:分析项目已下线', [
  411. 'student_id' => $data['student_id'] ?? 'unknown',
  412. 'exam_id' => $data['exam_id'] ?? 'unknown',
  413. ]);
  414. return [
  415. 'success' => false,
  416. 'message' => 'analysis_api_disabled',
  417. ];
  418. }
  419. /**
  420. * 获取分析结果详情
  421. */
  422. public function getAnalysisResult(string $analysisId): array
  423. {
  424. Log::warning('getAnalysisResult 已停用:分析项目已下线', [
  425. 'analysis_id' => $analysisId,
  426. ]);
  427. return [
  428. 'success' => false,
  429. 'message' => 'analysis_api_disabled',
  430. ];
  431. }
  432. /**
  433. * 检查服务健康状态(本地化)
  434. */
  435. public function checkHealth(): bool
  436. {
  437. // 检查本地服务是否可用
  438. try {
  439. $this->masteryCalculator->getStudentMasteryOverview('test');
  440. return true;
  441. } catch (\Exception $e) {
  442. return false;
  443. }
  444. }
  445. /**
  446. * 获取学生掌握度概览(本地化)
  447. */
  448. public function getStudentMasteryOverview(string $studentId): array
  449. {
  450. try {
  451. // 直接使用MasteryCalculator
  452. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  453. return [
  454. 'total_knowledge_points' => $overview['total_knowledge_points'],
  455. 'average_mastery_level' => $overview['average_mastery_level'],
  456. 'mastered_knowledge_points' => $overview['mastered_knowledge_points'],
  457. 'good_knowledge_points' => $overview['good_knowledge_points'],
  458. 'weak_knowledge_points' => $overview['weak_knowledge_points'],
  459. 'weak_knowledge_points_list' => $overview['weak_knowledge_points_list'],
  460. 'details' => $overview['details']
  461. ];
  462. } catch (\Exception $e) {
  463. Log::error('Get Student Mastery Overview Error', [
  464. 'student_id' => $studentId,
  465. 'error' => $e->getMessage()
  466. ]);
  467. return [
  468. 'total_knowledge_points' => 0,
  469. 'average_mastery_level' => 0,
  470. 'mastered_knowledge_points' => 0,
  471. 'good_knowledge_points' => 0,
  472. 'weak_knowledge_points' => 0,
  473. 'weak_knowledge_points_list' => [],
  474. 'details' => []
  475. ];
  476. }
  477. }
  478. /**
  479. * 获取学生技能摘要
  480. */
  481. public function getStudentSkillSummary(string $studentId): array
  482. {
  483. try {
  484. $proficiency = $this->getStudentSkillProficiency($studentId);
  485. // 无论是否有error,都继续处理,返回空数据
  486. $data = $proficiency['data'] ?? [];
  487. $totalSkills = count($data);
  488. $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
  489. // 计算总答题数
  490. $totalQuestions = 0;
  491. foreach ($data as $skill) {
  492. $totalQuestions += $skill['total_questions_attempted'] ?? 0;
  493. }
  494. return [
  495. 'total_skills' => $totalSkills,
  496. 'average_proficiency_level' => $averageLevel,
  497. 'total_questions_attempted' => $totalQuestions,
  498. 'skill_list' => $data
  499. ];
  500. } catch (\Exception $e) {
  501. Log::warning('Get Student Skill Summary Error', [
  502. 'student_id' => $studentId,
  503. 'error' => $e->getMessage()
  504. ]);
  505. // 发生异常时返回空数据
  506. return [
  507. 'total_skills' => 0,
  508. 'average_proficiency_level' => 0,
  509. 'total_questions_attempted' => 0,
  510. 'skill_list' => []
  511. ];
  512. }
  513. }
  514. /**
  515. * 获取学生预测数据(本地化 - 已停用外部API)
  516. */
  517. public function getStudentPredictions(string $studentId, int $count = 5): array
  518. {
  519. // 外部API已停用,基于本地数据生成预测
  520. try {
  521. Log::info('LearningAnalyticsService: 获取学生预测 (本地)', [
  522. 'student_id' => $studentId,
  523. ]);
  524. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  525. $avgMastery = $overview['average_mastery_level'] ?? 0;
  526. // 基于掌握度生成简单预测
  527. $predictions = [];
  528. if ($avgMastery > 0) {
  529. $predictions[] = [
  530. 'type' => 'score_improvement',
  531. 'current_level' => round($avgMastery * 100),
  532. 'predicted_improvement' => rand(5, 15),
  533. 'confidence' => 0.75,
  534. ];
  535. }
  536. return [
  537. 'predictions' => $predictions
  538. ];
  539. } catch (\Exception $e) {
  540. Log::error('Get Student Predictions Error', [
  541. 'student_id' => $studentId,
  542. 'error' => $e->getMessage()
  543. ]);
  544. return [
  545. 'predictions' => []
  546. ];
  547. }
  548. }
  549. /**
  550. * 获取学生学习路径(本地化 - 已停用外部API)
  551. */
  552. public function getStudentLearningPaths(string $studentId, int $count = 3): array
  553. {
  554. // 外部API已停用,基于薄弱点生成学习路径
  555. try {
  556. Log::info('LearningAnalyticsService: 获取学习路径 (本地)', [
  557. 'student_id' => $studentId,
  558. ]);
  559. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  560. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  561. $paths = [];
  562. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  563. $paths[] = [
  564. 'kp_code' => $weak->kp_code ?? $weak['kp_code'] ?? '',
  565. 'current_mastery' => $weak->mastery_level ?? $weak['mastery_level'] ?? 0,
  566. 'target_mastery' => 0.85,
  567. 'recommended_practice' => 5,
  568. ];
  569. }
  570. return [
  571. 'paths' => $paths
  572. ];
  573. } catch (\Exception $e) {
  574. Log::error('Get Student Learning Paths Error', [
  575. 'student_id' => $studentId,
  576. 'error' => $e->getMessage()
  577. ]);
  578. return [
  579. 'paths' => []
  580. ];
  581. }
  582. }
  583. /**
  584. * 获取预测分析数据
  585. */
  586. public function getPredictionAnalytics(string $studentId): array
  587. {
  588. try {
  589. $predictions = $this->getStudentPredictions($studentId, 10);
  590. if (empty($predictions)) {
  591. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  592. }
  593. $accuracy = 0;
  594. $confidence = 0;
  595. if (!empty($predictions)) {
  596. $accuracy = rand(75, 95); // 模拟准确率
  597. $confidence = rand(70, 90); // 模拟置信度
  598. }
  599. $trend = 'improving'; // improving, stable, declining
  600. return [
  601. 'accuracy' => $accuracy,
  602. 'trend' => $trend,
  603. 'confidence' => $confidence,
  604. 'sample_size' => count($predictions)
  605. ];
  606. } catch (\Exception $e) {
  607. Log::error('Get Prediction Analytics Error', [
  608. 'student_id' => $studentId,
  609. 'error' => $e->getMessage()
  610. ]);
  611. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  612. }
  613. }
  614. /**
  615. * 获取学习路径分析数据
  616. */
  617. public function getLearningPathAnalytics(string $studentId): array
  618. {
  619. try {
  620. $paths = $this->getStudentLearningPaths($studentId, 5);
  621. if (empty($paths)) {
  622. return [
  623. 'active_paths' => 0,
  624. 'completed_paths' => 0,
  625. 'average_efficiency_score' => 0,
  626. 'completion_rate' => 0,
  627. 'average_time' => 0,
  628. 'total_paths' => 0
  629. ];
  630. }
  631. $activePaths = 0;
  632. $completedPaths = 0;
  633. $efficiencyScores = [];
  634. foreach ($paths as $path) {
  635. if (($path['status'] ?? '') === 'active') {
  636. $activePaths++;
  637. }
  638. if (($path['status'] ?? '') === 'completed') {
  639. $completedPaths++;
  640. }
  641. if (isset($path['efficiency_score'])) {
  642. $efficiencyScores[] = $path['efficiency_score'];
  643. }
  644. }
  645. $averageEfficiency = !empty($efficiencyScores)
  646. ? array_sum($efficiencyScores) / count($efficiencyScores)
  647. : rand(60, 85) / 100;
  648. $completionRate = count($paths) > 0
  649. ? ($completedPaths / count($paths)) * 100
  650. : 0;
  651. $averageTime = rand(30, 60); // 模拟平均时间(分钟)
  652. return [
  653. 'active_paths' => $activePaths,
  654. 'completed_paths' => $completedPaths,
  655. 'average_efficiency_score' => $averageEfficiency,
  656. 'completion_rate' => $completionRate,
  657. 'average_time' => $averageTime,
  658. 'total_paths' => count($paths)
  659. ];
  660. } catch (\Exception $e) {
  661. Log::error('Get Learning Path Analytics Error', [
  662. 'student_id' => $studentId,
  663. 'error' => $e->getMessage()
  664. ]);
  665. return [
  666. 'active_paths' => 0,
  667. 'completed_paths' => 0,
  668. 'average_efficiency_score' => 0,
  669. 'completion_rate' => 0,
  670. 'average_time' => 0,
  671. 'total_paths' => 0
  672. ];
  673. }
  674. }
  675. /**
  676. * 快速分数预测
  677. */
  678. public function quickScorePrediction(string $studentId): array
  679. {
  680. Log::info('开始调用快速预测API', ['student_id' => $studentId]);
  681. $response = Http::timeout($this->timeout)
  682. ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction");
  683. Log::info('快速预测API响应', [
  684. 'student_id' => $studentId,
  685. 'status' => $response->status(),
  686. 'body' => $response->body()
  687. ]);
  688. if (!$response->successful()) {
  689. throw new \Exception(sprintf(
  690. '快速预测接口失败: %s %s',
  691. $response->status(),
  692. $response->body()
  693. ));
  694. }
  695. $data = $response->json();
  696. Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
  697. // API 返回结构:{ student_id, current_assumption, target_assumption, quick_prediction, prediction_id, message }
  698. $quickPredictionData = $data['quick_prediction'] ?? [];
  699. return [
  700. 'quick_prediction' => [
  701. 'current_score' => $quickPredictionData['current_score'] ?? $data['current_assumption'] ?? 0,
  702. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  703. 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? (($data['target_assumption'] ?? 0) - ($data['current_assumption'] ?? 0)),
  704. 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 0,
  705. 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0,
  706. 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
  707. 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
  708. 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
  709. 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
  710. ],
  711. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  712. 'confidence' => isset($quickPredictionData['confidence_level']) ? $quickPredictionData['confidence_level'] * 100 : 0,
  713. 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 0,
  714. 'prediction_id' => $data['prediction_id'] ?? null,
  715. 'message' => $data['message'] ?? null,
  716. ];
  717. }
  718. /**
  719. * 推荐学习路径(本地化)
  720. */
  721. public function recommendLearningPaths(string $studentId, int $count = 3): array
  722. {
  723. try {
  724. Log::info('LearningAnalyticsService: 推荐学习路径 (本地)', [
  725. 'student_id' => $studentId,
  726. ]);
  727. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  728. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  729. $recommendations = [];
  730. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  731. $kpCode = is_object($weak) ? $weak->kp_code : ($weak['kp_code'] ?? '');
  732. $masteryLevel = is_object($weak) ? $weak->mastery_level : ($weak['mastery_level'] ?? 0);
  733. $recommendations[] = [
  734. 'kp_code' => $kpCode,
  735. 'kp_name' => $this->getKnowledgePointName($kpCode),
  736. 'current_mastery' => $masteryLevel,
  737. 'target_mastery' => 0.85,
  738. 'priority' => 1 - $masteryLevel,
  739. 'recommended_practice_count' => max(3, intval((0.85 - $masteryLevel) * 10)),
  740. 'estimated_time_minutes' => max(15, intval((0.85 - $masteryLevel) * 60)),
  741. ];
  742. }
  743. return [
  744. 'recommendations' => $recommendations
  745. ];
  746. } catch (\Exception $e) {
  747. Log::error('Recommend Learning Paths Error', [
  748. 'student_id' => $studentId,
  749. 'error' => $e->getMessage()
  750. ]);
  751. return [
  752. 'recommendations' => []
  753. ];
  754. }
  755. }
  756. /**
  757. * 获取知识点名称
  758. */
  759. private function getKnowledgePointName(string $kpCode): string
  760. {
  761. try {
  762. $kp = DB::table('knowledge_points')
  763. ->where('kp_code', $kpCode)
  764. ->value('name');
  765. return $kp ?? $kpCode;
  766. } catch (\Exception $e) {
  767. return $kpCode;
  768. }
  769. }
  770. /**
  771. * 重新计算掌握度(本地化)
  772. */
  773. public function recalculateMastery(string $studentId, string $kpCode): bool
  774. {
  775. try {
  776. Log::info('LearningAnalyticsService: 重新计算掌握度 (本地)', [
  777. 'student_id' => $studentId,
  778. 'kp_code' => $kpCode,
  779. ]);
  780. // 使用MasteryCalculator重新计算
  781. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  782. // 更新到数据库
  783. DB::table('student_knowledge_mastery')
  784. ->updateOrInsert(
  785. ['student_id' => $studentId, 'kp_code' => $kpCode],
  786. [
  787. 'mastery_level' => $result['mastery'],
  788. 'confidence_level' => $result['confidence'],
  789. 'total_attempts' => $result['total_attempts'],
  790. 'correct_attempts' => $result['correct_attempts'],
  791. 'mastery_trend' => $result['trend'],
  792. 'last_mastery_update' => now(),
  793. 'updated_at' => now(),
  794. ]
  795. );
  796. return true;
  797. } catch (\Exception $e) {
  798. Log::error('Recalculate Mastery Error', [
  799. 'student_id' => $studentId,
  800. 'kp_code' => $kpCode,
  801. 'error' => $e->getMessage()
  802. ]);
  803. return false;
  804. }
  805. }
  806. /**
  807. * 批量更新技能熟练度(本地化)
  808. */
  809. public function batchUpdateSkillProficiency(string $studentId): bool
  810. {
  811. try {
  812. Log::info('LearningAnalyticsService: 批量更新技能熟练度 (本地)', [
  813. 'student_id' => $studentId,
  814. ]);
  815. // 获取学生所有知识点
  816. $kpCodes = DB::table('student_knowledge_mastery')
  817. ->where('student_id', $studentId)
  818. ->pluck('kp_code')
  819. ->toArray();
  820. // 批量更新
  821. $this->masteryCalculator->batchUpdateMastery($studentId, $kpCodes);
  822. return true;
  823. } catch (\Exception $e) {
  824. Log::error('Batch Update Skill Proficiency Error', [
  825. 'student_id' => $studentId,
  826. 'error' => $e->getMessage()
  827. ]);
  828. return false;
  829. }
  830. }
  831. /**
  832. * 清空学生所有答题数据(本地化)
  833. */
  834. public function clearStudentData(string $studentId): bool
  835. {
  836. try {
  837. Log::info('LearningAnalyticsService: 清空学生数据 (本地)', [
  838. 'student_id' => $studentId,
  839. ]);
  840. // 清空MySQL中的数据
  841. $this->clearStudentMySQLData($studentId);
  842. Log::info('Student Data Cleared Successfully', [
  843. 'student_id' => $studentId,
  844. ]);
  845. return true;
  846. } catch (\Exception $e) {
  847. Log::error('Clear Student Data Error', [
  848. 'student_id' => $studentId,
  849. 'error' => $e->getMessage()
  850. ]);
  851. return false;
  852. }
  853. }
  854. /**
  855. * 清空学生MySQL中的答题数据
  856. */
  857. private function clearStudentMySQLData(string $studentId): void
  858. {
  859. try {
  860. // 清空student_exercises表
  861. DB::table('student_exercises')
  862. ->where('student_id', $studentId)
  863. ->delete();
  864. // 清空student_mastery表
  865. DB::table('student_mastery')
  866. ->where('student_id', $studentId)
  867. ->delete();
  868. Log::info('Student MySQL Data Cleared', [
  869. 'student_id' => $studentId
  870. ]);
  871. } catch (\Exception $e) {
  872. Log::error('Clear Student MySQL Data Error', [
  873. 'student_id' => $studentId,
  874. 'error' => $e->getMessage()
  875. ]);
  876. throw $e; // 重新抛出异常,让上层处理
  877. }
  878. }
  879. /**
  880. * 获取学生列表(供智能出卷使用)
  881. */
  882. public function getStudentsList(): array
  883. {
  884. try {
  885. $response = Http::timeout($this->timeout)
  886. ->get($this->baseUrl . '/api/v1/students/list');
  887. if ($response->successful()) {
  888. return $response->json('data', []);
  889. }
  890. // 如果API失败,尝试从MySQL直接读取
  891. return $this->getStudentsFromMySQL();
  892. } catch (\Exception $e) {
  893. Log::error('Get Students List Error', [
  894. 'error' => $e->getMessage()
  895. ]);
  896. // 返回模拟数据
  897. return [
  898. ['student_id' => 'stu_001', 'name' => '张三'],
  899. ['student_id' => 'stu_002', 'name' => '李四'],
  900. ['student_id' => 'stu_003', 'name' => '王五'],
  901. ];
  902. }
  903. }
  904. /**
  905. * 从MySQL获取学生列表
  906. */
  907. private function getStudentsFromMySQL(): array
  908. {
  909. try {
  910. return DB::table('students')
  911. ->select('student_id', 'name')
  912. ->limit(100)
  913. ->get()
  914. ->toArray();
  915. } catch (\Exception $e) {
  916. Log::error('Get Students From MySQL Error', [
  917. 'error' => $e->getMessage()
  918. ]);
  919. return [];
  920. }
  921. }
  922. /**
  923. * 获取学生薄弱点列表
  924. * 策略:MySQL作为权威数据源,LearningAnalytics API仅作为辅助/缓存
  925. */
  926. public function getStudentWeaknesses(string $studentId, int $limit = 10): array
  927. {
  928. try {
  929. // 从本地MySQL数据库获取学生薄弱点
  930. Log::info('从本地MySQL数据库获取学生薄弱点', [
  931. 'student_id' => $studentId,
  932. 'limit' => $limit
  933. ]);
  934. $weaknesses = $this->getStudentWeaknessesFromMySQL($studentId, $limit);
  935. if (!empty($weaknesses)) {
  936. Log::info('从本地数据库获取到薄弱点数据', [
  937. 'student_id' => $studentId,
  938. 'count' => count($weaknesses)
  939. ]);
  940. return $weaknesses;
  941. }
  942. Log::warning('本地数据库中无该学生薄弱点数据', [
  943. 'student_id' => $studentId
  944. ]);
  945. return [];
  946. } catch (\Exception $e) {
  947. Log::error('Get Student Weaknesses Error', [
  948. 'student_id' => $studentId,
  949. 'error' => $e->getMessage()
  950. ]);
  951. // 发生异常时,返回空数组
  952. return [];
  953. }
  954. }
  955. /**
  956. * 从MySQL获取学生薄弱点
  957. */
  958. private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
  959. {
  960. try {
  961. // 优先从 student_knowledge_mastery 表读取(更完整的掌握度数据)
  962. $weaknesses = DB::table('student_knowledge_mastery as skm')
  963. ->join('knowledge_points as kp', 'kp.kp_code', '=', 'skm.kp_code')
  964. ->where('skm.student_id', $studentId)
  965. ->where('skm.mastery_level', '<', 0.9) // 掌握度低于70%视为薄弱点
  966. ->whereNotNull('kp.parent_kp_code') // 排除根节点(如 M00/S000_000)
  967. ->orderBy('skm.mastery_level', 'asc')
  968. ->limit($limit)
  969. ->select([
  970. 'skm.kp_code',
  971. 'skm.mastery_level',
  972. 'skm.total_attempts',
  973. 'skm.correct_attempts',
  974. 'skm.incorrect_attempts',
  975. 'skm.confidence_level',
  976. 'skm.mastery_trend'
  977. ])
  978. ->get()
  979. ->toArray();
  980. // 如果student_knowledge_mastery表没有数据,尝试从student_mastery表读取
  981. if (empty($weaknesses)) {
  982. Log::info('student_knowledge_mastery表无数据,尝试从student_mastery表读取', [
  983. 'student_id' => $studentId
  984. ]);
  985. $weaknesses = DB::table('student_mastery as sm')
  986. ->leftJoin('knowledge_points as kp', 'sm.kp', '=', 'kp.kp_code')
  987. ->where('sm.student_id', $studentId)
  988. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  989. ->whereNotNull('kp.parent_kp_code') // 排除根节点(如 M00/S000_000)
  990. ->orderBy('sm.mastery', 'asc')
  991. ->limit($limit)
  992. ->select([
  993. 'sm.kp as kp_code',
  994. 'kp.name as kp_name',
  995. 'sm.mastery',
  996. 'sm.attempts',
  997. 'sm.correct'
  998. ])
  999. ->get()
  1000. ->toArray();
  1001. // 转换为统一格式
  1002. return array_map(function ($item) {
  1003. $mastery = (float) ($item->mastery ?? 0);
  1004. $attempts = (int) ($item->attempts ?? 0);
  1005. $correct = (int) ($item->correct ?? 0);
  1006. return [
  1007. 'kp_code' => $item->kp_code,
  1008. 'kp_name' => $item->kp_name ?? $item->kp_code,
  1009. 'mastery' => $mastery,
  1010. 'stability' => 0.5, // 默认稳定性
  1011. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1012. 'practice_count' => $attempts,
  1013. 'success_rate' => $attempts > 0 ? ($correct / $attempts) : 0,
  1014. 'priority' => $mastery < 0.3 ? '高' : ($mastery < 0.5 ? '中' : '低'),
  1015. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)) // 掌握度越低,建议题目越多
  1016. ];
  1017. }, $weaknesses);
  1018. }
  1019. // 转换student_knowledge_mastery表的数据格式
  1020. return array_map(function ($item) {
  1021. $mastery = (float) ($item->mastery_level ?? 0);
  1022. $totalAttempts = (int) ($item->total_attempts ?? 0);
  1023. $correctAttempts = (int) ($item->correct_attempts ?? 0);
  1024. $incorrectAttempts = (int) ($item->incorrect_attempts ?? 0);
  1025. $confidence = (float) ($item->confidence_level ?? 0.5);
  1026. $trend = $item->mastery_trend ?? 'stable';
  1027. // 计算成功率
  1028. $successRate = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : 0;
  1029. // 确定优先级
  1030. $priority = '中';
  1031. if ($mastery < 0.3) {
  1032. $priority = '高';
  1033. } elseif ($mastery < 0.5) {
  1034. $priority = '中';
  1035. } else {
  1036. $priority = '低';
  1037. }
  1038. return [
  1039. 'kp_code' => $item->kp_code,
  1040. 'kp_name' => $item->kp_code, // 如果没有中文名,使用代码作为名称
  1041. 'mastery' => $mastery,
  1042. 'stability' => $confidence,
  1043. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1044. 'practice_count' => $totalAttempts,
  1045. 'success_rate' => $successRate,
  1046. 'priority' => $priority,
  1047. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)), // 掌握度越低,建议题目越多
  1048. 'trend' => $trend,
  1049. 'correct_attempts' => $correctAttempts,
  1050. 'incorrect_attempts' => $incorrectAttempts
  1051. ];
  1052. }, $weaknesses);
  1053. } catch (\Exception $e) {
  1054. Log::error('Get Student Weaknesses From MySQL Error', [
  1055. 'student_id' => $studentId,
  1056. 'error' => $e->getMessage(),
  1057. 'trace' => $e->getTraceAsString()
  1058. ]);
  1059. return [];
  1060. }
  1061. }
  1062. /**
  1063. * 智能出卷:根据学生掌握度智能选择题目
  1064. */
  1065. public function generateIntelligentExam(array $params): array
  1066. {
  1067. $startTime = microtime(true);
  1068. try {
  1069. // 应用组卷类型策略
  1070. $assembleType = (int) ($params['assemble_type'] ?? 4); // 默认为通用类型(4)
  1071. $examTypeLegacy = $params['exam_type'] ?? 'general'; // 兼容旧版参数
  1072. // 如果有 assemble_type 参数,优先使用新的参数系统
  1073. if (isset($params['assemble_type'])) {
  1074. try {
  1075. // 确保QuestionExpansionService和QuestionLocalService可用
  1076. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1077. $questionLocalService = app(QuestionLocalService::class);
  1078. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1079. $params = $strategy->buildParams($params, $assembleType);
  1080. } catch (Exception $e) {
  1081. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1082. 'assemble_type' => $assembleType,
  1083. 'error' => $e->getMessage(),
  1084. 'trace' => $e->getTraceAsString()
  1085. ]);
  1086. }
  1087. } elseif ($examTypeLegacy !== 'general') {
  1088. // 兼容旧版 exam_type 参数
  1089. try {
  1090. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1091. $questionLocalService = app(QuestionLocalService::class);
  1092. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1093. $params = $strategy->buildParamsLegacy($params, $examTypeLegacy);
  1094. } catch (Exception $e) {
  1095. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1096. 'exam_type' => $examTypeLegacy,
  1097. 'error' => $e->getMessage(),
  1098. 'trace' => $e->getTraceAsString()
  1099. ]);
  1100. }
  1101. }
  1102. $studentId = $params['student_id'] ?? null;
  1103. $grade = $params['grade'] ?? null; // 用户选择的年级
  1104. $totalQuestions = $params['total_questions'] ?? (int) config('question_bank.default_total_questions');
  1105. // 【修复】参数映射:支持 kp_codes 和 kp_code_list 两种参数名
  1106. $kpCodes = $params['kp_codes'] ?? $params['kp_code_list'] ?? [];
  1107. if (!is_array($kpCodes)) {
  1108. $kpCodes = [];
  1109. }
  1110. $skills = $params['skills'] ?? [];
  1111. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1112. '选择题' => 40,
  1113. '填空题' => 40,
  1114. '解答题' => 20,
  1115. ];
  1116. // 新增:题目分类筛选
  1117. $questionCategory = $params['question_category'] ?? null;
  1118. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  1119. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1120. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1121. // 1. 如果指定了学生,获取学生的薄弱点
  1122. $weaknessFilter = [];
  1123. if ($studentId) {
  1124. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1125. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1126. // 【修复】教材出卷(assemble_type=3)不使用薄弱点,严格按章节获取知识点
  1127. if ($assembleType == 3) {
  1128. // 教材组卷不使用薄弱点
  1129. } else {
  1130. // 如果用户没有指定知识点,使用学生的薄弱点(非教材组卷)
  1131. if (empty($kpCodes)) {
  1132. $kpCodes = $weaknessFilter;
  1133. }
  1134. }
  1135. }
  1136. // 2. 优先使用学生错题(如果存在)
  1137. $mistakeQuestionIds = $params['mistake_question_ids'] ?? [];
  1138. $priorityQuestions = [];
  1139. $maxQuestions = 50; // 错题最大题目数限制
  1140. $poolLimit = 0; // 题库池不设上限,0 表示不限制
  1141. if (!empty($mistakeQuestionIds)) {
  1142. // 如果错题超过最大值,截取到最大值
  1143. $truncatedMistakeIds = $mistakeQuestionIds;
  1144. if (count($mistakeQuestionIds) > $maxQuestions) {
  1145. $truncatedMistakeIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  1146. }
  1147. // 获取学生错题的详细信息(错题获取不需要智能补充,不传入 grade/textbook_id)
  1148. $priorityQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $truncatedMistakeIds, [], null, null, null, null, 1);
  1149. }
  1150. // 3. 处理错题本逻辑
  1151. $allQuestions = $priorityQuestions;
  1152. $isMistakeBook = ($assembleType === 5); // 错题本类型
  1153. $hasMistakePriority = !empty($priorityQuestions);
  1154. $strictMistakeBook = $isMistakeBook && $hasMistakePriority;
  1155. // 【修改】错题本类型严格按错题组卷,不补充题目
  1156. if ($isMistakeBook) {
  1157. $mistakeKpSource = (bool) ($params['mistake_kp_source'] ?? false);
  1158. // 如果完全没有错题,回退到知识点/题库组卷
  1159. if (!$hasMistakePriority && !$mistakeKpSource) {
  1160. } elseif (!$hasMistakePriority && $mistakeKpSource) {
  1161. }
  1162. }
  1163. if (!$strictMistakeBook && count($priorityQuestions) < $totalQuestions) {
  1164. try {
  1165. // 【优化】获取textbook_catalog_node_ids参数(教材组卷时使用)
  1166. $textbookCatalogNodeIds = $params['textbook_catalog_node_ids'] ?? null;
  1167. // 【修复超纲问题】获取 textbook_id 和 difficulty_category,用于智能补充时限制范围
  1168. $textbookId = isset($params['textbook_id']) ? (int) $params['textbook_id'] : null;
  1169. $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
  1170. // 【修复超纲问题】传入 grade 和 textbook_id,用于智能补充时限制范围
  1171. // 【修复】传入实际需要数量,否则 totalNeeded=0 会导致智能补充不触发
  1172. $excludeQuestionIds = $params['exclude_question_ids'] ?? [];
  1173. $needCount = $totalQuestions - count($priorityQuestions);
  1174. $baseNeedCount = in_array($assembleType, [2, 3], true) ? 0 : $needCount;
  1175. $additionalQuestions = $this->getQuestionsFromBank(
  1176. $kpCodes,
  1177. $skills,
  1178. $studentId,
  1179. $questionTypeRatio,
  1180. $baseNeedCount,
  1181. [],
  1182. $excludeQuestionIds,
  1183. $questionCategory,
  1184. $textbookCatalogNodeIds,
  1185. $grade ? (int) $grade : null, // 年级
  1186. $textbookId, // 教材ID(避免超纲)
  1187. $difficultyCategory // 难度类别
  1188. );
  1189. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($priorityQuestions, $additionalQuestions));
  1190. // assemble_type=2/3:本源池不足,先用父树补题 KP 拉题(兄弟节点优先)
  1191. if (
  1192. in_array($assembleType, [2, 3], true)
  1193. && count($allQuestions) < $totalQuestions
  1194. && ! empty($params['kp_supplement_subtree_codes'] ?? [])
  1195. && $grade !== null
  1196. ) {
  1197. $before = count($allQuestions);
  1198. $excludeForSupp = array_values(array_unique(array_filter(array_merge(
  1199. $excludeQuestionIds,
  1200. array_column($allQuestions, 'id')
  1201. ))));
  1202. Log::info('assemble.supplement', [
  1203. 'stage' => 'kp_subtree',
  1204. 'status' => 'start',
  1205. 'before_count' => $before,
  1206. 'target_count' => $totalQuestions,
  1207. 'assemble_type' => $assembleType,
  1208. ]);
  1209. $supp = $this->fetchQuestionsForKpAssembleSupplement(
  1210. $params['kp_supplement_subtree_codes'],
  1211. $excludeForSupp,
  1212. (int) $grade,
  1213. $skills,
  1214. $questionCategory,
  1215. $assembleType === 3 ? null : $textbookCatalogNodeIds
  1216. );
  1217. $supplementStats = $this->buildSupplementQuestionStats($supp);
  1218. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($allQuestions, $supp));
  1219. Log::info('assemble.supplement', [
  1220. 'stage' => 'kp_subtree',
  1221. 'status' => empty($supp) ? 'empty' : 'done',
  1222. 'before_count' => $before,
  1223. 'supplement_count' => count($supp),
  1224. 'after_count' => count($allQuestions),
  1225. 'target_count' => $totalQuestions,
  1226. 'assemble_type' => $assembleType,
  1227. 'supplement_kp_distribution_topn' => $supplementStats['supplement_kp_distribution_topn'],
  1228. 'supplement_kp_sample' => $supplementStats['supplement_kp_sample'],
  1229. ]);
  1230. }
  1231. // assemble_type=3:兄弟补题后仍不足,再走教材前章节补题兜底
  1232. if (
  1233. $assembleType === 3
  1234. && count($allQuestions) < $totalQuestions
  1235. && $grade !== null
  1236. ) {
  1237. $before = count($allQuestions);
  1238. $deficit = $totalQuestions - count($allQuestions);
  1239. $excludeForChapterSupplement = array_values(array_unique(array_filter(array_merge(
  1240. $excludeQuestionIds,
  1241. array_column($allQuestions, 'id')
  1242. ))));
  1243. Log::info('assemble.supplement', [
  1244. 'stage' => 'chapter_fallback',
  1245. 'status' => 'start',
  1246. 'before_count' => $before,
  1247. 'target_count' => $totalQuestions,
  1248. 'assemble_type' => $assembleType,
  1249. ]);
  1250. $chapterSupplement = $this->getSupplementaryQuestionsForGrade(
  1251. (int) $grade,
  1252. array_column($allQuestions, 'kp_code'),
  1253. $deficit,
  1254. $difficultyCategory,
  1255. $textbookId,
  1256. $excludeForChapterSupplement,
  1257. $textbookCatalogNodeIds ?? null,
  1258. $studentId
  1259. );
  1260. $chapterSupplementStats = $this->buildSupplementQuestionStats($chapterSupplement);
  1261. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($allQuestions, $chapterSupplement));
  1262. Log::info('assemble.supplement', [
  1263. 'stage' => 'chapter_fallback',
  1264. 'status' => empty($chapterSupplement) ? 'empty' : 'done',
  1265. 'before_count' => $before,
  1266. 'supplement_count' => count($chapterSupplement),
  1267. 'after_count' => count($allQuestions),
  1268. 'target_count' => $totalQuestions,
  1269. 'assemble_type' => $assembleType,
  1270. 'supplement_kp_distribution_topn' => $chapterSupplementStats['supplement_kp_distribution_topn'],
  1271. 'supplement_kp_sample' => $chapterSupplementStats['supplement_kp_sample'],
  1272. ]);
  1273. }
  1274. // 通用兜底:无论何种组卷类型,前序补题后仍不足时,最终都走常规补题策略
  1275. if (count($allQuestions) < $totalQuestions && $grade !== null) {
  1276. $before = count($allQuestions);
  1277. $deficit = $totalQuestions - count($allQuestions);
  1278. $excludeForCommonFallback = array_values(array_unique(array_filter(array_merge(
  1279. $excludeQuestionIds,
  1280. array_column($allQuestions, 'id')
  1281. ))));
  1282. Log::info('assemble.supplement', [
  1283. 'stage' => 'common_fallback',
  1284. 'status' => 'start',
  1285. 'before_count' => $before,
  1286. 'target_count' => $totalQuestions,
  1287. 'assemble_type' => $assembleType,
  1288. ]);
  1289. $commonFallback = $this->getSupplementaryQuestionsForGrade(
  1290. (int) $grade,
  1291. array_column($allQuestions, 'kp_code'),
  1292. $deficit,
  1293. $difficultyCategory,
  1294. $textbookId,
  1295. $excludeForCommonFallback,
  1296. $assembleType === 3 ? null : ($textbookCatalogNodeIds ?? null),
  1297. $studentId
  1298. );
  1299. $commonFallbackStats = $this->buildSupplementQuestionStats($commonFallback);
  1300. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($allQuestions, $commonFallback));
  1301. Log::info('assemble.supplement', [
  1302. 'stage' => 'common_fallback',
  1303. 'status' => empty($commonFallback) ? 'empty' : 'done',
  1304. 'before_count' => $before,
  1305. 'supplement_count' => count($commonFallback),
  1306. 'after_count' => count($allQuestions),
  1307. 'target_count' => $totalQuestions,
  1308. 'assemble_type' => $assembleType,
  1309. 'supplement_kp_distribution_topn' => $commonFallbackStats['supplement_kp_distribution_topn'],
  1310. 'supplement_kp_sample' => $commonFallbackStats['supplement_kp_sample'],
  1311. ]);
  1312. }
  1313. } catch (\Exception $e) {
  1314. Log::error('getQuestionsFromBank 调用失败', [
  1315. 'error' => $e->getMessage(),
  1316. 'trace' => $e->getTraceAsString()
  1317. ]);
  1318. throw $e;
  1319. }
  1320. }
  1321. if (empty($allQuestions)) {
  1322. // 如果指定了知识点但题库为空,给出明确提示
  1323. if (!empty($kpCodes)) {
  1324. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1325. } else {
  1326. // 没有选择知识点时,从所有题目中选择
  1327. // 如果仍然没有题目,说明题库为空,提示补充题库
  1328. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1329. }
  1330. return [
  1331. 'success' => false,
  1332. 'message' => $message,
  1333. 'questions' => []
  1334. ];
  1335. }
  1336. // 3. 根据掌握度对题目进行筛选和排序(含追练:题量与 total_questions / default_total_questions 一致,不再按 50 拉满)
  1337. $targetQuestionCount = min(count($allQuestions), $totalQuestions);
  1338. if (! empty($params['kp_target_counts']) || ! empty($params['max_difficulty_by_kp']) || ! empty($params['type_targets_by_kp'])) {
  1339. $allQuestions = app(QuestionDifficultyResolver::class)->applyCalibratedDifficulty($allQuestions);
  1340. }
  1341. $startTime = microtime(true);
  1342. $selectedQuestions = $this->selectQuestionsByMastery(
  1343. $allQuestions,
  1344. $studentId,
  1345. $targetQuestionCount,
  1346. $questionTypeRatio,
  1347. $difficultyLevels,
  1348. $weaknessFilter,
  1349. $assembleType, // 新增assembleType参数
  1350. $params['kp_code_list_original'] ?? $params['kp_codes'] ?? [],
  1351. $params['kp_target_counts'] ?? [],
  1352. $params['max_difficulty_by_kp'] ?? [],
  1353. $params['type_targets_by_kp'] ?? []
  1354. );
  1355. if (empty($selectedQuestions)) {
  1356. return [
  1357. 'success' => false,
  1358. 'message' => '题目筛选失败',
  1359. 'questions' => []
  1360. ];
  1361. }
  1362. // 【恢复】简化难度分布检查
  1363. $difficultyCategory = $params['difficulty_category'] ?? 1;
  1364. $enableDistribution = $params['enable_difficulty_distribution'] ?? false;
  1365. // assemble_type=2(知识点组卷)优先保证请求知识点覆盖,避免二次难度重排把次要 KP 挤没
  1366. $isExcludedType = ($assembleType === 2);
  1367. if ($enableDistribution && !$isExcludedType) {
  1368. try {
  1369. $selectedQuestions = $this->applyTypeAwareDifficultyDistribution(
  1370. $allQuestions,
  1371. $selectedQuestions,
  1372. $totalQuestions,
  1373. (int) $difficultyCategory,
  1374. $questionTypeRatio
  1375. );
  1376. } catch (\Exception $e) {
  1377. // 保持组卷主流程稳定,难度分布失败时继续返回原结果
  1378. }
  1379. }
  1380. $selectedQuestions = $this->enforceAnswerDifficultyFloor(
  1381. $allQuestions,
  1382. $selectedQuestions,
  1383. (int) $difficultyCategory,
  1384. (int) $totalQuestions
  1385. );
  1386. $requestedKpSelectionStats = $this->buildRequestedKpSelectionStats(
  1387. $selectedQuestions,
  1388. $params['kp_code_list_original'] ?? $params['kp_codes'] ?? []
  1389. );
  1390. Log::info('LearningAnalyticsService: 最终选题分布', [
  1391. 'assemble_type' => $assembleType,
  1392. 'question_count' => count($selectedQuestions),
  1393. 'type_distribution' => $this->countByType($selectedQuestions),
  1394. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code')),
  1395. 'requested_kp_selection' => $assembleType === 2 ? $requestedKpSelectionStats : null,
  1396. ]);
  1397. return [
  1398. 'success' => true,
  1399. 'message' => '智能出卷成功',
  1400. 'questions' => $selectedQuestions,
  1401. // 【新增】传递章节摸底和智能组卷的关键字段
  1402. 'diagnostic_chapter_id' => $params['diagnostic_chapter_id'] ?? null,
  1403. 'explanation_kp_codes' => $params['explanation_kp_codes'] ?? null,
  1404. 'assemble_type' => $params['assembleType'] ?? null, // 策略可能修改assembleType(如章节智能→章节摸底)
  1405. 'stats' => [
  1406. 'total_selected' => count($selectedQuestions),
  1407. 'source_questions' => count($allQuestions),
  1408. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1409. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1410. })) : 0,
  1411. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1412. 'difficulty_category' => $difficultyCategory,
  1413. 'final_distribution' => $this->buildDifficultyDistributionStats($selectedQuestions, (int) $difficultyCategory),
  1414. 'final_distribution_shortage' => $this->buildDifficultyDistributionShortage(
  1415. $selectedQuestions,
  1416. (int) $difficultyCategory,
  1417. (int) $totalQuestions
  1418. ),
  1419. 'requested_kp_selection' => $assembleType === 2 ? $requestedKpSelectionStats : null,
  1420. // 【新增】章节知识点数量统计(教材组卷时)
  1421. 'chapter_knowledge_point_stats' => $params['chapter_knowledge_point_stats'] ?? null,
  1422. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? null
  1423. ]
  1424. ];
  1425. } catch (\Exception $e) {
  1426. Log::error('Generate Intelligent Exam Error', [
  1427. 'error' => $e->getMessage(),
  1428. 'trace' => $e->getTraceAsString()
  1429. ]);
  1430. return [
  1431. 'success' => false,
  1432. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1433. 'questions' => []
  1434. ];
  1435. }
  1436. }
  1437. /**
  1438. * @param array<int, array<string, mixed>> $questions
  1439. * @return array<int, array<string, mixed>>
  1440. */
  1441. private function dedupeQuestionsByBankId(array $questions): array
  1442. {
  1443. $seen = [];
  1444. $out = [];
  1445. foreach ($questions as $q) {
  1446. $id = $q['id'] ?? null;
  1447. if ($id === null || $id === '') {
  1448. continue;
  1449. }
  1450. $k = (string) $id;
  1451. if (isset($seen[$k])) {
  1452. continue;
  1453. }
  1454. $seen[$k] = true;
  1455. $out[] = $q;
  1456. }
  1457. return $out;
  1458. }
  1459. /**
  1460. * 知识点组卷补题:仅按补充 KP 列表查询,筛选条件与 getQuestionsFromBank 主查询一致(不调用教材/已学那条智能补题)。
  1461. *
  1462. * @param array<string> $kpCodes
  1463. * @param array<int|string> $excludeQuestionIds
  1464. * @return array<int, array<string, mixed>>
  1465. */
  1466. private function fetchQuestionsForKpAssembleSupplement(
  1467. array $kpCodes,
  1468. array $excludeQuestionIds,
  1469. int $grade,
  1470. array $skills = [],
  1471. ?int $questionCategory = null,
  1472. ?array $textbookCatalogNodeIds = null
  1473. ): array {
  1474. $kpCodes = array_values(array_unique(array_filter($kpCodes)));
  1475. if ($kpCodes === []) {
  1476. return [];
  1477. }
  1478. $query = \App\Models\Question::query()
  1479. ->where('audit_status', 0)
  1480. ->whereIn('kp_code', $kpCodes);
  1481. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  1482. if ($stageGrade !== null) {
  1483. $query->where('grade', $stageGrade);
  1484. }
  1485. if (! empty($skills)) {
  1486. $query->where(function ($q) use ($skills) {
  1487. foreach ($skills as $skill) {
  1488. $q->orWhere('tags', 'like', '%'.$skill.'%');
  1489. }
  1490. });
  1491. }
  1492. if (! empty($excludeQuestionIds)) {
  1493. $query->whereNotIn('id', $excludeQuestionIds);
  1494. }
  1495. if ($questionCategory !== null) {
  1496. $query->where('question_category', $questionCategory);
  1497. }
  1498. $query->whereNotNull('solution')
  1499. ->where('solution', '!=', '')
  1500. ->where('solution', '!=', '[]');
  1501. if (! empty($textbookCatalogNodeIds)) {
  1502. $query->whereIn('textbook_catalog_nodes_id', $textbookCatalogNodeIds);
  1503. }
  1504. return $query->inRandomOrder()->get()->map(function ($q) {
  1505. return [
  1506. 'id' => $q->id,
  1507. 'question_code' => $q->question_code,
  1508. 'kp_code' => $q->kp_code,
  1509. 'question_type' => $q->question_type,
  1510. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1511. 'stem' => $q->stem,
  1512. 'solution' => $q->solution,
  1513. 'metadata' => [
  1514. 'has_solution' => true,
  1515. 'is_choice' => $q->question_type === 'choice',
  1516. 'is_fill' => $q->question_type === 'fill',
  1517. 'is_answer' => $q->question_type === 'answer',
  1518. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1519. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type),
  1520. ],
  1521. ];
  1522. })->toArray();
  1523. }
  1524. /**
  1525. * 从题库获取题目
  1526. *
  1527. * @param array $kpCodes 知识点代码列表
  1528. * @param array $skills 技能标签列表
  1529. * @param string|null $studentId 学生ID
  1530. * @param array $questionTypeRatio 题型比例
  1531. * @param int $totalNeeded 需要的题目数量
  1532. * @param array $priorityQuestionIds 优先获取的题目ID(错题)
  1533. * @param array $excludeQuestionIds 排除的题目ID
  1534. * @param int|null $questionCategory 题目分类
  1535. * @param array|null $textbookCatalogNodeIds 教材章节节点ID
  1536. * @param int|null $grade 年级(用于智能补充时限制范围)
  1537. * @param int|null $textbookId 教材ID(用于智能补充时限制范围,避免超纲)
  1538. * @param int $difficultyCategory 难度类别(用于智能补充)
  1539. * @return array 题目列表
  1540. */
  1541. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], int $totalNeeded = 100, array $priorityQuestionIds = [], array $excludeQuestionIds = [], ?int $questionCategory = null, ?array $textbookCatalogNodeIds = null, ?int $grade = null, ?int $textbookId = null, int $difficultyCategory = 1): array
  1542. {
  1543. $startTime = microtime(true);
  1544. try {
  1545. // 错题回顾:优先获取指定的学生错题
  1546. if (!empty($priorityQuestionIds)) {
  1547. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1548. if (!empty($priorityQuestions)) {
  1549. return $priorityQuestions;
  1550. } else {
  1551. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1552. return [];
  1553. }
  1554. }
  1555. $query = \App\Models\Question::query();
  1556. // 【新增】只获取审核通过的题目(audit_status = 0 表示合格)
  1557. $query->where('audit_status', 0);
  1558. // 按知识点筛选
  1559. if (!empty($kpCodes)) {
  1560. $query->whereIn('kp_code', $kpCodes);
  1561. }
  1562. // 按学段筛选(题库 grade: 2=初中, 3=高中)
  1563. if ($grade !== null) {
  1564. $stageGrade = $this->normalizeQuestionStageGrade((int) $grade);
  1565. if ($stageGrade !== null) {
  1566. $query->where('grade', $stageGrade);
  1567. }
  1568. }
  1569. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1570. if (!empty($skills)) {
  1571. $query->where(function ($q) use ($skills) {
  1572. foreach ($skills as $skill) {
  1573. $q->orWhere('tags', 'like', "%{$skill}%");
  1574. }
  1575. });
  1576. }
  1577. // 排除学生已做过的题目
  1578. if (!empty($excludeQuestionIds)) {
  1579. $query->whereNotIn('id', $excludeQuestionIds);
  1580. }
  1581. // 按题目分类筛选(如果指定了 question_category)
  1582. if ($questionCategory !== null) {
  1583. $query->where('question_category', $questionCategory);
  1584. }
  1585. // 筛选有解题思路的题目
  1586. $query->whereNotNull('solution')
  1587. ->where('solution', '!=', '')
  1588. ->where('solution', '!=', '[]');
  1589. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1590. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1591. $hasSpecificScope = !empty($kpCodes) || !empty($textbookCatalogNodeIds);
  1592. $queryPoolLimit = 0;
  1593. if ($hasSpecificScope) {
  1594. // 有明确知识点/章节范围时,保留随机抽样能力。
  1595. $query->inRandomOrder();
  1596. } else {
  1597. // 新学生常见场景:没有掌握度、没有知识点范围。
  1598. // 避免全表随机+全量加载导致队列任务超时。
  1599. $queryPoolLimit = max(500, $totalNeeded * 50);
  1600. $query->orderByDesc('id')->limit($queryPoolLimit);
  1601. }
  1602. $questions = $query->get();
  1603. Log::info('getQuestionsFromBank: query_pool', [
  1604. 'has_specific_scope' => $hasSpecificScope,
  1605. 'kp_codes_count' => count($kpCodes),
  1606. 'textbook_node_count' => is_array($textbookCatalogNodeIds) ? count($textbookCatalogNodeIds) : 0,
  1607. 'total_needed' => $totalNeeded,
  1608. 'query_pool_limit' => $queryPoolLimit,
  1609. 'result_count' => $questions->count(),
  1610. ]);
  1611. // 转换为标准格式
  1612. $formattedQuestions = $questions->map(function ($q) {
  1613. return [
  1614. 'id' => $q->id,
  1615. 'question_code' => $q->question_code,
  1616. 'kp_code' => $q->kp_code,
  1617. 'question_type' => $q->question_type,
  1618. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1619. 'stem' => $q->stem,
  1620. 'solution' => $q->solution,
  1621. 'metadata' => [
  1622. 'has_solution' => true,
  1623. 'is_choice' => $q->question_type === 'choice',
  1624. 'is_fill' => $q->question_type === 'fill',
  1625. 'is_answer' => $q->question_type === 'answer',
  1626. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1627. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1628. ]
  1629. ];
  1630. })->toArray();
  1631. // 【重要】返回所有符合条件的题目,不限制数量
  1632. // 让上层调用者根据需要选择题目数量
  1633. $selectedQuestions = $formattedQuestions;
  1634. // 【修复】重新启用智能补充功能,增加 textbook_id 限制避免超纲
  1635. if ($totalNeeded > 0 && count($selectedQuestions) < $totalNeeded && $grade !== null) {
  1636. $deficit = $totalNeeded - count($selectedQuestions);
  1637. Log::info('assemble.supplement', [
  1638. 'stage' => 'start',
  1639. 'deficit' => $deficit,
  1640. 'current_count' => count($selectedQuestions),
  1641. 'target_count' => $totalNeeded,
  1642. 'grade' => $grade,
  1643. 'textbook_id' => $textbookId,
  1644. 'has_student_id' => ! empty($studentId),
  1645. 'has_chapter_scope' => ! empty($textbookCatalogNodeIds),
  1646. ]);
  1647. // 【修复超纲问题】补充策略:只从「学过的」内容补充
  1648. // - 有 textbook_id:从同教材的前章节补充
  1649. // - 无 textbook_id:从学生做过的题目对应的知识点补充,避免未学内容
  1650. $supplementaryQuestions = $this->getSupplementaryQuestionsForGrade(
  1651. $grade,
  1652. array_column($selectedQuestions, 'kp_code'),
  1653. $deficit,
  1654. $difficultyCategory,
  1655. $textbookId,
  1656. $excludeQuestionIds,
  1657. $textbookCatalogNodeIds ?? null,
  1658. $studentId
  1659. );
  1660. if (!empty($supplementaryQuestions)) {
  1661. $selectedQuestions = array_merge($selectedQuestions, $supplementaryQuestions);
  1662. Log::info('assemble.supplement', [
  1663. 'stage' => 'done',
  1664. 'supplement_count' => count($supplementaryQuestions),
  1665. 'after_count' => count($selectedQuestions),
  1666. 'target_count' => $totalNeeded,
  1667. 'grade' => $grade,
  1668. 'textbook_id' => $textbookId,
  1669. ]);
  1670. } else {
  1671. Log::info('assemble.supplement', [
  1672. 'stage' => 'empty',
  1673. 'supplement_count' => 0,
  1674. 'after_count' => count($selectedQuestions),
  1675. 'target_count' => $totalNeeded,
  1676. 'grade' => $grade,
  1677. 'textbook_id' => $textbookId,
  1678. ]);
  1679. }
  1680. }
  1681. return $selectedQuestions;
  1682. } catch (\Exception $e) {
  1683. Log::error('getQuestionsFromBank 查询失败', [
  1684. 'error' => $e->getMessage(),
  1685. 'trace' => $e->getTraceAsString()
  1686. ]);
  1687. throw $e;
  1688. }
  1689. }
  1690. /**
  1691. * 获取指定ID的题目详情
  1692. */
  1693. private function getLocalQuestionsByIds(array $questionIds): array
  1694. {
  1695. try {
  1696. // 通过QuestionBankService获取题目详情
  1697. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1698. // 批量获取题目详情
  1699. $response = $questionBankService->getQuestionsByIds($questionIds);
  1700. if (empty($response['data'])) {
  1701. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1702. 'requested_ids' => $questionIds
  1703. ]);
  1704. return [];
  1705. }
  1706. $questions = $response['data'];
  1707. // 转换为标准格式
  1708. $result = array_map(function ($q) {
  1709. $difficulty = $q['difficulty'] ?? 0.5;
  1710. return [
  1711. 'id' => $q['id'],
  1712. 'question_code' => $q['question_code'] ?? '',
  1713. 'kp_code' => $q['kp_code'] ?? '',
  1714. 'question_type' => $q['question_type'] ?? 'choice',
  1715. 'difficulty' => (float) $difficulty,
  1716. 'stem' => $q['stem'] ?? '',
  1717. 'solution' => $q['solution'] ?? '',
  1718. 'answer' => $q['answer'] ?? '',
  1719. 'metadata' => [
  1720. 'has_solution' => !empty($q['solution']),
  1721. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1722. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1723. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1724. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1725. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1726. ]
  1727. ];
  1728. }, $questions);
  1729. Log::info('getLocalQuestionsByIds 获取成功', [
  1730. 'requested_count' => count($questionIds),
  1731. 'found_count' => count($result),
  1732. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1733. 'question_ids' => array_slice($questionIds, 0, 20),
  1734. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1735. ]);
  1736. return $result;
  1737. } catch (\Exception $e) {
  1738. Log::error('getLocalQuestionsByIds 获取失败', [
  1739. 'question_ids' => $questionIds,
  1740. 'error' => $e->getMessage(),
  1741. 'trace' => $e->getTraceAsString()
  1742. ]);
  1743. return [];
  1744. }
  1745. }
  1746. /**
  1747. * 获取卷子的所有题目ID(不区分对错)
  1748. */
  1749. private function getPaperAllQuestions(array $paperIds): array
  1750. {
  1751. try {
  1752. // 查询 paper_questions 表获取所有题目ID
  1753. $questionIds = DB::table('paper_questions')
  1754. ->whereIn('paper_id', $paperIds)
  1755. ->pluck('question_bank_id')
  1756. ->unique()
  1757. ->filter()
  1758. ->values()
  1759. ->toArray();
  1760. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1761. 'paper_ids' => $paperIds,
  1762. 'question_count' => count($questionIds)
  1763. ]);
  1764. return $questionIds;
  1765. } catch (\Exception $e) {
  1766. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1767. 'paper_ids' => $paperIds,
  1768. 'error' => $e->getMessage()
  1769. ]);
  1770. return [];
  1771. }
  1772. }
  1773. /**
  1774. * 获取难度标签
  1775. */
  1776. private function getDifficultyLabel(?float $difficulty): string
  1777. {
  1778. if ($difficulty === null) {
  1779. return '未知';
  1780. }
  1781. return match (true) {
  1782. $difficulty < 0.4 => '基础',
  1783. $difficulty < 0.7 => '中等',
  1784. default => '拔高'
  1785. };
  1786. }
  1787. /**
  1788. * 获取题型标签
  1789. */
  1790. private function getQuestionTypeLabel(string $questionType): string
  1791. {
  1792. return match ($questionType) {
  1793. 'choice' => '选择题',
  1794. 'fill' => '填空题',
  1795. 'answer' => '解答题',
  1796. default => '未知题型'
  1797. };
  1798. }
  1799. /**
  1800. * 根据题型配比选择题目
  1801. * 注意: 难度配比调整由 QuestionLocalService 处理
  1802. */
  1803. private function selectQuestionsByRatio(
  1804. array $questions,
  1805. int $totalNeeded,
  1806. array $questionTypeRatio = []
  1807. ): array {
  1808. if (empty($questions)) {
  1809. return [];
  1810. }
  1811. // 如果没有配比要求,直接返回
  1812. if (empty($questionTypeRatio)) {
  1813. return array_slice($questions, 0, $totalNeeded);
  1814. }
  1815. $selected = [];
  1816. $usedIndices = [];
  1817. // 按题型配比选择
  1818. if (!empty($questionTypeRatio)) {
  1819. foreach ($questionTypeRatio as $type => $ratio) {
  1820. $count = (int) round(($ratio / 100) * $totalNeeded);
  1821. if ($count <= 0) continue;
  1822. $typeQuestions = [];
  1823. foreach ($questions as $idx => $q) {
  1824. if (in_array($idx, $usedIndices)) continue;
  1825. $qType = $q['question_type'] ?? '';
  1826. $label = $this->getQuestionTypeLabel($qType);
  1827. if ($label === $type) {
  1828. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1829. }
  1830. }
  1831. // 随机选择
  1832. shuffle($typeQuestions);
  1833. $selectedCount = min($count, count($typeQuestions));
  1834. for ($i = 0; $i < $selectedCount; $i++) {
  1835. $selected[] = $typeQuestions[$i]['question'];
  1836. $usedIndices[] = $typeQuestions[$i]['idx'];
  1837. }
  1838. }
  1839. }
  1840. // 如果还有空缺,补充剩余题目
  1841. // 注意: 难度配比调整由 QuestionLocalService 处理
  1842. if (count($selected) < $totalNeeded) {
  1843. foreach ($questions as $idx => $q) {
  1844. if (count($selected) >= $totalNeeded) break;
  1845. if (!in_array($idx, $usedIndices)) {
  1846. $selected[] = $q;
  1847. $usedIndices[] = $idx;
  1848. }
  1849. }
  1850. }
  1851. return array_slice($selected, 0, $totalNeeded);
  1852. }
  1853. /**
  1854. * 根据学生掌握度筛选题目
  1855. */
  1856. private function selectQuestionsByMastery(
  1857. array $questions,
  1858. ?string $studentId,
  1859. int $totalQuestions,
  1860. array $questionTypeRatio,
  1861. array $difficultyLevels,
  1862. array $weaknessFilter,
  1863. int $assembleType, // 新增assembleType参数
  1864. array $requestedKpCodes = [],
  1865. array $kpTargetCounts = [],
  1866. array $maxDifficultyByKp = [],
  1867. array $typeTargetsByKp = []
  1868. ): array {
  1869. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1870. // 如果题目数量超过目标,则截取到目标数量
  1871. // 如果题目数量不足,则使用所有题目,并记录警告
  1872. if (count($questions) > $totalQuestions) {
  1873. Log::debug('selectQuestionsByMastery: 题目数量超过目标,进行截取', [
  1874. 'question_count' => count($questions),
  1875. 'total_questions' => $totalQuestions
  1876. ]);
  1877. } else {
  1878. Log::warning('题目数量不足,将使用所有可用题目', [
  1879. 'available_count' => count($questions),
  1880. 'requested_count' => $totalQuestions,
  1881. 'note' => '可能需要补充题库或放宽筛选条件'
  1882. ]);
  1883. }
  1884. // 【移除】删除多余的难度筛选逻辑
  1885. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1886. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1887. $requestedKpCodes = array_values(array_unique(array_filter($requestedKpCodes)));
  1888. $requestedKpSet = array_fill_keys($requestedKpCodes, true);
  1889. $shouldRestrictToRequestedKps = ($assembleType === 2 && ! empty($requestedKpSet));
  1890. if ($assembleType === 2 && ! empty($kpTargetCounts)) {
  1891. return $this->selectQuestionsByKpTargets(
  1892. $questions,
  1893. $totalQuestions,
  1894. $requestedKpCodes,
  1895. $kpTargetCounts,
  1896. $maxDifficultyByKp,
  1897. $typeTargetsByKp
  1898. );
  1899. }
  1900. if ($shouldRestrictToRequestedKps) {
  1901. $requestedQuestions = array_values(array_filter($questions, function ($question) use ($requestedKpSet) {
  1902. $kpCode = $question['kp_code'] ?? '';
  1903. return isset($requestedKpSet[$kpCode]);
  1904. }));
  1905. $fallbackQuestions = array_values(array_filter($questions, function ($question) use ($requestedKpSet) {
  1906. $kpCode = $question['kp_code'] ?? '';
  1907. return ! isset($requestedKpSet[$kpCode]);
  1908. }));
  1909. Log::info('selectQuestionsByMastery: assemble_type=2 请求知识点约束', [
  1910. 'requested_kp_codes' => $requestedKpCodes,
  1911. 'requested_question_count' => count($requestedQuestions),
  1912. 'fallback_question_count' => count($fallbackQuestions),
  1913. 'target_question_count' => $totalQuestions,
  1914. ]);
  1915. // 原始请求知识点足够时,最终选题不应被补题池中的兄弟/父树知识点带偏。
  1916. if (count($requestedQuestions) >= $totalQuestions) {
  1917. $questions = $requestedQuestions;
  1918. } else {
  1919. $questions = array_merge($requestedQuestions, $fallbackQuestions);
  1920. }
  1921. }
  1922. // 1. 按知识点分组
  1923. $groupStartTime = microtime(true);
  1924. $questionsByKp = [];
  1925. foreach ($questions as $question) {
  1926. $kpCode = $question['kp_code'] ?? '';
  1927. if (!isset($questionsByKp[$kpCode])) {
  1928. $questionsByKp[$kpCode] = [];
  1929. }
  1930. $questionsByKp[$kpCode][] = $question;
  1931. }
  1932. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1933. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1934. $kpWeights = [];
  1935. $kpCodes = array_keys($questionsByKp);
  1936. $startTime = microtime(true);
  1937. $allMastery = [];
  1938. if ($studentId) {
  1939. // 批量获取所有知识点的掌握度(一次查询)
  1940. $masteryStart = microtime(true);
  1941. try {
  1942. $masteryRecords = DB::table('student_mastery')
  1943. ->where('student_id', $studentId)
  1944. ->whereIn('kp', $kpCodes)
  1945. ->pluck('mastery', 'kp')
  1946. ->all();
  1947. Log::debug('批量获取掌握度', [
  1948. 'student_id' => $studentId,
  1949. 'kp_count' => count($kpCodes),
  1950. 'found_count' => count($masteryRecords),
  1951. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1952. ]);
  1953. $allMastery = $masteryRecords;
  1954. } catch (\Exception $e) {
  1955. Log::warning('批量获取掌握度失败,将使用默认值', [
  1956. 'student_id' => $studentId,
  1957. 'error' => $e->getMessage()
  1958. ]);
  1959. }
  1960. }
  1961. foreach ($kpCodes as $kpCode) {
  1962. if ($studentId) {
  1963. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1964. // 薄弱点权重更高
  1965. if (in_array($kpCode, $weaknessFilter)) {
  1966. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1967. } else {
  1968. // 掌握度越低,权重越高
  1969. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1970. }
  1971. Log::debug('计算知识点权重', [
  1972. 'kp_code' => $kpCode,
  1973. 'mastery' => $mastery,
  1974. 'weight' => $kpWeights[$kpCode]
  1975. ]);
  1976. } else {
  1977. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1978. }
  1979. }
  1980. // 3. 按题型分配题目数量(权重用于题型内排序)
  1981. $selectedQuestions = [];
  1982. // 将所有题目合并
  1983. $weightedQuestions = [];
  1984. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1985. foreach ($kpQuestions as $q) {
  1986. $q['kp_code'] = $kpCode;
  1987. $weightedQuestions[] = $q;
  1988. }
  1989. }
  1990. // ========== 知识点优先选择机制 ==========
  1991. // 摸底测试的核心目标是最大化知识点覆盖
  1992. // 题型只是约束条件(每种至少1题)
  1993. // 首先按题型分组
  1994. $questionsByType = [
  1995. 'choice' => [],
  1996. 'fill' => [],
  1997. 'answer' => [],
  1998. ];
  1999. foreach ($weightedQuestions as $q) {
  2000. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2001. if ($qid && isset($questionTypeCache[$qid])) {
  2002. $type = $questionTypeCache[$qid];
  2003. } else {
  2004. $type = $this->determineQuestionType($q);
  2005. if ($qid) {
  2006. $questionTypeCache[$qid] = $type;
  2007. }
  2008. }
  2009. if (!isset($questionsByType[$type])) {
  2010. $type = 'answer'; // 默认归类为answer
  2011. }
  2012. $questionsByType[$type][] = $q;
  2013. }
  2014. // ========== 步骤1:按题型分配题目 ==========
  2015. $selectedQuestions = [];
  2016. // 【区分】根据 assembleType 决定是否使用知识点覆盖优先机制
  2017. // - 0:摸底测试,优先扩大知识点覆盖
  2018. // - 2:知识点组卷,也应尽量覆盖请求中的多个知识点,避免被单一 KP 吞掉
  2019. $useKnowledgePointPriority = in_array($assembleType, [0, 2], true);
  2020. $kpSelected = []; // 已选知识点记录
  2021. // 【新增】非摸底类型:按比例计算每种题型的目标数量
  2022. $typeTargets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2023. if (!$useKnowledgePointPriority) {
  2024. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  2025. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  2026. $allocated = 0;
  2027. $fractions = [];
  2028. foreach ($ratioMap as $type => $ratioKey) {
  2029. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  2030. $exact = $totalQuestions * $ratio / $totalRatio;
  2031. $typeTargets[$type] = (int) floor($exact);
  2032. $fractions[$type] = $exact - floor($exact);
  2033. $allocated += $typeTargets[$type];
  2034. }
  2035. // 余数分配给小数部分最大的题型
  2036. $remainder = $totalQuestions - $allocated;
  2037. arsort($fractions);
  2038. foreach ($fractions as $type => $frac) {
  2039. if ($remainder <= 0) break;
  2040. $typeTargets[$type]++;
  2041. $remainder--;
  2042. }
  2043. Log::debug('selectQuestionsByMastery: 题型目标分配', [
  2044. 'total_questions' => $totalQuestions,
  2045. 'targets' => $typeTargets,
  2046. ]);
  2047. }
  2048. // 确保每种题型至少选1题
  2049. foreach (['choice', 'fill', 'answer'] as $type) {
  2050. if (empty($questionsByType[$type])) {
  2051. Log::warning('题型分配:题型无题目', ['type' => $type]);
  2052. continue;
  2053. }
  2054. // 按权重排序该题型的题目
  2055. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  2056. $kpA = $a['kp_code'] ?? '';
  2057. $kpB = $b['kp_code'] ?? '';
  2058. $weightA = $kpWeights[$kpA] ?? 1.0;
  2059. $weightB = $kpWeights[$kpB] ?? 1.0;
  2060. return $weightB <=> $weightA;
  2061. });
  2062. // 【修复】摸底测试题型基础分配:记录每个题型的知识点分布
  2063. $typeKpDistribution = [];
  2064. foreach ($questionsByType[$type] as $q) {
  2065. $kpCode = $q['kp_code'] ?? '';
  2066. if (!isset($typeKpDistribution[$kpCode])) {
  2067. $typeKpDistribution[$kpCode] = 0;
  2068. }
  2069. $typeKpDistribution[$kpCode]++;
  2070. }
  2071. Log::debug('摸底测试题型基础分配', [
  2072. 'type' => $type,
  2073. 'total_in_type' => count($questionsByType[$type]),
  2074. 'kp_count' => count($typeKpDistribution)
  2075. ]);
  2076. // 根据策略选择题目
  2077. if ($useKnowledgePointPriority) {
  2078. // 知识点优先:assemble_type=2 先从原始请求知识点里选;摸底则扩大覆盖
  2079. $selectedInThisType = 0;
  2080. $candidate = null;
  2081. foreach ($questionsByType[$type] as $q) {
  2082. $kpCode = $q['kp_code'] ?? '';
  2083. if ($shouldRestrictToRequestedKps && ! isset($requestedKpSet[$kpCode])) {
  2084. continue;
  2085. }
  2086. if (!isset($kpSelected[$kpCode])) {
  2087. $candidate = $q;
  2088. break; // 只选1题
  2089. }
  2090. }
  2091. if ($candidate === null && $shouldRestrictToRequestedKps) {
  2092. foreach ($questionsByType[$type] as $q) {
  2093. $kpCode = $q['kp_code'] ?? '';
  2094. if (isset($requestedKpSet[$kpCode])) {
  2095. $candidate = $q;
  2096. break;
  2097. }
  2098. }
  2099. }
  2100. if ($candidate !== null) {
  2101. $kpCode = $candidate['kp_code'] ?? '';
  2102. $selectedQuestions[] = $candidate;
  2103. $kpSelected[$kpCode] = true;
  2104. $selectedInThisType++;
  2105. Log::debug('题型基础分配(知识点优先)', [
  2106. 'type' => $type,
  2107. 'kp' => $kpCode,
  2108. 'question_id' => $candidate['id'] ?? 'unknown',
  2109. 'selected_in_type' => $selectedInThisType
  2110. ]);
  2111. }
  2112. Log::debug('知识点优先题型基础分配完成', [
  2113. 'type' => $type,
  2114. 'selected_count' => $selectedInThisType
  2115. ]);
  2116. } else {
  2117. // 非摸底:按目标数量从该题型池中选题
  2118. $target = $typeTargets[$type] ?? 0;
  2119. $selectedIds = array_column($selectedQuestions, 'id');
  2120. $taken = 0;
  2121. foreach ($questionsByType[$type] as $q) {
  2122. if ($taken >= $target) break;
  2123. $qid = $q['id'] ?? null;
  2124. if ($qid && !in_array($qid, $selectedIds)) {
  2125. $selectedQuestions[] = $q;
  2126. $selectedIds[] = $qid;
  2127. $taken++;
  2128. }
  2129. }
  2130. $typeTargets[$type . '_actual'] = $taken;
  2131. Log::debug('题型按比例分配', [
  2132. 'type' => $type,
  2133. 'target' => $target,
  2134. 'actual' => $taken
  2135. ]);
  2136. }
  2137. }
  2138. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  2139. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  2140. // 【重要】添加排序前的知识点分布日志
  2141. $preSortKpDistribution = [];
  2142. foreach ($allQuestions as $q) {
  2143. $kpCode = $q['kp_code'] ?? '';
  2144. if (!isset($preSortKpDistribution[$kpCode])) {
  2145. $preSortKpDistribution[$kpCode] = 0;
  2146. }
  2147. $preSortKpDistribution[$kpCode]++;
  2148. }
  2149. Log::debug('selectQuestionsByMastery: 排序前知识点分布', [
  2150. 'total_questions' => count($allQuestions),
  2151. 'kp_distribution' => $preSortKpDistribution
  2152. ]);
  2153. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  2154. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  2155. $kpA = $a['kp_code'] ?? '';
  2156. $kpB = $b['kp_code'] ?? '';
  2157. $weightA = $kpWeights[$kpA] ?? 1.0;
  2158. $weightB = $kpWeights[$kpB] ?? 1.0;
  2159. // 主要按权重排序
  2160. if ($weightA != $weightB) {
  2161. return $weightB <=> $weightA;
  2162. }
  2163. // 权重相同时,添加随机排序而不是按ID排序
  2164. // 使用随机因子确保相同权重的知识点有公平的选中机会
  2165. return mt_rand(-1, 1);
  2166. });
  2167. // 【重要】添加排序后的知识点分布日志
  2168. $postSortKpDistribution = [];
  2169. $postSortFirst50 = []; // 记录前50题的知识点分布
  2170. foreach ($allQuestions as $idx => $q) {
  2171. $kpCode = $q['kp_code'] ?? '';
  2172. if (!isset($postSortKpDistribution[$kpCode])) {
  2173. $postSortKpDistribution[$kpCode] = 0;
  2174. }
  2175. $postSortKpDistribution[$kpCode]++;
  2176. // 记录前50题的知识点
  2177. if ($idx < 50) {
  2178. $postSortFirst50[] = $kpCode;
  2179. }
  2180. }
  2181. Log::debug('selectQuestionsByMastery: 排序后知识点分布', [
  2182. 'total_questions' => count($allQuestions),
  2183. 'kp_distribution' => $postSortKpDistribution
  2184. ]);
  2185. // 【修复】摸底测试继续选择题目:记录详细的选题过程
  2186. Log::debug('摸底测试继续选择题目开始', [
  2187. 'selected_count_after_basic' => count($selectedQuestions),
  2188. 'total_questions' => $totalQuestions,
  2189. 'selected_kp_codes' => array_keys($kpSelected),
  2190. 'available_kp_count' => count($preSortKpDistribution),
  2191. 'strategy' => $useKnowledgePointPriority ? '知识点覆盖优先' : '无知识点限制'
  2192. ]);
  2193. if ($useKnowledgePointPriority) {
  2194. // 知识点优先:assemble_type=2 先补齐原始请求知识点,再允许请求知识点重复,最后才使用 fallback KP
  2195. $initialSelectedCount = count($selectedQuestions);
  2196. $prioritySelectedCount = 0;
  2197. $selectedIds = array_values(array_filter(array_column($selectedQuestions, 'id')));
  2198. if ($shouldRestrictToRequestedKps) {
  2199. foreach ($allQuestions as $q) {
  2200. if (count($selectedQuestions) >= $totalQuestions) {
  2201. break;
  2202. }
  2203. $kpCode = $q['kp_code'] ?? '';
  2204. $qid = $q['id'] ?? null;
  2205. if (!isset($requestedKpSet[$kpCode]) || $qid === null || in_array($qid, $selectedIds)) {
  2206. continue;
  2207. }
  2208. if (!isset($kpSelected[$kpCode])) {
  2209. $selectedQuestions[] = $q;
  2210. $selectedIds[] = $qid;
  2211. $kpSelected[$kpCode] = true;
  2212. $prioritySelectedCount++;
  2213. Log::debug('继续选择题目(请求知识点优先)', [
  2214. 'kp' => $kpCode,
  2215. 'id' => $qid,
  2216. 'priority_selected_count' => $prioritySelectedCount,
  2217. 'total_selected' => count($selectedQuestions)
  2218. ]);
  2219. }
  2220. }
  2221. } else {
  2222. foreach ($allQuestions as $q) {
  2223. if (count($selectedQuestions) >= $totalQuestions) break;
  2224. $kpCode = $q['kp_code'] ?? '';
  2225. if (!isset($kpSelected[$kpCode])) {
  2226. $selectedQuestions[] = $q;
  2227. $kpSelected[$kpCode] = true;
  2228. $prioritySelectedCount++;
  2229. Log::debug('继续选择题目(知识点优先)', [
  2230. 'kp' => $kpCode,
  2231. 'id' => $q['id'] ?? 'unknown',
  2232. 'priority_selected_count' => $prioritySelectedCount,
  2233. 'total_selected' => count($selectedQuestions)
  2234. ]);
  2235. }
  2236. }
  2237. }
  2238. Log::debug('摸底测试优先阶段完成', [
  2239. 'priority_selected_count' => $prioritySelectedCount,
  2240. 'total_selected' => count($selectedQuestions),
  2241. 'unique_kp_count' => count($kpSelected),
  2242. 'note' => '优先选择未选过知识点的题目'
  2243. ]);
  2244. // 【修复】降级策略:如果仍未达到目标数量,允许重复选择知识点
  2245. if (count($selectedQuestions) < $totalQuestions) {
  2246. Log::warning('selectQuestionsByMastery: 知识点优先策略无法满足数量要求,启用降级策略', [
  2247. 'requested_count' => $totalQuestions,
  2248. 'selected_count' => count($selectedQuestions),
  2249. 'priority_selected_count' => $prioritySelectedCount,
  2250. 'unique_kp_count' => count($kpSelected),
  2251. 'available_kp_count' => count($preSortKpDistribution),
  2252. 'note' => '将允许重复选择知识点以达到目标数量'
  2253. ]);
  2254. $fallbackSelectedCount = 0;
  2255. $selectedIds = array_values(array_filter(array_column($selectedQuestions, 'id')));
  2256. if ($shouldRestrictToRequestedKps) {
  2257. foreach ($allQuestions as $q) {
  2258. if (count($selectedQuestions) >= $totalQuestions) {
  2259. break;
  2260. }
  2261. $kpCode = $q['kp_code'] ?? '';
  2262. $qid = $q['id'] ?? null;
  2263. if ($qid === null || in_array($qid, $selectedIds) || !isset($requestedKpSet[$kpCode])) {
  2264. continue;
  2265. }
  2266. $selectedQuestions[] = $q;
  2267. $selectedIds[] = $qid;
  2268. $fallbackSelectedCount++;
  2269. Log::debug('降级选择题目(请求知识点重复)', [
  2270. 'kp' => $kpCode,
  2271. 'id' => $qid,
  2272. 'fallback_selected_count' => $fallbackSelectedCount,
  2273. 'current_count' => count($selectedQuestions)
  2274. ]);
  2275. }
  2276. }
  2277. foreach ($allQuestions as $q) {
  2278. if (count($selectedQuestions) >= $totalQuestions) break;
  2279. $qid = $q['id'] ?? null;
  2280. if ($qid && !in_array($qid, $selectedIds)) {
  2281. $selectedQuestions[] = $q;
  2282. $selectedIds[] = $qid;
  2283. $fallbackSelectedCount++;
  2284. Log::debug('降级选择题目(允许知识点重复)', [
  2285. 'kp' => $q['kp_code'] ?? 'unknown',
  2286. 'id' => $qid,
  2287. 'fallback_selected_count' => $fallbackSelectedCount,
  2288. 'current_count' => count($selectedQuestions)
  2289. ]);
  2290. }
  2291. }
  2292. Log::debug('摸底测试降级阶段完成', [
  2293. 'fallback_selected_count' => $fallbackSelectedCount,
  2294. 'total_selected' => count($selectedQuestions),
  2295. 'note' => '允许重复选择知识点补充数量'
  2296. ]);
  2297. }
  2298. } else {
  2299. // 非摸底:题型不足时,缺口按优先级补到其他题型
  2300. $totalSelected = count($selectedQuestions);
  2301. if ($totalSelected < $totalQuestions) {
  2302. $deficit = $totalQuestions - $totalSelected;
  2303. $selectedIds = array_column($selectedQuestions, 'id');
  2304. // 按补充优先级:填空 > 解答 > 选择(避免解答题独占缺口)
  2305. $supplementOrder = ['fill', 'answer', 'choice'];
  2306. Log::debug('题型缺口补充开始', [
  2307. 'deficit' => $deficit,
  2308. 'current_count' => $totalSelected,
  2309. 'target' => $totalQuestions,
  2310. 'supplement_order' => $supplementOrder,
  2311. ]);
  2312. foreach ($supplementOrder as $type) {
  2313. if ($deficit <= 0) break;
  2314. foreach ($questionsByType[$type] as $q) {
  2315. if ($deficit <= 0) break;
  2316. $qid = $q['id'] ?? null;
  2317. if ($qid && !in_array($qid, $selectedIds)) {
  2318. $selectedQuestions[] = $q;
  2319. $selectedIds[] = $qid;
  2320. $deficit--;
  2321. }
  2322. }
  2323. }
  2324. Log::debug('题型缺口补充完成', [
  2325. 'final_count' => count($selectedQuestions),
  2326. 'target' => $totalQuestions,
  2327. ]);
  2328. }
  2329. }
  2330. // 【移除】删除步骤3的多余逻辑
  2331. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2332. Log::info('selectQuestionsByMastery 完成', [
  2333. 'total_questions' => $totalQuestions,
  2334. 'selected_count' => count($selectedQuestions),
  2335. 'success' => count($selectedQuestions) === $totalQuestions,
  2336. 'assemble_type' => $assembleType,
  2337. 'strategy' => $useKnowledgePointPriority ? '知识点覆盖优先' : '无知识点限制',
  2338. 'requested_kp_selection' => $this->buildRequestedKpSelectionStats($selectedQuestions, $requestedKpCodes),
  2339. 'type_distribution' => array_count_values(array_map(function($q) {
  2340. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2341. if ($qid && isset($questionTypeCache[$qid])) {
  2342. return $questionTypeCache[$qid];
  2343. }
  2344. return $this->determineQuestionType($q);
  2345. }, $selectedQuestions)),
  2346. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2347. ]);
  2348. // 【重要】最终截取到目标数量(如果超过)
  2349. if (count($selectedQuestions) > $totalQuestions) {
  2350. Log::info('题目数量超过目标,进行最终截取', [
  2351. 'before' => count($selectedQuestions),
  2352. 'after' => $totalQuestions
  2353. ]);
  2354. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2355. }
  2356. // 【重要】添加最终数量验证日志
  2357. Log::debug('selectQuestionsByMastery: 最终题目数量验证', [
  2358. 'before_final_check' => count($selectedQuestions),
  2359. 'target_count' => $totalQuestions,
  2360. 'is_array' => is_array($selectedQuestions)
  2361. ]);
  2362. // 【新增】最终知识点分布统计
  2363. $finalKpDistribution = array_count_values(array_column($selectedQuestions, 'kp_code'));
  2364. Log::debug('摸底测试最终知识点分布', [
  2365. 'final_total_count' => count($selectedQuestions),
  2366. 'target_count' => $totalQuestions,
  2367. 'final_kp_distribution' => $finalKpDistribution,
  2368. 'unique_kp_count' => count($finalKpDistribution),
  2369. 'success' => count($selectedQuestions) === $totalQuestions,
  2370. 'kp_coverage_rate' => count($finalKpDistribution) / max(count($preSortKpDistribution), 1) * 100
  2371. ]);
  2372. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2373. $finalQuestions = [];
  2374. $seenQuestionIds = [];
  2375. $duplicateCount = 0;
  2376. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2377. foreach ($selectedQuestions as $question) {
  2378. $qbId = $question['question_bank_id'] ?? $question['id'];
  2379. if (!in_array($qbId, $seenQuestionIds)) {
  2380. $seenQuestionIds[] = $qbId;
  2381. $finalQuestions[] = $question;
  2382. // 统计题型分布
  2383. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2384. $type = null;
  2385. if ($qid && isset($questionTypeCache[$qid])) {
  2386. $type = $questionTypeCache[$qid];
  2387. } else {
  2388. $type = $this->determineQuestionType($question);
  2389. if ($qid) {
  2390. $questionTypeCache[$qid] = $type;
  2391. }
  2392. }
  2393. if (isset($typeDistribution[$type])) {
  2394. $typeDistribution[$type]++;
  2395. }
  2396. } else {
  2397. $duplicateCount++;
  2398. Log::warning('发现重复题目(已自动移除)', [
  2399. 'question_id' => $qbId,
  2400. 'duplicate_count' => $duplicateCount
  2401. ]);
  2402. }
  2403. }
  2404. // 【重要】如果去重后数量不足,补充到目标数量
  2405. if (count($finalQuestions) < $totalQuestions) {
  2406. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2407. 'final_count' => count($finalQuestions),
  2408. 'target_count' => $totalQuestions,
  2409. 'need_more' => $totalQuestions - count($finalQuestions)
  2410. ]);
  2411. // 从原始题目中选择未选过的题目补充
  2412. $usedIds = array_column($finalQuestions, 'id');
  2413. $supplementCount = 0;
  2414. foreach ($selectedQuestions as $question) {
  2415. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2416. $qid = $question['id'] ?? null;
  2417. if ($qid && !in_array($qid, $usedIds)) {
  2418. $finalQuestions[] = $question;
  2419. $usedIds[] = $qid;
  2420. $supplementCount++;
  2421. }
  2422. }
  2423. Log::debug('selectQuestionsByMastery: 补充完成', [
  2424. 'supplement_added' => $supplementCount,
  2425. 'final_count_after_supplement' => count($finalQuestions)
  2426. ]);
  2427. }
  2428. Log::debug('最终排查完成', [
  2429. 'original_count' => count($selectedQuestions),
  2430. 'final_count' => count($finalQuestions),
  2431. 'duplicate_removed' => $duplicateCount,
  2432. 'final_type_distribution' => $typeDistribution,
  2433. 'target_count' => $totalQuestions
  2434. ]);
  2435. // 【重要】确保返回的题目数量正确
  2436. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2437. Log::debug('selectQuestionsByMastery: 返回结果', [
  2438. 'return_count' => count($finalQuestions),
  2439. 'target_count' => $totalQuestions,
  2440. 'success' => count($finalQuestions) === $totalQuestions
  2441. ]);
  2442. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2443. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2444. return $finalQuestions;
  2445. }
  2446. /**
  2447. * 错题追练复用知识点组卷时使用:按计划里的 KP 配额、题型配额和难度上限选题。
  2448. *
  2449. * @param array<int, array<string, mixed>> $questions
  2450. * @param array<int, string> $requestedKpCodes
  2451. * @param array<string, int> $kpTargetCounts
  2452. * @param array<string, float|int|string> $maxDifficultyByKp
  2453. * @param array<string, array<string, int>> $typeTargetsByKp
  2454. * @return array<int, array<string, mixed>>
  2455. */
  2456. private function selectQuestionsByKpTargets(
  2457. array $questions,
  2458. int $totalQuestions,
  2459. array $requestedKpCodes,
  2460. array $kpTargetCounts,
  2461. array $maxDifficultyByKp,
  2462. array $typeTargetsByKp
  2463. ): array {
  2464. $normalizedKpTargetCounts = [];
  2465. foreach ($kpTargetCounts as $kpCode => $count) {
  2466. $count = (int) $count;
  2467. if ($count > 0) {
  2468. $normalizedKpTargetCounts[(string) $kpCode] = $count;
  2469. }
  2470. }
  2471. $kpTargetCounts = $normalizedKpTargetCounts;
  2472. if ($kpTargetCounts === [] || $totalQuestions <= 0) {
  2473. return [];
  2474. }
  2475. $targetKpOrder = array_values(array_filter($requestedKpCodes, static fn ($kp) => isset($kpTargetCounts[$kp])));
  2476. foreach (array_keys($kpTargetCounts) as $kpCode) {
  2477. if (! in_array($kpCode, $targetKpOrder, true)) {
  2478. $targetKpOrder[] = $kpCode;
  2479. }
  2480. }
  2481. $targetKpSet = array_fill_keys(array_keys($kpTargetCounts), true);
  2482. $questionsByKp = [];
  2483. $supplementQuestions = [];
  2484. foreach ($questions as $question) {
  2485. $kpCode = (string) ($question['kp_code'] ?? '');
  2486. if ($kpCode === '') {
  2487. continue;
  2488. }
  2489. $questionsByKp[$kpCode][] = $question;
  2490. if (! isset($targetKpSet[$kpCode])) {
  2491. $supplementQuestions[] = $question;
  2492. }
  2493. }
  2494. $selected = [];
  2495. $usedIds = [];
  2496. $shortageByKp = [];
  2497. foreach ($targetKpOrder as $kpCode) {
  2498. $need = min((int) ($kpTargetCounts[$kpCode] ?? 0), max(0, $totalQuestions - count($selected)));
  2499. if ($need <= 0) {
  2500. continue;
  2501. }
  2502. $maxDifficulty = $this->normalizeAssemblyDifficulty($maxDifficultyByKp[$kpCode] ?? null);
  2503. $typeTargets = $typeTargetsByKp[$kpCode] ?? [];
  2504. $directSelected = $this->takeQuestionsForPracticeTarget(
  2505. $questionsByKp[$kpCode] ?? [],
  2506. $need,
  2507. $maxDifficulty,
  2508. $typeTargets,
  2509. $usedIds
  2510. );
  2511. foreach ($directSelected as $question) {
  2512. $question['practice_target_kp_code'] = $kpCode;
  2513. $question['practice_target_difficulty'] = $maxDifficulty;
  2514. $selected[] = $question;
  2515. }
  2516. $remainingNeed = $need - count($directSelected);
  2517. if ($remainingNeed > 0 && $supplementQuestions !== []) {
  2518. $supplementSelected = $this->takeQuestionsForPracticeTarget(
  2519. $supplementQuestions,
  2520. $remainingNeed,
  2521. $maxDifficulty,
  2522. [],
  2523. $usedIds
  2524. );
  2525. foreach ($supplementSelected as $question) {
  2526. $question['practice_target_kp_code'] = $kpCode;
  2527. $question['practice_target_difficulty'] = $maxDifficulty;
  2528. $question['practice_supplement_kp_code'] = $question['kp_code'] ?? null;
  2529. $selected[] = $question;
  2530. }
  2531. $remainingNeed -= count($supplementSelected);
  2532. }
  2533. if ($remainingNeed > 0) {
  2534. $shortageByKp[$kpCode] = $remainingNeed;
  2535. }
  2536. }
  2537. if (count($selected) < $totalQuestions) {
  2538. $remainingNeed = $totalQuestions - count($selected);
  2539. $targetPool = [];
  2540. foreach ($targetKpOrder as $kpCode) {
  2541. $targetPool = array_merge($targetPool, $questionsByKp[$kpCode] ?? []);
  2542. }
  2543. $backfillSelected = $this->takeQuestionsForPracticeTarget(
  2544. $targetPool,
  2545. $remainingNeed,
  2546. null,
  2547. [],
  2548. $usedIds
  2549. );
  2550. foreach ($backfillSelected as $question) {
  2551. $question['practice_backfill_reason'] = 'target_kp_shortage';
  2552. $selected[] = $question;
  2553. }
  2554. $remainingNeed = $totalQuestions - count($selected);
  2555. if ($remainingNeed > 0 && $supplementQuestions !== []) {
  2556. $supplementBackfill = $this->takeQuestionsForPracticeTarget(
  2557. $supplementQuestions,
  2558. $remainingNeed,
  2559. null,
  2560. [],
  2561. $usedIds
  2562. );
  2563. foreach ($supplementBackfill as $question) {
  2564. $question['practice_backfill_reason'] = 'supplement_kp_shortage';
  2565. $selected[] = $question;
  2566. }
  2567. }
  2568. Log::info('selectQuestionsByKpTargets: applied global backfill', [
  2569. 'target_count' => $totalQuestions,
  2570. 'selected_count' => count($selected),
  2571. 'shortage_by_kp' => $shortageByKp,
  2572. 'backfill_count' => count($selected) - ($totalQuestions - array_sum($shortageByKp)),
  2573. ]);
  2574. }
  2575. if (count($selected) < $totalQuestions) {
  2576. Log::warning('selectQuestionsByKpTargets: planned KP selection produced fewer questions', [
  2577. 'target_count' => $totalQuestions,
  2578. 'selected_count' => count($selected),
  2579. 'shortage_by_kp' => $shortageByKp,
  2580. 'kp_target_counts' => $kpTargetCounts,
  2581. 'available_kp_distribution' => array_map('count', $questionsByKp),
  2582. ]);
  2583. }
  2584. Log::info('selectQuestionsByKpTargets 完成', [
  2585. 'target_count' => $totalQuestions,
  2586. 'selected_count' => count($selected),
  2587. 'kp_target_counts' => $kpTargetCounts,
  2588. 'selected_kp_distribution' => array_count_values(array_column($selected, 'kp_code')),
  2589. 'practice_target_distribution' => array_count_values(array_column($selected, 'practice_target_kp_code')),
  2590. ]);
  2591. return array_slice($selected, 0, $totalQuestions);
  2592. }
  2593. /**
  2594. * @param array<int, array<string, mixed>> $pool
  2595. * @param array<string, int> $typeTargets
  2596. * @param array<string, bool> $usedIds
  2597. * @return array<int, array<string, mixed>>
  2598. */
  2599. private function takeQuestionsForPracticeTarget(
  2600. array $pool,
  2601. int $need,
  2602. ?float $maxDifficulty,
  2603. array $typeTargets,
  2604. array &$usedIds
  2605. ): array {
  2606. if ($need <= 0 || $pool === []) {
  2607. return [];
  2608. }
  2609. $candidateBuckets = ['choice' => [], 'fill' => [], 'answer' => []];
  2610. $questionPayloadMapper = app(QuestionPayloadMapper::class);
  2611. foreach ($pool as $question) {
  2612. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2613. if ($id === '' || isset($usedIds[$id])) {
  2614. continue;
  2615. }
  2616. $difficulty = $this->normalizeAssemblyDifficulty($question['difficulty'] ?? null) ?? 0.5;
  2617. $type = $questionPayloadMapper->normalizeQuestionType((string) ($question['question_type'] ?? $question['type'] ?? ''))
  2618. ?? $this->determineQuestionType($question);
  2619. if (! isset($candidateBuckets[$type])) {
  2620. $type = 'answer';
  2621. }
  2622. $question['practice_match_delta'] = $maxDifficulty !== null ? round($maxDifficulty - $difficulty, 4) : 0.0;
  2623. $question['practice_candidate_difficulty'] = $difficulty;
  2624. $candidateBuckets[$type][] = $question;
  2625. }
  2626. foreach ($candidateBuckets as &$bucket) {
  2627. usort($bucket, function (array $a, array $b) use ($maxDifficulty): int {
  2628. return $this->comparePracticeDifficulty($a, $b, $maxDifficulty);
  2629. });
  2630. }
  2631. unset($bucket);
  2632. $selected = [];
  2633. foreach (['choice', 'fill', 'answer'] as $type) {
  2634. $target = min((int) ($typeTargets[$type] ?? 0), $need - count($selected));
  2635. if ($target <= 0) {
  2636. continue;
  2637. }
  2638. while ($target > 0 && ! empty($candidateBuckets[$type])) {
  2639. $question = array_shift($candidateBuckets[$type]);
  2640. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2641. if ($id === '' || isset($usedIds[$id])) {
  2642. continue;
  2643. }
  2644. $selected[] = $question;
  2645. $usedIds[$id] = true;
  2646. $target--;
  2647. }
  2648. }
  2649. $remaining = array_merge($candidateBuckets['choice'], $candidateBuckets['fill'], $candidateBuckets['answer']);
  2650. usort($remaining, function (array $a, array $b) use ($maxDifficulty): int {
  2651. return $this->comparePracticeDifficulty($a, $b, $maxDifficulty);
  2652. });
  2653. foreach ($remaining as $question) {
  2654. if (count($selected) >= $need) {
  2655. break;
  2656. }
  2657. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2658. if ($id === '' || isset($usedIds[$id])) {
  2659. continue;
  2660. }
  2661. $selected[] = $question;
  2662. $usedIds[$id] = true;
  2663. }
  2664. return $selected;
  2665. }
  2666. private function comparePracticeDifficulty(array $a, array $b, ?float $targetDifficulty): int
  2667. {
  2668. $da = $this->normalizeAssemblyDifficulty($a['difficulty'] ?? null) ?? 0.5;
  2669. $db = $this->normalizeAssemblyDifficulty($b['difficulty'] ?? null) ?? 0.5;
  2670. if ($targetDifficulty === null) {
  2671. $scoreA = abs(0.5 - $da);
  2672. $scoreB = abs(0.5 - $db);
  2673. } else {
  2674. $scoreA = $da <= $targetDifficulty
  2675. ? $targetDifficulty - $da
  2676. : 1 + ($da - $targetDifficulty);
  2677. $scoreB = $db <= $targetDifficulty
  2678. ? $targetDifficulty - $db
  2679. : 1 + ($db - $targetDifficulty);
  2680. }
  2681. if ($scoreA !== $scoreB) {
  2682. return $scoreA <=> $scoreB;
  2683. }
  2684. return ((int) ($a['id'] ?? $a['question_id'] ?? 0)) <=> ((int) ($b['id'] ?? $b['question_id'] ?? 0));
  2685. }
  2686. private function normalizeAssemblyDifficulty(mixed $difficulty): ?float
  2687. {
  2688. if ($difficulty === null || $difficulty === '') {
  2689. return null;
  2690. }
  2691. if (! is_numeric($difficulty)) {
  2692. return null;
  2693. }
  2694. $value = (float) $difficulty;
  2695. if ($value > 1) {
  2696. $value = $value / 5;
  2697. }
  2698. return max(0.0, min(1.0, $value));
  2699. }
  2700. /**
  2701. * @param array<int, array<string, mixed>> $questions
  2702. * @param array<int, string> $requestedKpCodes
  2703. * @return array<string, mixed>
  2704. */
  2705. private function buildRequestedKpSelectionStats(array $questions, array $requestedKpCodes): array
  2706. {
  2707. $requestedKpCodes = array_values(array_unique(array_filter($requestedKpCodes)));
  2708. if ($requestedKpCodes === []) {
  2709. return [
  2710. 'requested_kp_codes' => [],
  2711. 'requested_kp_selected_count' => 0,
  2712. 'related_kp_selected_count' => 0,
  2713. 'requested_kp_distribution' => [],
  2714. 'related_kp_distribution' => [],
  2715. ];
  2716. }
  2717. $requestedKpSet = array_fill_keys($requestedKpCodes, true);
  2718. $requestedDistribution = [];
  2719. $relatedDistribution = [];
  2720. foreach ($questions as $question) {
  2721. $kpCode = (string) ($question['kp_code'] ?? '');
  2722. if ($kpCode === '') {
  2723. continue;
  2724. }
  2725. if (isset($requestedKpSet[$kpCode])) {
  2726. $requestedDistribution[$kpCode] = ($requestedDistribution[$kpCode] ?? 0) + 1;
  2727. } else {
  2728. $relatedDistribution[$kpCode] = ($relatedDistribution[$kpCode] ?? 0) + 1;
  2729. }
  2730. }
  2731. return [
  2732. 'requested_kp_codes' => $requestedKpCodes,
  2733. 'requested_kp_selected_count' => array_sum($requestedDistribution),
  2734. 'related_kp_selected_count' => array_sum($relatedDistribution),
  2735. 'requested_kp_distribution' => $requestedDistribution,
  2736. 'related_kp_distribution' => $relatedDistribution,
  2737. ];
  2738. }
  2739. /**
  2740. * @param array<int, array<string, mixed>> $questions
  2741. * @return array<string, mixed>
  2742. */
  2743. private function buildSupplementQuestionStats(array $questions): array
  2744. {
  2745. $kpDistribution = array_count_values(array_filter(array_map(
  2746. static fn ($question) => (string) ($question['kp_code'] ?? ''),
  2747. $questions
  2748. )));
  2749. arsort($kpDistribution);
  2750. return [
  2751. 'supplement_kp_distribution_topn' => array_slice($kpDistribution, 0, 10, true),
  2752. 'supplement_kp_sample' => array_slice(array_keys($kpDistribution), 0, 10),
  2753. ];
  2754. }
  2755. /**
  2756. * 获取学生对特定知识点的掌握度
  2757. */
  2758. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2759. {
  2760. try {
  2761. $mastery = DB::table('student_mastery')
  2762. ->where('student_id', $studentId)
  2763. ->where('kp', $kpCode)
  2764. ->value('mastery');
  2765. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2766. } catch (\Exception $e) {
  2767. Log::error('Get Student Kp Mastery Error', [
  2768. 'student_id' => $studentId,
  2769. 'kp_code' => $kpCode,
  2770. 'error' => $e->getMessage()
  2771. ]);
  2772. return 0.5;
  2773. }
  2774. }
  2775. /**
  2776. * 根据题型和难度配比调整题目
  2777. */
  2778. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2779. {
  2780. Log::debug('开始题型配比调整', [
  2781. 'input_questions' => count($questions),
  2782. 'target_count' => $targetCount,
  2783. 'type_ratio' => $typeRatio
  2784. ]);
  2785. // 缓存题目类型,避免重复计算
  2786. $questionTypeCache = [];
  2787. // 按题型分桶
  2788. $buckets = [
  2789. 'choice' => [],
  2790. 'fill' => [],
  2791. 'answer' => [],
  2792. ];
  2793. foreach ($questions as $q) {
  2794. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2795. if ($qid && isset($questionTypeCache[$qid])) {
  2796. $type = $questionTypeCache[$qid];
  2797. } else {
  2798. $type = $this->determineQuestionType($q);
  2799. if ($qid) {
  2800. $questionTypeCache[$qid] = $type;
  2801. }
  2802. }
  2803. if (!isset($buckets[$type])) {
  2804. $type = 'answer';
  2805. }
  2806. $buckets[$type][] = $q;
  2807. }
  2808. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2809. // 修复:不自动减少目标数量,确保达到用户要求
  2810. $availableCount = count($questions);
  2811. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2812. Log::debug('题型配比调整前桶统计', [
  2813. 'target_count' => $targetCount,
  2814. 'available_count' => $availableCount,
  2815. 'targets' => $targets,
  2816. 'bucket_counts' => [
  2817. 'choice' => count($buckets['choice']),
  2818. 'fill' => count($buckets['fill']),
  2819. 'answer' => count($buckets['answer']),
  2820. ],
  2821. 'raw_ratio' => $typeRatio,
  2822. ]);
  2823. // 随机打乱桶
  2824. foreach ($buckets as $k => $v) {
  2825. if (!empty($v)) {
  2826. shuffle($v);
  2827. $buckets[$k] = $v;
  2828. }
  2829. }
  2830. $selected = [];
  2831. $selectedIds = [];
  2832. // 按目标数依次取题
  2833. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2834. $need = $targets[$typeKey] ?? 0;
  2835. if ($need <= 0 || empty($buckets[$typeKey])) {
  2836. continue;
  2837. }
  2838. $take = min($need, count($buckets[$typeKey]));
  2839. $slice = array_slice($buckets[$typeKey], 0, $take);
  2840. foreach ($slice as $q) {
  2841. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2842. if (isset($selectedIds[$id])) {
  2843. continue;
  2844. }
  2845. $selected[] = $q;
  2846. $selectedIds[$id] = true;
  2847. }
  2848. }
  2849. // 不足则从剩余题中补齐
  2850. if (count($selected) < $targetCount) {
  2851. $remaining = [];
  2852. foreach ($buckets as $v) {
  2853. foreach ($v as $q) {
  2854. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2855. if (!isset($selectedIds[$id])) {
  2856. $remaining[] = $q;
  2857. }
  2858. }
  2859. }
  2860. shuffle($remaining);
  2861. $needMore = $targetCount - count($selected);
  2862. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2863. }
  2864. // 截断至目标数
  2865. $selected = array_slice($selected, 0, $targetCount);
  2866. // 使用缓存统计题型分布
  2867. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2868. foreach ($selected as $q) {
  2869. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2870. if ($qid && isset($questionTypeCache[$qid])) {
  2871. $type = $questionTypeCache[$qid];
  2872. } else {
  2873. $type = $this->determineQuestionType($q);
  2874. }
  2875. if (isset($selectedCounts[$type])) {
  2876. $selectedCounts[$type]++;
  2877. }
  2878. }
  2879. Log::debug('题型配比调整完成', [
  2880. 'target_count' => $targetCount,
  2881. 'targets' => $targets,
  2882. 'selected_counts' => $selectedCounts,
  2883. 'final_selected_count' => count($selected)
  2884. ]);
  2885. return $selected;
  2886. }
  2887. private function determineQuestionType(array $q): string
  2888. {
  2889. // 优先信任结构化题型字段,避免解答题被题干模式误判。
  2890. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2891. if (is_string($typeField)) {
  2892. $t = strtolower($typeField);
  2893. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2894. return 'choice';
  2895. }
  2896. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2897. return 'fill';
  2898. }
  2899. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2900. return 'answer';
  2901. }
  2902. }
  2903. // 结构化字段不可用时,再根据题目内容启发式判断。
  2904. $stem = $q['stem'] ?? $q['content'] ?? '';
  2905. // 处理 stem 可能是数组的情况
  2906. if (is_array($stem)) {
  2907. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2908. }
  2909. $tags = $q['tags'] ?? '';
  2910. // 处理 tags 可能是数组的情况
  2911. if (is_array($tags)) {
  2912. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2913. }
  2914. $skills = $q['skills'] ?? [];
  2915. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2916. if (is_string($stem)) {
  2917. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2918. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2919. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2920. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2921. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2922. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2923. // 至少有2个选项就认为是选择题(降低阈值)
  2924. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2925. if ($optionCount >= 2) {
  2926. return 'choice';
  2927. }
  2928. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2929. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2930. return 'choice';
  2931. }
  2932. }
  2933. // 2. 根据技能点判断
  2934. if (is_array($skills) && !empty($skills)) {
  2935. // 过滤非字符串元素,避免 implode 报错
  2936. $skillsFiltered = array_filter($skills, 'is_string');
  2937. if (!empty($skillsFiltered)) {
  2938. $skillsStr = implode(',', $skillsFiltered);
  2939. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2940. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2941. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2942. }
  2943. }
  2944. // 3. 无法识别时回落为解答题
  2945. // 4. 根据标签判断
  2946. if (is_string($tags)) {
  2947. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2948. return 'choice';
  2949. }
  2950. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2951. return 'fill';
  2952. }
  2953. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2954. return 'answer';
  2955. }
  2956. }
  2957. // 5. 根据options字段判断
  2958. if (!empty($q['options']) && is_array($q['options'])) {
  2959. return 'choice';
  2960. }
  2961. // 6. 填空题特征:连续下划线或明显的填空括号
  2962. if (is_string($stem)) {
  2963. // 检查填空题特征:连续下划线
  2964. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2965. return 'fill';
  2966. }
  2967. // 空括号填空
  2968. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2969. return 'fill';
  2970. }
  2971. }
  2972. // 7. 根据题干内容关键词判断
  2973. if (is_string($stem)) {
  2974. // 有证明、解答、计算、求证等关键词的是解答题
  2975. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2976. return 'answer';
  2977. }
  2978. }
  2979. // 默认是解答题(更安全的默认值)
  2980. return 'answer';
  2981. }
  2982. // 【移除】删除未使用的mapDifficultyLevel方法
  2983. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2984. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2985. {
  2986. $map = [
  2987. '选择题' => 'choice',
  2988. '填空题' => 'fill',
  2989. '解答题' => 'answer',
  2990. ];
  2991. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2992. foreach ($questionTypeRatio as $label => $ratio) {
  2993. $key = $map[$label] ?? null;
  2994. if (!$key) {
  2995. continue;
  2996. }
  2997. $cnt = (int) round($targetCount * ($ratio / 100));
  2998. if ($ratio > 0 && $cnt < 1) {
  2999. $cnt = 1;
  3000. }
  3001. $targets[$key] = $cnt;
  3002. }
  3003. $sum = array_sum($targets);
  3004. if ($sum === 0) {
  3005. $targets['answer'] = $targetCount;
  3006. return $targets;
  3007. }
  3008. while ($sum > $targetCount) {
  3009. arsort($targets);
  3010. foreach ($targets as $k => $v) {
  3011. if ($v > 1) {
  3012. $targets[$k]--;
  3013. $sum--;
  3014. break;
  3015. }
  3016. }
  3017. }
  3018. if ($sum < $targetCount) {
  3019. $ratioByKey = [
  3020. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  3021. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  3022. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  3023. ];
  3024. while ($sum < $targetCount) {
  3025. arsort($ratioByKey);
  3026. $k = array_key_first($ratioByKey);
  3027. $targets[$k]++;
  3028. $sum++;
  3029. }
  3030. }
  3031. return $targets;
  3032. }
  3033. /**
  3034. * 提交手动评分结果到 LearningAnalytics
  3035. *
  3036. * @param array $data 包含 student_id, paper_id, grades 的数组
  3037. * @return array
  3038. */
  3039. public function submitManualGrading(array $data): array
  3040. {
  3041. try {
  3042. $response = Http::timeout($this->timeout)
  3043. ->post($this->baseUrl . '/api/ocr/analyze', [
  3044. 'student_id' => $data['student_id'],
  3045. 'paper_id' => $data['paper_id'],
  3046. 'answers' => $data['grades'],
  3047. ]);
  3048. if ($response->successful()) {
  3049. Log::info('Manual grading submitted successfully', [
  3050. 'student_id' => $data['student_id'],
  3051. 'paper_id' => $data['paper_id'],
  3052. 'question_count' => count($data['grades'])
  3053. ]);
  3054. return $response->json();
  3055. }
  3056. Log::error('Submit Manual Grading Error', [
  3057. 'data' => $data,
  3058. 'status' => $response->status(),
  3059. 'response' => $response->body()
  3060. ]);
  3061. return [
  3062. 'error' => true,
  3063. 'message' => 'Failed to submit manual grading'
  3064. ];
  3065. } catch (\Exception $e) {
  3066. Log::error('Submit Manual Grading Exception', [
  3067. 'error' => $e->getMessage(),
  3068. 'data' => $data
  3069. ]);
  3070. return [
  3071. 'error' => true,
  3072. 'message' => $e->getMessage()
  3073. ];
  3074. }
  3075. }
  3076. /**
  3077. * 分析学生作答结果
  3078. *
  3079. * @param array $data 包含 paper_id, student_id, answers 等
  3080. * @return array
  3081. */
  3082. public function analyzeStudentAnswers(array $data): array
  3083. {
  3084. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  3085. 'student_id' => $data['student_id'] ?? null,
  3086. 'paper_id' => $data['paper_id'] ?? null,
  3087. ]);
  3088. return [
  3089. 'success' => false,
  3090. 'message' => 'analysis_api_disabled',
  3091. ];
  3092. }
  3093. /**
  3094. * 智能补充题目(当指定知识点的题目不足时)
  3095. *
  3096. * @param int $grade 年级
  3097. * @param array $existingKpCodes 已有的知识点代码(用于排除)
  3098. * @param int $needCount 需要补充的题目数量
  3099. * @param int $difficultyCategory 难度类别
  3100. * @param int|null $textbookId 教材ID(用于限制补充范围,避免超纲)
  3101. * @param array $excludeQuestionIds 排除的题目ID(学生已做过,避免重复)
  3102. * @param array|null $textbookCatalogNodeIds 当前选中的章节节点ID;与 textbookId 同时传入时,仅从同教材的前章节补充(未学章节不补充)
  3103. * @param string|null $studentId 学生ID(无教材时用于获取「已学知识点」,仅从已学内容补充,避免未学章节)
  3104. * @return array 补充的题目列表
  3105. */
  3106. private function getSupplementaryQuestionsForGrade(
  3107. int $grade,
  3108. array $existingKpCodes,
  3109. int $needCount,
  3110. int $difficultyCategory,
  3111. ?int $textbookId = null,
  3112. array $excludeQuestionIds = [],
  3113. ?array $textbookCatalogNodeIds = null,
  3114. ?string $studentId = null
  3115. ): array {
  3116. try {
  3117. Log::info('getSupplementaryQuestionsForGrade: 开始智能补充', [
  3118. 'grade' => $grade,
  3119. 'existing_kp_count' => count($existingKpCodes),
  3120. 'need_count' => $needCount,
  3121. 'difficulty_category' => $difficultyCategory,
  3122. 'textbook_id' => $textbookId,
  3123. 'student_id' => $studentId ? '(有)' : '(无)',
  3124. 'exclude_count' => count($excludeQuestionIds),
  3125. 'has_chapter_scope' => !empty($textbookCatalogNodeIds),
  3126. ]);
  3127. // 【核心】补充范围:只从「学过的」内容补充,不能从未学知识点或年级对应章节中选
  3128. // - 有 textbookId:从 textbook_id -> 章节 -> 章节知识点关联表 取 kp_code(若有 chapter scope 再收缩到前章节)
  3129. // - 无 textbookId 且有 studentId:从学生做过的题目对应知识点(getStudentLearnedKpCodes)补充
  3130. // - 无 textbookId 且无 studentId:无法确定学过的内容,不补充
  3131. $gradeKpCodes = [];
  3132. if ($textbookId) {
  3133. $allCatalogNodeIds = DB::table('textbook_catalog_nodes')
  3134. ->where('textbook_id', $textbookId)
  3135. ->pluck('id')
  3136. ->map(static fn ($id) => (int) $id)
  3137. ->toArray();
  3138. $gradeKpCodes = $this->getKpCodesForCatalogChapterIds($allCatalogNodeIds);
  3139. Log::info('getSupplementaryQuestionsForGrade: 教材模式,按章节关联知识点补题', [
  3140. 'kp_count' => count($gradeKpCodes),
  3141. 'textbook_id' => $textbookId,
  3142. 'catalog_node_count' => count($allCatalogNodeIds),
  3143. ]);
  3144. } elseif ($studentId) {
  3145. $learnedKps = $this->getStudentLearnedKpCodes($studentId);
  3146. $gradeKpCodes = array_values(array_diff($learnedKps, $existingKpCodes));
  3147. Log::info('getSupplementaryQuestionsForGrade: 无教材模式,使用学生已学知识点', [
  3148. 'learned_count' => count($learnedKps),
  3149. 'after_exclude_existing' => count($gradeKpCodes),
  3150. ]);
  3151. } else {
  3152. Log::warning('getSupplementaryQuestionsForGrade: 无教材且无学生ID,无法确定学过的内容,不补充');
  3153. return [];
  3154. }
  3155. if (empty($gradeKpCodes)) {
  3156. Log::warning('getSupplementaryQuestionsForGrade: 无可用知识点,跳过补充', [
  3157. 'grade' => $grade,
  3158. 'textbook_id' => $textbookId,
  3159. 'note' => $textbookId ? '教材知识点不足' : '学生已学知识点不足或与当前选题重复',
  3160. ]);
  3161. return [];
  3162. }
  3163. // 有教材且带章节:用 textbook_chapter_knowledge_relation 由「前章节」解析知识点,再按 kp_code 选题(不用 questions.textbook_catalog_nodes_id)
  3164. $effectiveKpCodes = $gradeKpCodes;
  3165. if ($textbookId && ! empty($textbookCatalogNodeIds)) {
  3166. $allowedNodeIds = $this->getEarlierChapterNodeIds((int) $textbookId, $textbookCatalogNodeIds);
  3167. if (empty($allowedNodeIds)) {
  3168. Log::warning('getSupplementaryQuestionsForGrade: 未找到前章节节点,跳过补充');
  3169. return [];
  3170. }
  3171. $chapterKpCodes = $this->getKpCodesForCatalogChapterIds($allowedNodeIds);
  3172. if (empty($chapterKpCodes)) {
  3173. Log::warning('getSupplementaryQuestionsForGrade: 前章节在 textbook_chapter_knowledge_relation 中无知识点', [
  3174. 'allowed_node_ids' => $allowedNodeIds,
  3175. ]);
  3176. return [];
  3177. }
  3178. $effectiveKpCodes = array_values(array_intersect($gradeKpCodes, $chapterKpCodes));
  3179. if (empty($effectiveKpCodes)) {
  3180. Log::warning('getSupplementaryQuestionsForGrade: 教材年级知识点与章节关联知识点无交集', [
  3181. 'grade_kp_count' => count($gradeKpCodes),
  3182. 'chapter_kp_count' => count($chapterKpCodes),
  3183. ]);
  3184. return [];
  3185. }
  3186. Log::info('getSupplementaryQuestionsForGrade: 按章节关联知识点缩小补充范围', [
  3187. 'allowed_chapter_nodes' => count($allowedNodeIds),
  3188. 'chapter_kp_count' => count($chapterKpCodes),
  3189. 'effective_kp_count' => count($effectiveKpCodes),
  3190. ]);
  3191. }
  3192. // 查询同年级其他知识点的题目
  3193. $query = \App\Models\Question::query();
  3194. // 只获取审核通过的题目
  3195. $query->where('audit_status', 0);
  3196. // 【新增】排除学生已做过的题目
  3197. if (!empty($excludeQuestionIds)) {
  3198. $query->whereNotIn('id', $excludeQuestionIds);
  3199. }
  3200. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  3201. if ($stageGrade !== null) {
  3202. $query->where('grade', $stageGrade);
  3203. Log::info('getSupplementaryQuestionsForGrade: 应用学段筛选', [
  3204. 'input_grade' => $grade,
  3205. 'stage_grade' => $stageGrade
  3206. ]);
  3207. }
  3208. // 排除已选知识点
  3209. if (!empty($existingKpCodes)) {
  3210. $query->whereNotIn('kp_code', $existingKpCodes);
  3211. }
  3212. $query->whereIn('kp_code', $effectiveKpCodes);
  3213. // 筛选有解题思路的题目
  3214. $query->whereNotNull('solution')
  3215. ->where('solution', '!=', '')
  3216. ->where('solution', '!=', '[]');
  3217. // 【重要】移除题目分类限制,允许补充其他分类的题目
  3218. // $query->where('question_category', 1); // 移除这行
  3219. // 根据难度类别调整查询
  3220. $difficultyRanges = $this->getDifficultyRangesForCategory($difficultyCategory);
  3221. $query->where(function ($q) use ($difficultyRanges) {
  3222. foreach ($difficultyRanges as $range) {
  3223. $q->orWhereBetween('difficulty', [$range['min'], $range['max']]);
  3224. }
  3225. });
  3226. // 随机排序,增加多样性
  3227. $query->inRandomOrder()
  3228. ->limit($needCount * 2); // 多取一些,后续筛选
  3229. $supplementaryQuestions = $query->get();
  3230. Log::info('getSupplementaryQuestionsForGrade: 查询完成', [
  3231. 'found_count' => $supplementaryQuestions->count(),
  3232. 'need_count' => $needCount
  3233. ]);
  3234. // 格式化题目
  3235. $formatted = [];
  3236. foreach ($supplementaryQuestions as $question) {
  3237. // 优先使用题库原始题型
  3238. $stem = $question->stem ?? '';
  3239. $options = is_array($question->options) ? $question->options : (json_decode($question->options ?? '[]', true) ?: []);
  3240. $correctAnswer = $question->correct_answer ?? '';
  3241. $questionType = $question->question_type ?? 'answer';
  3242. $formatted[] = [
  3243. 'id' => $question->id,
  3244. 'question_bank_id' => $question->id,
  3245. 'question_type' => $questionType,
  3246. 'kp_code' => $question->kp_code,
  3247. 'difficulty' => $question->difficulty !== null ? (float) $question->difficulty : 0.5,
  3248. 'stem' => $stem,
  3249. 'options' => $options,
  3250. 'correct_answer' => $correctAnswer,
  3251. 'solution' => $question->solution,
  3252. 'score' => $question->score ?? 4,
  3253. 'estimated_time' => $question->estimated_time ?? 300,
  3254. 'metadata' => [
  3255. 'question_type_label' => $questionType === 'choice' ? '选择题' : ($questionType === 'fill' ? '填空题' : '解答题'),
  3256. 'difficulty_label' => $this->getDifficultyLabelFromObject($question->difficulty ?? 0.5),
  3257. 'is_supplementary' => true
  3258. ]
  3259. ];
  3260. }
  3261. // 随机选择需要的数量
  3262. shuffle($formatted);
  3263. $selected = array_slice($formatted, 0, $needCount);
  3264. Log::info('getSupplementaryQuestionsForGrade: 补充完成', [
  3265. 'supplementary_count' => count($selected),
  3266. 'kp_distribution' => array_count_values(array_column($selected, 'kp_code'))
  3267. ]);
  3268. return $selected;
  3269. } catch (\Exception $e) {
  3270. Log::error('getSupplementaryQuestionsForGrade: 补充失败', [
  3271. 'grade' => $grade,
  3272. 'need_count' => $needCount,
  3273. 'error' => $e->getMessage()
  3274. ]);
  3275. return [];
  3276. }
  3277. }
  3278. /**
  3279. * 获取同教材中「当前选中章节及之前」的节点 ID 列表(用于前章节补充,避免未学章节)
  3280. *
  3281. * @param int $textbookId 教材ID
  3282. * @param array $chapterNodeIds 当前选中的章节节点ID
  3283. * @return array 允许的节点ID列表(sort_order <= 选中章节的最大 sort_order)
  3284. */
  3285. private function getEarlierChapterNodeIds(int $textbookId, array $chapterNodeIds): array
  3286. {
  3287. if (empty($chapterNodeIds)) {
  3288. return [];
  3289. }
  3290. try {
  3291. $maxSortOrder = DB::table('textbook_catalog_nodes')
  3292. ->where('textbook_id', $textbookId)
  3293. ->whereIn('id', $chapterNodeIds)
  3294. ->max('sort_order');
  3295. if ($maxSortOrder === null) {
  3296. Log::warning('getEarlierChapterNodeIds: 未找到选中章节的 sort_order', [
  3297. 'textbook_id' => $textbookId,
  3298. 'chapter_node_ids' => $chapterNodeIds
  3299. ]);
  3300. return [];
  3301. }
  3302. $allowedNodeIds = DB::table('textbook_catalog_nodes')
  3303. ->where('textbook_id', $textbookId)
  3304. ->where('sort_order', '<=', $maxSortOrder)
  3305. ->pluck('id')
  3306. ->toArray();
  3307. Log::info('getEarlierChapterNodeIds: 前章节节点', [
  3308. 'textbook_id' => $textbookId,
  3309. 'max_sort_order' => $maxSortOrder,
  3310. 'allowed_node_count' => count($allowedNodeIds)
  3311. ]);
  3312. return $allowedNodeIds;
  3313. } catch (\Exception $e) {
  3314. Log::error('getEarlierChapterNodeIds: 查询失败', [
  3315. 'textbook_id' => $textbookId,
  3316. 'error' => $e->getMessage()
  3317. ]);
  3318. return [];
  3319. }
  3320. }
  3321. /**
  3322. * 获取指定年级的知识点列表
  3323. *
  3324. * @param int $grade 年级
  3325. * @param int|null $textbookId 教材ID(可选,用于限制在特定教材范围内,避免超纲)
  3326. * @return array 知识点代码列表
  3327. */
  3328. /**
  3329. * 获取学生「已学知识点」:通过该学生做过的题目(paper_questions)对应的 kp_code 推断
  3330. * 用于无教材信息时,智能补充仅从已学知识点中选,避免出现未学内容
  3331. *
  3332. * @param string|null $studentId 学生ID
  3333. * @return array 知识点代码列表(去重、非空)
  3334. */
  3335. private function getStudentLearnedKpCodes(?string $studentId): array
  3336. {
  3337. if (empty($studentId)) {
  3338. return [];
  3339. }
  3340. try {
  3341. $questionBankIds = \App\Models\PaperQuestion::query()
  3342. ->whereHas('paper', fn($q) => $q->where('student_id', $studentId))
  3343. ->pluck('question_bank_id')
  3344. ->unique()
  3345. ->filter()
  3346. ->values()
  3347. ->toArray();
  3348. if (empty($questionBankIds)) {
  3349. Log::info('getStudentLearnedKpCodes: 学生暂无做题记录', ['student_id' => $studentId]);
  3350. return [];
  3351. }
  3352. $kpCodes = \App\Models\Question::query()
  3353. ->whereIn('id', $questionBankIds)
  3354. ->whereNotNull('kp_code')
  3355. ->where('kp_code', '!=', '')
  3356. ->pluck('kp_code')
  3357. ->unique()
  3358. ->values()
  3359. ->toArray();
  3360. Log::info('getStudentLearnedKpCodes: 已学知识点', [
  3361. 'student_id' => $studentId,
  3362. 'kp_count' => count($kpCodes),
  3363. ]);
  3364. return $kpCodes;
  3365. } catch (\Exception $e) {
  3366. Log::error('getStudentLearnedKpCodes: 查询失败', [
  3367. 'student_id' => $studentId,
  3368. 'error' => $e->getMessage(),
  3369. ]);
  3370. return [];
  3371. }
  3372. }
  3373. /**
  3374. * 由 catalog 章节节点 ID 列表,从 textbook_chapter_knowledge_relation 取关联的知识点编码(用于选题,而非题目表上的章节字段)。
  3375. *
  3376. * @param array<int> $catalogChapterIds textbook_catalog_nodes.id
  3377. * @return list<string>
  3378. */
  3379. private function getKpCodesForCatalogChapterIds(array $catalogChapterIds): array
  3380. {
  3381. $ids = array_values(array_unique(array_filter(array_map(
  3382. static fn ($id) => (int) $id,
  3383. $catalogChapterIds
  3384. ), static fn (int $id) => $id > 0)));
  3385. if ($ids === []) {
  3386. return [];
  3387. }
  3388. return array_values(array_filter(array_unique(DB::table('textbook_chapter_knowledge_relation')
  3389. ->whereIn('catalog_chapter_id', $ids)
  3390. ->where(function ($q) {
  3391. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  3392. })
  3393. ->pluck('kp_code')
  3394. ->toArray())));
  3395. }
  3396. private function getGradeKnowledgePoints(int $grade, ?int $textbookId = null): array
  3397. {
  3398. try {
  3399. $query = DB::table('textbook_chapter_knowledge_relation as tckr')
  3400. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  3401. ->join('textbooks as t', 'tcn.textbook_id', '=', 't.id')
  3402. ->where('t.grade', $grade)
  3403. ->where(function ($q) {
  3404. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  3405. });
  3406. // 【修复超纲问题】如果有 textbook_id,严格限制在该教材范围内
  3407. // 避免七年级上册学生拿到七年级下册的知识点
  3408. if ($textbookId) {
  3409. $query->where('t.id', $textbookId);
  3410. Log::info('getGradeKnowledgePoints: 限制在指定教材范围内', [
  3411. 'grade' => $grade,
  3412. 'textbook_id' => $textbookId
  3413. ]);
  3414. }
  3415. $kpCodes = $query->distinct()
  3416. ->pluck('tckr.kp_code')
  3417. ->toArray();
  3418. Log::info('getGradeKnowledgePoints: 获取知识点完成', [
  3419. 'grade' => $grade,
  3420. 'textbook_id' => $textbookId,
  3421. 'kp_count' => count($kpCodes)
  3422. ]);
  3423. return array_filter($kpCodes);
  3424. } catch (\Exception $e) {
  3425. Log::error('getGradeKnowledgePoints: 查询失败', [
  3426. 'grade' => $grade,
  3427. 'textbook_id' => $textbookId,
  3428. 'error' => $e->getMessage()
  3429. ]);
  3430. return [];
  3431. }
  3432. }
  3433. /**
  3434. * 【新增】根据难度类别获取难度范围
  3435. */
  3436. private function getDifficultyRangesForCategory(int $difficultyCategory): array
  3437. {
  3438. $ranges = app(DifficultyDistributionService::class)->getRanges($difficultyCategory);
  3439. $segments = [];
  3440. foreach (['primary', 'high', 'low', 'secondary', 'fallback_low'] as $key) {
  3441. if (!isset($ranges[$key]) || !is_array($ranges[$key])) {
  3442. continue;
  3443. }
  3444. $min = $ranges[$key]['min'] ?? null;
  3445. $max = $ranges[$key]['max'] ?? null;
  3446. $percentage = $ranges[$key]['percentage'] ?? null;
  3447. if (!is_numeric($min) || !is_numeric($max)) {
  3448. continue;
  3449. }
  3450. // 仅将“目标占比 > 0”的区间用于补题查询,避免 0% 兜底区间误入候选池。
  3451. if (!is_numeric($percentage) || (float) $percentage <= 0.0) {
  3452. continue;
  3453. }
  3454. $segments[] = ['min' => (float) $min, 'max' => (float) $max];
  3455. }
  3456. if ($segments === []) {
  3457. return [['min' => 0.0, 'max' => 1.0]];
  3458. }
  3459. return $segments;
  3460. }
  3461. private function normalizeQuestionStageGrade(int $grade): ?int
  3462. {
  3463. if ($grade <= 0) {
  3464. return null;
  3465. }
  3466. // 年级转学段 todo:下一步需要视频小学
  3467. return $grade <= 9 ? 2 : 3;
  3468. }
  3469. /**
  3470. * 【新增】获取难度标签(重载版本)
  3471. */
  3472. private function getDifficultyLabelFromObject(?float $difficulty): string
  3473. {
  3474. if ($difficulty === null) return '未知';
  3475. if ($difficulty < 0.3) return '基础';
  3476. if ($difficulty < 0.7) return '中等';
  3477. return '拔高';
  3478. }
  3479. private function buildDifficultyDistributionStats(array $questions, int $difficultyCategory): array
  3480. {
  3481. if (empty($questions)) {
  3482. return [];
  3483. }
  3484. $service = app(DifficultyDistributionService::class);
  3485. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3486. $total = max(1, count($questions));
  3487. return array_map(static function ($bucket) use ($total) {
  3488. $count = count($bucket);
  3489. return [
  3490. 'count' => $count,
  3491. 'ratio' => round(($count / $total) * 100, 2),
  3492. ];
  3493. }, $buckets);
  3494. }
  3495. private function buildDifficultyDistributionShortage(array $questions, int $difficultyCategory, int $totalQuestions): array
  3496. {
  3497. $service = app(DifficultyDistributionService::class);
  3498. $distribution = $service->calculateDistribution($difficultyCategory, $totalQuestions);
  3499. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3500. $expected = [
  3501. 'primary_low' => 0,
  3502. 'primary_medium' => 0,
  3503. 'primary_high' => 0,
  3504. 'secondary' => 0,
  3505. 'other' => 0,
  3506. ];
  3507. foreach ($distribution as $level => $config) {
  3508. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3509. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  3510. }
  3511. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  3512. $shortage = [];
  3513. foreach ($expected as $bucketKey => $count) {
  3514. $actualCount = $actual[$bucketKey] ?? 0;
  3515. $shortage[$bucketKey] = [
  3516. 'expected' => $count,
  3517. 'actual' => $actualCount,
  3518. 'short' => max(0, $count - $actualCount),
  3519. ];
  3520. }
  3521. return $shortage;
  3522. }
  3523. /**
  3524. * 题型感知的难度分布选题
  3525. * 在每种题型内部应用难度分布,确保题型比例和难度分布同时被满足
  3526. */
  3527. private function applyTypeAwareDifficultyDistribution(
  3528. array $allQuestions,
  3529. array $selectedQuestions,
  3530. int $totalQuestions,
  3531. int $difficultyCategory,
  3532. array $questionTypeRatio
  3533. ): array {
  3534. $diffService = app(DifficultyDistributionService::class);
  3535. $distribution = $diffService->calculateDistribution($difficultyCategory, $totalQuestions);
  3536. // 1. 计算每种题型的目标数量
  3537. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  3538. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  3539. $typeTargets = [];
  3540. $fractions = [];
  3541. $allocated = 0;
  3542. foreach ($ratioMap as $type => $ratioKey) {
  3543. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  3544. $exact = $totalQuestions * $ratio / $totalRatio;
  3545. $typeTargets[$type] = (int) floor($exact);
  3546. $fractions[$type] = $exact - floor($exact);
  3547. $allocated += $typeTargets[$type];
  3548. }
  3549. $remainder = $totalQuestions - $allocated;
  3550. arsort($fractions);
  3551. foreach ($fractions as $type => $frac) {
  3552. if ($remainder <= 0) break;
  3553. $typeTargets[$type]++;
  3554. $remainder--;
  3555. }
  3556. // 2. 构建候选题池(合并 allQuestions + selectedQuestions 去重)
  3557. $candidatePool = [];
  3558. $seen = [];
  3559. foreach (array_merge($allQuestions, $selectedQuestions) as $q) {
  3560. $id = $q['id'] ?? null;
  3561. if ($id && !isset($seen[$id])) {
  3562. $seen[$id] = true;
  3563. $candidatePool[] = $q;
  3564. }
  3565. }
  3566. // 3. 按题型分组候选题
  3567. $candidatesByType = ['choice' => [], 'fill' => [], 'answer' => []];
  3568. foreach ($candidatePool as $q) {
  3569. $qType = $q['question_type'] ?? '';
  3570. if (isset($candidatesByType[$qType])) {
  3571. $candidatesByType[$qType][] = $q;
  3572. }
  3573. }
  3574. // 4. 在每种题型内按难度分桶选题
  3575. $result = [];
  3576. $usedIds = [];
  3577. $typeActual = [];
  3578. foreach ($ratioMap as $type => $ratioKey) {
  3579. $target = $typeTargets[$type];
  3580. if ($target <= 0) {
  3581. $typeActual[$type] = 0;
  3582. continue;
  3583. }
  3584. $typeCandidates = $candidatesByType[$type];
  3585. $buckets = $diffService->groupQuestionsByDifficultyRange($typeCandidates, $difficultyCategory);
  3586. // 按 distribution 比例在该题型内选题
  3587. $typeSelected = [];
  3588. foreach ($distribution as $level => $config) {
  3589. $levelRatio = $config['percentage'];
  3590. $levelTarget = max(0, (int) round($target * $levelRatio / 100));
  3591. if ($levelTarget <= 0) continue;
  3592. $rangeKey = $diffService->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3593. $bucket = $buckets[$rangeKey] ?? [];
  3594. shuffle($bucket);
  3595. $taken = 0;
  3596. foreach ($bucket as $q) {
  3597. if ($taken >= $levelTarget) break;
  3598. $qid = $q['id'] ?? null;
  3599. if ($qid && !isset($usedIds[$qid])) {
  3600. $typeSelected[] = $q;
  3601. $usedIds[$qid] = true;
  3602. $taken++;
  3603. }
  3604. }
  3605. }
  3606. // 如果难度分布不满足目标数,从该题型剩余题目补充
  3607. if (count($typeSelected) < $target) {
  3608. $supplementBucketOrder = array_values(array_unique(array_merge(
  3609. $diffService->getSupplementOrder($difficultyCategory),
  3610. ['primary_medium', 'primary_high', 'primary_low', 'secondary', 'other']
  3611. )));
  3612. $allTypeBuckets = [];
  3613. foreach ($supplementBucketOrder as $bucketKey) {
  3614. $allTypeBuckets = array_merge($allTypeBuckets, $buckets[$bucketKey] ?? []);
  3615. }
  3616. shuffle($allTypeBuckets);
  3617. foreach ($allTypeBuckets as $q) {
  3618. if (count($typeSelected) >= $target) break;
  3619. $qid = $q['id'] ?? null;
  3620. if ($qid && !isset($usedIds[$qid])) {
  3621. $typeSelected[] = $q;
  3622. $usedIds[$qid] = true;
  3623. }
  3624. }
  3625. }
  3626. $typeActual[$type] = count($typeSelected);
  3627. $result = array_merge($result, $typeSelected);
  3628. }
  3629. // 5. 如果总数不足(某题型候选不够),跨题型补充
  3630. if (count($result) < $totalQuestions) {
  3631. $deficit = $totalQuestions - count($result);
  3632. // 按 fill > choice > answer 优先级补充
  3633. $supplementOrder = ['fill', 'choice', 'answer'];
  3634. foreach ($supplementOrder as $type) {
  3635. if ($deficit <= 0) break;
  3636. $bucket = $candidatesByType[$type];
  3637. shuffle($bucket);
  3638. foreach ($bucket as $q) {
  3639. if ($deficit <= 0) break;
  3640. $qid = $q['id'] ?? null;
  3641. if ($qid && !isset($usedIds[$qid])) {
  3642. $result[] = $q;
  3643. $usedIds[$qid] = true;
  3644. $deficit--;
  3645. }
  3646. }
  3647. }
  3648. }
  3649. Log::info('LearningAnalyticsService: 题型感知难度分布详情', [
  3650. 'type_targets' => $typeTargets,
  3651. 'type_actual' => $typeActual,
  3652. 'total_result' => count($result),
  3653. 'difficulty_category' => $difficultyCategory,
  3654. 'candidates_by_type' => array_map('count', $candidatesByType),
  3655. ]);
  3656. return array_slice($result, 0, $totalQuestions);
  3657. }
  3658. /**
  3659. * 培优/竞赛卷的解答题更接近真实区分度:不允许用极低难度解答题兜底。
  3660. *
  3661. * 总题量优先级仍然很高:低难解答题先尝试替换为同题型合格题;没有同题型时,
  3662. * 再用任意非违规候选题补齐总数,避免因为题库供给不足直接少题。
  3663. *
  3664. * @param array<int, array<string, mixed>> $candidatePool
  3665. * @param array<int, array<string, mixed>> $selectedQuestions
  3666. * @return array<int, array<string, mixed>>
  3667. */
  3668. private function enforceAnswerDifficultyFloor(
  3669. array $candidatePool,
  3670. array $selectedQuestions,
  3671. int $difficultyCategory,
  3672. int $totalQuestions
  3673. ): array {
  3674. $floor = $this->answerDifficultyFloor($difficultyCategory);
  3675. if ($floor === null || empty($selectedQuestions)) {
  3676. return $selectedQuestions;
  3677. }
  3678. $selectedIds = [];
  3679. foreach ($selectedQuestions as $question) {
  3680. $id = $this->questionIdentity($question);
  3681. if ($id !== '') {
  3682. $selectedIds[$id] = true;
  3683. }
  3684. }
  3685. $candidates = [];
  3686. $seen = [];
  3687. foreach (array_merge($candidatePool, $selectedQuestions) as $question) {
  3688. $id = $this->questionIdentity($question);
  3689. if ($id === '' || isset($seen[$id])) {
  3690. continue;
  3691. }
  3692. $seen[$id] = true;
  3693. $candidates[] = $question;
  3694. }
  3695. usort($candidates, function (array $a, array $b) use ($difficultyCategory): int {
  3696. return $this->compareCandidateDifficultyFit($a, $b, $difficultyCategory);
  3697. });
  3698. $replacementUsed = [];
  3699. $removed = 0;
  3700. foreach ($selectedQuestions as $idx => $question) {
  3701. if (! $this->isLowAnswerQuestion($question, $floor)) {
  3702. continue;
  3703. }
  3704. $replacement = $this->takeReplacementQuestion(
  3705. $candidates,
  3706. $selectedIds,
  3707. $replacementUsed,
  3708. $floor,
  3709. true
  3710. );
  3711. if ($replacement === null) {
  3712. unset($selectedQuestions[$idx]);
  3713. $removed++;
  3714. continue;
  3715. }
  3716. $oldId = $this->questionIdentity($question);
  3717. if ($oldId !== '') {
  3718. unset($selectedIds[$oldId]);
  3719. }
  3720. $newId = $this->questionIdentity($replacement);
  3721. if ($newId !== '') {
  3722. $selectedIds[$newId] = true;
  3723. $replacementUsed[$newId] = true;
  3724. }
  3725. $selectedQuestions[$idx] = $replacement;
  3726. }
  3727. $selectedQuestions = array_values($selectedQuestions);
  3728. if (count($selectedQuestions) < $totalQuestions) {
  3729. foreach ($candidates as $candidate) {
  3730. if (count($selectedQuestions) >= $totalQuestions) {
  3731. break;
  3732. }
  3733. $id = $this->questionIdentity($candidate);
  3734. if ($id === '' || isset($selectedIds[$id]) || isset($replacementUsed[$id])) {
  3735. continue;
  3736. }
  3737. if ($this->isLowAnswerQuestion($candidate, $floor)) {
  3738. continue;
  3739. }
  3740. $selectedQuestions[] = $candidate;
  3741. $selectedIds[$id] = true;
  3742. }
  3743. }
  3744. if ($removed > 0 || count($selectedQuestions) < $totalQuestions) {
  3745. Log::warning('LearningAnalyticsService: 培优解答题难度护栏触发', [
  3746. 'difficulty_category' => $difficultyCategory,
  3747. 'answer_floor' => $floor,
  3748. 'removed_low_answer_count' => $removed,
  3749. 'final_count' => count($selectedQuestions),
  3750. 'target_count' => $totalQuestions,
  3751. ]);
  3752. }
  3753. return array_slice($selectedQuestions, 0, $totalQuestions);
  3754. }
  3755. private function answerDifficultyFloor(int $difficultyCategory): ?float
  3756. {
  3757. return match ($difficultyCategory) {
  3758. 3 => 0.4,
  3759. 4 => 0.5,
  3760. default => null,
  3761. };
  3762. }
  3763. private function isLowAnswerQuestion(array $question, float $floor): bool
  3764. {
  3765. return $this->determineQuestionType($question) === 'answer'
  3766. && (float) ($question['difficulty'] ?? 0.0) < $floor;
  3767. }
  3768. /**
  3769. * @param array<int, array<string, mixed>> $candidates
  3770. * @param array<string, bool> $selectedIds
  3771. * @param array<string, bool> $replacementUsed
  3772. */
  3773. private function takeReplacementQuestion(
  3774. array $candidates,
  3775. array $selectedIds,
  3776. array $replacementUsed,
  3777. float $floor,
  3778. bool $sameTypeOnly
  3779. ): ?array {
  3780. foreach ($candidates as $candidate) {
  3781. $id = $this->questionIdentity($candidate);
  3782. if ($id === '' || isset($selectedIds[$id]) || isset($replacementUsed[$id])) {
  3783. continue;
  3784. }
  3785. if ($sameTypeOnly && $this->determineQuestionType($candidate) !== 'answer') {
  3786. continue;
  3787. }
  3788. if ($this->isLowAnswerQuestion($candidate, $floor)) {
  3789. continue;
  3790. }
  3791. return $candidate;
  3792. }
  3793. return null;
  3794. }
  3795. private function compareCandidateDifficultyFit(array $a, array $b, int $difficultyCategory): int
  3796. {
  3797. $target = match ($difficultyCategory) {
  3798. 3 => 0.62,
  3799. 4 => 0.82,
  3800. default => 0.5,
  3801. };
  3802. $da = (float) ($a['difficulty'] ?? 0.5);
  3803. $db = (float) ($b['difficulty'] ?? 0.5);
  3804. $scoreA = abs($target - $da);
  3805. $scoreB = abs($target - $db);
  3806. if ($scoreA !== $scoreB) {
  3807. return $scoreA <=> $scoreB;
  3808. }
  3809. return $this->questionIdentity($a) <=> $this->questionIdentity($b);
  3810. }
  3811. private function questionIdentity(array $question): string
  3812. {
  3813. return (string) ($question['id'] ?? $question['question_id'] ?? $question['question_bank_id'] ?? '');
  3814. }
  3815. /**
  3816. * 统计题目列表中各题型的数量
  3817. */
  3818. private function countByType(array $questions): array
  3819. {
  3820. $counts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  3821. foreach ($questions as $q) {
  3822. $type = $q['question_type'] ?? '';
  3823. if (isset($counts[$type])) {
  3824. $counts[$type]++;
  3825. }
  3826. }
  3827. return $counts;
  3828. }
  3829. private function buildDistributionCandidates(array $allQuestions, array $selectedQuestions, int $difficultyCategory): array
  3830. {
  3831. if (empty($allQuestions)) {
  3832. return $selectedQuestions;
  3833. }
  3834. $service = app(DifficultyDistributionService::class);
  3835. $distribution = $service->calculateDistribution($difficultyCategory, max(1, count($selectedQuestions)));
  3836. $buckets = $service->groupQuestionsByDifficultyRange($allQuestions, $difficultyCategory);
  3837. $preferredBuckets = [];
  3838. foreach ($distribution as $level => $config) {
  3839. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3840. $preferredBuckets[$bucketKey] = true;
  3841. }
  3842. $candidates = [];
  3843. foreach (array_keys($preferredBuckets) as $bucketKey) {
  3844. foreach ($buckets[$bucketKey] ?? [] as $q) {
  3845. $candidates[] = $q;
  3846. }
  3847. }
  3848. foreach ($selectedQuestions as $q) {
  3849. $candidates[] = $q;
  3850. }
  3851. $seen = [];
  3852. $unique = [];
  3853. foreach ($candidates as $q) {
  3854. $id = $q['id'] ?? null;
  3855. if (!$id || isset($seen[$id])) {
  3856. continue;
  3857. }
  3858. $seen[$id] = true;
  3859. $unique[] = $q;
  3860. }
  3861. return $unique;
  3862. }
  3863. }