LearningAnalyticsService.php 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158
  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. $requestedKpSelectionStats = $this->buildRequestedKpSelectionStats(
  1381. $selectedQuestions,
  1382. $params['kp_code_list_original'] ?? $params['kp_codes'] ?? []
  1383. );
  1384. Log::info('LearningAnalyticsService: 最终选题分布', [
  1385. 'assemble_type' => $assembleType,
  1386. 'question_count' => count($selectedQuestions),
  1387. 'type_distribution' => $this->countByType($selectedQuestions),
  1388. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code')),
  1389. 'requested_kp_selection' => $assembleType === 2 ? $requestedKpSelectionStats : null,
  1390. ]);
  1391. return [
  1392. 'success' => true,
  1393. 'message' => '智能出卷成功',
  1394. 'questions' => $selectedQuestions,
  1395. // 【新增】传递章节摸底和智能组卷的关键字段
  1396. 'diagnostic_chapter_id' => $params['diagnostic_chapter_id'] ?? null,
  1397. 'explanation_kp_codes' => $params['explanation_kp_codes'] ?? null,
  1398. 'assemble_type' => $params['assembleType'] ?? null, // 策略可能修改assembleType(如章节智能→章节摸底)
  1399. 'stats' => [
  1400. 'total_selected' => count($selectedQuestions),
  1401. 'source_questions' => count($allQuestions),
  1402. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1403. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1404. })) : 0,
  1405. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1406. 'difficulty_category' => $difficultyCategory,
  1407. 'final_distribution' => $this->buildDifficultyDistributionStats($selectedQuestions, (int) $difficultyCategory),
  1408. 'final_distribution_shortage' => $this->buildDifficultyDistributionShortage(
  1409. $selectedQuestions,
  1410. (int) $difficultyCategory,
  1411. (int) $totalQuestions
  1412. ),
  1413. 'requested_kp_selection' => $assembleType === 2 ? $requestedKpSelectionStats : null,
  1414. // 【新增】章节知识点数量统计(教材组卷时)
  1415. 'chapter_knowledge_point_stats' => $params['chapter_knowledge_point_stats'] ?? null,
  1416. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? null
  1417. ]
  1418. ];
  1419. } catch (\Exception $e) {
  1420. Log::error('Generate Intelligent Exam Error', [
  1421. 'error' => $e->getMessage(),
  1422. 'trace' => $e->getTraceAsString()
  1423. ]);
  1424. return [
  1425. 'success' => false,
  1426. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1427. 'questions' => []
  1428. ];
  1429. }
  1430. }
  1431. /**
  1432. * @param array<int, array<string, mixed>> $questions
  1433. * @return array<int, array<string, mixed>>
  1434. */
  1435. private function dedupeQuestionsByBankId(array $questions): array
  1436. {
  1437. $seen = [];
  1438. $out = [];
  1439. foreach ($questions as $q) {
  1440. $id = $q['id'] ?? null;
  1441. if ($id === null || $id === '') {
  1442. continue;
  1443. }
  1444. $k = (string) $id;
  1445. if (isset($seen[$k])) {
  1446. continue;
  1447. }
  1448. $seen[$k] = true;
  1449. $out[] = $q;
  1450. }
  1451. return $out;
  1452. }
  1453. /**
  1454. * 知识点组卷补题:仅按补充 KP 列表查询,筛选条件与 getQuestionsFromBank 主查询一致(不调用教材/已学那条智能补题)。
  1455. *
  1456. * @param array<string> $kpCodes
  1457. * @param array<int|string> $excludeQuestionIds
  1458. * @return array<int, array<string, mixed>>
  1459. */
  1460. private function fetchQuestionsForKpAssembleSupplement(
  1461. array $kpCodes,
  1462. array $excludeQuestionIds,
  1463. int $grade,
  1464. array $skills = [],
  1465. ?int $questionCategory = null,
  1466. ?array $textbookCatalogNodeIds = null
  1467. ): array {
  1468. $kpCodes = array_values(array_unique(array_filter($kpCodes)));
  1469. if ($kpCodes === []) {
  1470. return [];
  1471. }
  1472. $query = \App\Models\Question::query()
  1473. ->where('audit_status', 0)
  1474. ->whereIn('kp_code', $kpCodes);
  1475. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  1476. if ($stageGrade !== null) {
  1477. $query->where('grade', $stageGrade);
  1478. }
  1479. if (! empty($skills)) {
  1480. $query->where(function ($q) use ($skills) {
  1481. foreach ($skills as $skill) {
  1482. $q->orWhere('tags', 'like', '%'.$skill.'%');
  1483. }
  1484. });
  1485. }
  1486. if (! empty($excludeQuestionIds)) {
  1487. $query->whereNotIn('id', $excludeQuestionIds);
  1488. }
  1489. if ($questionCategory !== null) {
  1490. $query->where('question_category', $questionCategory);
  1491. }
  1492. $query->whereNotNull('solution')
  1493. ->where('solution', '!=', '')
  1494. ->where('solution', '!=', '[]');
  1495. if (! empty($textbookCatalogNodeIds)) {
  1496. $query->whereIn('textbook_catalog_nodes_id', $textbookCatalogNodeIds);
  1497. }
  1498. return $query->inRandomOrder()->get()->map(function ($q) {
  1499. return [
  1500. 'id' => $q->id,
  1501. 'question_code' => $q->question_code,
  1502. 'kp_code' => $q->kp_code,
  1503. 'question_type' => $q->question_type,
  1504. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1505. 'stem' => $q->stem,
  1506. 'solution' => $q->solution,
  1507. 'metadata' => [
  1508. 'has_solution' => true,
  1509. 'is_choice' => $q->question_type === 'choice',
  1510. 'is_fill' => $q->question_type === 'fill',
  1511. 'is_answer' => $q->question_type === 'answer',
  1512. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1513. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type),
  1514. ],
  1515. ];
  1516. })->toArray();
  1517. }
  1518. /**
  1519. * 从题库获取题目
  1520. *
  1521. * @param array $kpCodes 知识点代码列表
  1522. * @param array $skills 技能标签列表
  1523. * @param string|null $studentId 学生ID
  1524. * @param array $questionTypeRatio 题型比例
  1525. * @param int $totalNeeded 需要的题目数量
  1526. * @param array $priorityQuestionIds 优先获取的题目ID(错题)
  1527. * @param array $excludeQuestionIds 排除的题目ID
  1528. * @param int|null $questionCategory 题目分类
  1529. * @param array|null $textbookCatalogNodeIds 教材章节节点ID
  1530. * @param int|null $grade 年级(用于智能补充时限制范围)
  1531. * @param int|null $textbookId 教材ID(用于智能补充时限制范围,避免超纲)
  1532. * @param int $difficultyCategory 难度类别(用于智能补充)
  1533. * @return array 题目列表
  1534. */
  1535. 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
  1536. {
  1537. $startTime = microtime(true);
  1538. try {
  1539. // 错题回顾:优先获取指定的学生错题
  1540. if (!empty($priorityQuestionIds)) {
  1541. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1542. if (!empty($priorityQuestions)) {
  1543. return $priorityQuestions;
  1544. } else {
  1545. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1546. return [];
  1547. }
  1548. }
  1549. $query = \App\Models\Question::query();
  1550. // 【新增】只获取审核通过的题目(audit_status = 0 表示合格)
  1551. $query->where('audit_status', 0);
  1552. // 按知识点筛选
  1553. if (!empty($kpCodes)) {
  1554. $query->whereIn('kp_code', $kpCodes);
  1555. }
  1556. // 按学段筛选(题库 grade: 2=初中, 3=高中)
  1557. if ($grade !== null) {
  1558. $stageGrade = $this->normalizeQuestionStageGrade((int) $grade);
  1559. if ($stageGrade !== null) {
  1560. $query->where('grade', $stageGrade);
  1561. }
  1562. }
  1563. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1564. if (!empty($skills)) {
  1565. $query->where(function ($q) use ($skills) {
  1566. foreach ($skills as $skill) {
  1567. $q->orWhere('tags', 'like', "%{$skill}%");
  1568. }
  1569. });
  1570. }
  1571. // 排除学生已做过的题目
  1572. if (!empty($excludeQuestionIds)) {
  1573. $query->whereNotIn('id', $excludeQuestionIds);
  1574. }
  1575. // 按题目分类筛选(如果指定了 question_category)
  1576. if ($questionCategory !== null) {
  1577. $query->where('question_category', $questionCategory);
  1578. }
  1579. // 筛选有解题思路的题目
  1580. $query->whereNotNull('solution')
  1581. ->where('solution', '!=', '')
  1582. ->where('solution', '!=', '[]');
  1583. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1584. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1585. // 【重要】移除数量限制,获取所有符合条件的题目
  1586. // 不使用limit()限制查询结果,让后续处理逻辑决定最终数量
  1587. $query->inRandomOrder();
  1588. $questions = $query->get();
  1589. // 转换为标准格式
  1590. $formattedQuestions = $questions->map(function ($q) {
  1591. return [
  1592. 'id' => $q->id,
  1593. 'question_code' => $q->question_code,
  1594. 'kp_code' => $q->kp_code,
  1595. 'question_type' => $q->question_type,
  1596. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1597. 'stem' => $q->stem,
  1598. 'solution' => $q->solution,
  1599. 'metadata' => [
  1600. 'has_solution' => true,
  1601. 'is_choice' => $q->question_type === 'choice',
  1602. 'is_fill' => $q->question_type === 'fill',
  1603. 'is_answer' => $q->question_type === 'answer',
  1604. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1605. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1606. ]
  1607. ];
  1608. })->toArray();
  1609. // 【重要】返回所有符合条件的题目,不限制数量
  1610. // 让上层调用者根据需要选择题目数量
  1611. $selectedQuestions = $formattedQuestions;
  1612. // 【修复】重新启用智能补充功能,增加 textbook_id 限制避免超纲
  1613. if ($totalNeeded > 0 && count($selectedQuestions) < $totalNeeded && $grade !== null) {
  1614. $deficit = $totalNeeded - count($selectedQuestions);
  1615. Log::info('assemble.supplement', [
  1616. 'stage' => 'start',
  1617. 'deficit' => $deficit,
  1618. 'current_count' => count($selectedQuestions),
  1619. 'target_count' => $totalNeeded,
  1620. 'grade' => $grade,
  1621. 'textbook_id' => $textbookId,
  1622. 'has_student_id' => ! empty($studentId),
  1623. 'has_chapter_scope' => ! empty($textbookCatalogNodeIds),
  1624. ]);
  1625. // 【修复超纲问题】补充策略:只从「学过的」内容补充
  1626. // - 有 textbook_id:从同教材的前章节补充
  1627. // - 无 textbook_id:从学生做过的题目对应的知识点补充,避免未学内容
  1628. $supplementaryQuestions = $this->getSupplementaryQuestionsForGrade(
  1629. $grade,
  1630. array_column($selectedQuestions, 'kp_code'),
  1631. $deficit,
  1632. $difficultyCategory,
  1633. $textbookId,
  1634. $excludeQuestionIds,
  1635. $textbookCatalogNodeIds ?? null,
  1636. $studentId
  1637. );
  1638. if (!empty($supplementaryQuestions)) {
  1639. $selectedQuestions = array_merge($selectedQuestions, $supplementaryQuestions);
  1640. Log::info('assemble.supplement', [
  1641. 'stage' => 'done',
  1642. 'supplement_count' => count($supplementaryQuestions),
  1643. 'after_count' => count($selectedQuestions),
  1644. 'target_count' => $totalNeeded,
  1645. 'grade' => $grade,
  1646. 'textbook_id' => $textbookId,
  1647. ]);
  1648. } else {
  1649. Log::info('assemble.supplement', [
  1650. 'stage' => 'empty',
  1651. 'supplement_count' => 0,
  1652. 'after_count' => count($selectedQuestions),
  1653. 'target_count' => $totalNeeded,
  1654. 'grade' => $grade,
  1655. 'textbook_id' => $textbookId,
  1656. ]);
  1657. }
  1658. }
  1659. return $selectedQuestions;
  1660. } catch (\Exception $e) {
  1661. Log::error('getQuestionsFromBank 查询失败', [
  1662. 'error' => $e->getMessage(),
  1663. 'trace' => $e->getTraceAsString()
  1664. ]);
  1665. throw $e;
  1666. }
  1667. }
  1668. /**
  1669. * 获取指定ID的题目详情
  1670. */
  1671. private function getLocalQuestionsByIds(array $questionIds): array
  1672. {
  1673. try {
  1674. // 通过QuestionBankService获取题目详情
  1675. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1676. // 批量获取题目详情
  1677. $response = $questionBankService->getQuestionsByIds($questionIds);
  1678. if (empty($response['data'])) {
  1679. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1680. 'requested_ids' => $questionIds
  1681. ]);
  1682. return [];
  1683. }
  1684. $questions = $response['data'];
  1685. // 转换为标准格式
  1686. $result = array_map(function ($q) {
  1687. $difficulty = $q['difficulty'] ?? 0.5;
  1688. return [
  1689. 'id' => $q['id'],
  1690. 'question_code' => $q['question_code'] ?? '',
  1691. 'kp_code' => $q['kp_code'] ?? '',
  1692. 'question_type' => $q['question_type'] ?? 'choice',
  1693. 'difficulty' => (float) $difficulty,
  1694. 'stem' => $q['stem'] ?? '',
  1695. 'solution' => $q['solution'] ?? '',
  1696. 'answer' => $q['answer'] ?? '',
  1697. 'metadata' => [
  1698. 'has_solution' => !empty($q['solution']),
  1699. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1700. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1701. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1702. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1703. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1704. ]
  1705. ];
  1706. }, $questions);
  1707. Log::info('getLocalQuestionsByIds 获取成功', [
  1708. 'requested_count' => count($questionIds),
  1709. 'found_count' => count($result),
  1710. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1711. 'question_ids' => array_slice($questionIds, 0, 20),
  1712. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1713. ]);
  1714. return $result;
  1715. } catch (\Exception $e) {
  1716. Log::error('getLocalQuestionsByIds 获取失败', [
  1717. 'question_ids' => $questionIds,
  1718. 'error' => $e->getMessage(),
  1719. 'trace' => $e->getTraceAsString()
  1720. ]);
  1721. return [];
  1722. }
  1723. }
  1724. /**
  1725. * 获取卷子的所有题目ID(不区分对错)
  1726. */
  1727. private function getPaperAllQuestions(array $paperIds): array
  1728. {
  1729. try {
  1730. // 查询 paper_questions 表获取所有题目ID
  1731. $questionIds = DB::table('paper_questions')
  1732. ->whereIn('paper_id', $paperIds)
  1733. ->pluck('question_bank_id')
  1734. ->unique()
  1735. ->filter()
  1736. ->values()
  1737. ->toArray();
  1738. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1739. 'paper_ids' => $paperIds,
  1740. 'question_count' => count($questionIds)
  1741. ]);
  1742. return $questionIds;
  1743. } catch (\Exception $e) {
  1744. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1745. 'paper_ids' => $paperIds,
  1746. 'error' => $e->getMessage()
  1747. ]);
  1748. return [];
  1749. }
  1750. }
  1751. /**
  1752. * 获取难度标签
  1753. */
  1754. private function getDifficultyLabel(?float $difficulty): string
  1755. {
  1756. if ($difficulty === null) {
  1757. return '未知';
  1758. }
  1759. return match (true) {
  1760. $difficulty < 0.4 => '基础',
  1761. $difficulty < 0.7 => '中等',
  1762. default => '拔高'
  1763. };
  1764. }
  1765. /**
  1766. * 获取题型标签
  1767. */
  1768. private function getQuestionTypeLabel(string $questionType): string
  1769. {
  1770. return match ($questionType) {
  1771. 'choice' => '选择题',
  1772. 'fill' => '填空题',
  1773. 'answer' => '解答题',
  1774. default => '未知题型'
  1775. };
  1776. }
  1777. /**
  1778. * 根据题型配比选择题目
  1779. * 注意: 难度配比调整由 QuestionLocalService 处理
  1780. */
  1781. private function selectQuestionsByRatio(
  1782. array $questions,
  1783. int $totalNeeded,
  1784. array $questionTypeRatio = []
  1785. ): array {
  1786. if (empty($questions)) {
  1787. return [];
  1788. }
  1789. // 如果没有配比要求,直接返回
  1790. if (empty($questionTypeRatio)) {
  1791. return array_slice($questions, 0, $totalNeeded);
  1792. }
  1793. $selected = [];
  1794. $usedIndices = [];
  1795. // 按题型配比选择
  1796. if (!empty($questionTypeRatio)) {
  1797. foreach ($questionTypeRatio as $type => $ratio) {
  1798. $count = (int) round(($ratio / 100) * $totalNeeded);
  1799. if ($count <= 0) continue;
  1800. $typeQuestions = [];
  1801. foreach ($questions as $idx => $q) {
  1802. if (in_array($idx, $usedIndices)) continue;
  1803. $qType = $q['question_type'] ?? '';
  1804. $label = $this->getQuestionTypeLabel($qType);
  1805. if ($label === $type) {
  1806. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1807. }
  1808. }
  1809. // 随机选择
  1810. shuffle($typeQuestions);
  1811. $selectedCount = min($count, count($typeQuestions));
  1812. for ($i = 0; $i < $selectedCount; $i++) {
  1813. $selected[] = $typeQuestions[$i]['question'];
  1814. $usedIndices[] = $typeQuestions[$i]['idx'];
  1815. }
  1816. }
  1817. }
  1818. // 如果还有空缺,补充剩余题目
  1819. // 注意: 难度配比调整由 QuestionLocalService 处理
  1820. if (count($selected) < $totalNeeded) {
  1821. foreach ($questions as $idx => $q) {
  1822. if (count($selected) >= $totalNeeded) break;
  1823. if (!in_array($idx, $usedIndices)) {
  1824. $selected[] = $q;
  1825. $usedIndices[] = $idx;
  1826. }
  1827. }
  1828. }
  1829. return array_slice($selected, 0, $totalNeeded);
  1830. }
  1831. /**
  1832. * 根据学生掌握度筛选题目
  1833. */
  1834. private function selectQuestionsByMastery(
  1835. array $questions,
  1836. ?string $studentId,
  1837. int $totalQuestions,
  1838. array $questionTypeRatio,
  1839. array $difficultyLevels,
  1840. array $weaknessFilter,
  1841. int $assembleType, // 新增assembleType参数
  1842. array $requestedKpCodes = [],
  1843. array $kpTargetCounts = [],
  1844. array $maxDifficultyByKp = [],
  1845. array $typeTargetsByKp = []
  1846. ): array {
  1847. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1848. // 如果题目数量超过目标,则截取到目标数量
  1849. // 如果题目数量不足,则使用所有题目,并记录警告
  1850. if (count($questions) > $totalQuestions) {
  1851. Log::debug('selectQuestionsByMastery: 题目数量超过目标,进行截取', [
  1852. 'question_count' => count($questions),
  1853. 'total_questions' => $totalQuestions
  1854. ]);
  1855. } else {
  1856. Log::warning('题目数量不足,将使用所有可用题目', [
  1857. 'available_count' => count($questions),
  1858. 'requested_count' => $totalQuestions,
  1859. 'note' => '可能需要补充题库或放宽筛选条件'
  1860. ]);
  1861. }
  1862. // 【移除】删除多余的难度筛选逻辑
  1863. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1864. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1865. $requestedKpCodes = array_values(array_unique(array_filter($requestedKpCodes)));
  1866. $requestedKpSet = array_fill_keys($requestedKpCodes, true);
  1867. $shouldRestrictToRequestedKps = ($assembleType === 2 && ! empty($requestedKpSet));
  1868. if ($assembleType === 2 && ! empty($kpTargetCounts)) {
  1869. return $this->selectQuestionsByKpTargets(
  1870. $questions,
  1871. $totalQuestions,
  1872. $requestedKpCodes,
  1873. $kpTargetCounts,
  1874. $maxDifficultyByKp,
  1875. $typeTargetsByKp
  1876. );
  1877. }
  1878. if ($shouldRestrictToRequestedKps) {
  1879. $requestedQuestions = array_values(array_filter($questions, function ($question) use ($requestedKpSet) {
  1880. $kpCode = $question['kp_code'] ?? '';
  1881. return isset($requestedKpSet[$kpCode]);
  1882. }));
  1883. $fallbackQuestions = array_values(array_filter($questions, function ($question) use ($requestedKpSet) {
  1884. $kpCode = $question['kp_code'] ?? '';
  1885. return ! isset($requestedKpSet[$kpCode]);
  1886. }));
  1887. Log::info('selectQuestionsByMastery: assemble_type=2 请求知识点约束', [
  1888. 'requested_kp_codes' => $requestedKpCodes,
  1889. 'requested_question_count' => count($requestedQuestions),
  1890. 'fallback_question_count' => count($fallbackQuestions),
  1891. 'target_question_count' => $totalQuestions,
  1892. ]);
  1893. // 原始请求知识点足够时,最终选题不应被补题池中的兄弟/父树知识点带偏。
  1894. if (count($requestedQuestions) >= $totalQuestions) {
  1895. $questions = $requestedQuestions;
  1896. } else {
  1897. $questions = array_merge($requestedQuestions, $fallbackQuestions);
  1898. }
  1899. }
  1900. // 1. 按知识点分组
  1901. $groupStartTime = microtime(true);
  1902. $questionsByKp = [];
  1903. foreach ($questions as $question) {
  1904. $kpCode = $question['kp_code'] ?? '';
  1905. if (!isset($questionsByKp[$kpCode])) {
  1906. $questionsByKp[$kpCode] = [];
  1907. }
  1908. $questionsByKp[$kpCode][] = $question;
  1909. }
  1910. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1911. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1912. $kpWeights = [];
  1913. $kpCodes = array_keys($questionsByKp);
  1914. $startTime = microtime(true);
  1915. $allMastery = [];
  1916. if ($studentId) {
  1917. // 批量获取所有知识点的掌握度(一次查询)
  1918. $masteryStart = microtime(true);
  1919. try {
  1920. $masteryRecords = DB::table('student_mastery')
  1921. ->where('student_id', $studentId)
  1922. ->whereIn('kp', $kpCodes)
  1923. ->pluck('mastery', 'kp')
  1924. ->all();
  1925. Log::debug('批量获取掌握度', [
  1926. 'student_id' => $studentId,
  1927. 'kp_count' => count($kpCodes),
  1928. 'found_count' => count($masteryRecords),
  1929. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1930. ]);
  1931. $allMastery = $masteryRecords;
  1932. } catch (\Exception $e) {
  1933. Log::warning('批量获取掌握度失败,将使用默认值', [
  1934. 'student_id' => $studentId,
  1935. 'error' => $e->getMessage()
  1936. ]);
  1937. }
  1938. }
  1939. foreach ($kpCodes as $kpCode) {
  1940. if ($studentId) {
  1941. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1942. // 薄弱点权重更高
  1943. if (in_array($kpCode, $weaknessFilter)) {
  1944. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1945. } else {
  1946. // 掌握度越低,权重越高
  1947. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1948. }
  1949. Log::debug('计算知识点权重', [
  1950. 'kp_code' => $kpCode,
  1951. 'mastery' => $mastery,
  1952. 'weight' => $kpWeights[$kpCode]
  1953. ]);
  1954. } else {
  1955. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1956. }
  1957. }
  1958. // 3. 按题型分配题目数量(权重用于题型内排序)
  1959. $selectedQuestions = [];
  1960. // 将所有题目合并
  1961. $weightedQuestions = [];
  1962. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1963. foreach ($kpQuestions as $q) {
  1964. $q['kp_code'] = $kpCode;
  1965. $weightedQuestions[] = $q;
  1966. }
  1967. }
  1968. // ========== 知识点优先选择机制 ==========
  1969. // 摸底测试的核心目标是最大化知识点覆盖
  1970. // 题型只是约束条件(每种至少1题)
  1971. // 首先按题型分组
  1972. $questionsByType = [
  1973. 'choice' => [],
  1974. 'fill' => [],
  1975. 'answer' => [],
  1976. ];
  1977. foreach ($weightedQuestions as $q) {
  1978. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1979. if ($qid && isset($questionTypeCache[$qid])) {
  1980. $type = $questionTypeCache[$qid];
  1981. } else {
  1982. $type = $this->determineQuestionType($q);
  1983. if ($qid) {
  1984. $questionTypeCache[$qid] = $type;
  1985. }
  1986. }
  1987. if (!isset($questionsByType[$type])) {
  1988. $type = 'answer'; // 默认归类为answer
  1989. }
  1990. $questionsByType[$type][] = $q;
  1991. }
  1992. // ========== 步骤1:按题型分配题目 ==========
  1993. $selectedQuestions = [];
  1994. // 【区分】根据 assembleType 决定是否使用知识点覆盖优先机制
  1995. // - 0:摸底测试,优先扩大知识点覆盖
  1996. // - 2:知识点组卷,也应尽量覆盖请求中的多个知识点,避免被单一 KP 吞掉
  1997. $useKnowledgePointPriority = in_array($assembleType, [0, 2], true);
  1998. $kpSelected = []; // 已选知识点记录
  1999. // 【新增】非摸底类型:按比例计算每种题型的目标数量
  2000. $typeTargets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2001. if (!$useKnowledgePointPriority) {
  2002. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  2003. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  2004. $allocated = 0;
  2005. $fractions = [];
  2006. foreach ($ratioMap as $type => $ratioKey) {
  2007. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  2008. $exact = $totalQuestions * $ratio / $totalRatio;
  2009. $typeTargets[$type] = (int) floor($exact);
  2010. $fractions[$type] = $exact - floor($exact);
  2011. $allocated += $typeTargets[$type];
  2012. }
  2013. // 余数分配给小数部分最大的题型
  2014. $remainder = $totalQuestions - $allocated;
  2015. arsort($fractions);
  2016. foreach ($fractions as $type => $frac) {
  2017. if ($remainder <= 0) break;
  2018. $typeTargets[$type]++;
  2019. $remainder--;
  2020. }
  2021. Log::debug('selectQuestionsByMastery: 题型目标分配', [
  2022. 'total_questions' => $totalQuestions,
  2023. 'targets' => $typeTargets,
  2024. ]);
  2025. }
  2026. // 确保每种题型至少选1题
  2027. foreach (['choice', 'fill', 'answer'] as $type) {
  2028. if (empty($questionsByType[$type])) {
  2029. Log::warning('题型分配:题型无题目', ['type' => $type]);
  2030. continue;
  2031. }
  2032. // 按权重排序该题型的题目
  2033. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  2034. $kpA = $a['kp_code'] ?? '';
  2035. $kpB = $b['kp_code'] ?? '';
  2036. $weightA = $kpWeights[$kpA] ?? 1.0;
  2037. $weightB = $kpWeights[$kpB] ?? 1.0;
  2038. return $weightB <=> $weightA;
  2039. });
  2040. // 【修复】摸底测试题型基础分配:记录每个题型的知识点分布
  2041. $typeKpDistribution = [];
  2042. foreach ($questionsByType[$type] as $q) {
  2043. $kpCode = $q['kp_code'] ?? '';
  2044. if (!isset($typeKpDistribution[$kpCode])) {
  2045. $typeKpDistribution[$kpCode] = 0;
  2046. }
  2047. $typeKpDistribution[$kpCode]++;
  2048. }
  2049. Log::debug('摸底测试题型基础分配', [
  2050. 'type' => $type,
  2051. 'total_in_type' => count($questionsByType[$type]),
  2052. 'kp_count' => count($typeKpDistribution)
  2053. ]);
  2054. // 根据策略选择题目
  2055. if ($useKnowledgePointPriority) {
  2056. // 知识点优先:assemble_type=2 先从原始请求知识点里选;摸底则扩大覆盖
  2057. $selectedInThisType = 0;
  2058. $candidate = null;
  2059. foreach ($questionsByType[$type] as $q) {
  2060. $kpCode = $q['kp_code'] ?? '';
  2061. if ($shouldRestrictToRequestedKps && ! isset($requestedKpSet[$kpCode])) {
  2062. continue;
  2063. }
  2064. if (!isset($kpSelected[$kpCode])) {
  2065. $candidate = $q;
  2066. break; // 只选1题
  2067. }
  2068. }
  2069. if ($candidate === null && $shouldRestrictToRequestedKps) {
  2070. foreach ($questionsByType[$type] as $q) {
  2071. $kpCode = $q['kp_code'] ?? '';
  2072. if (isset($requestedKpSet[$kpCode])) {
  2073. $candidate = $q;
  2074. break;
  2075. }
  2076. }
  2077. }
  2078. if ($candidate !== null) {
  2079. $kpCode = $candidate['kp_code'] ?? '';
  2080. $selectedQuestions[] = $candidate;
  2081. $kpSelected[$kpCode] = true;
  2082. $selectedInThisType++;
  2083. Log::debug('题型基础分配(知识点优先)', [
  2084. 'type' => $type,
  2085. 'kp' => $kpCode,
  2086. 'question_id' => $candidate['id'] ?? 'unknown',
  2087. 'selected_in_type' => $selectedInThisType
  2088. ]);
  2089. }
  2090. Log::debug('知识点优先题型基础分配完成', [
  2091. 'type' => $type,
  2092. 'selected_count' => $selectedInThisType
  2093. ]);
  2094. } else {
  2095. // 非摸底:按目标数量从该题型池中选题
  2096. $target = $typeTargets[$type] ?? 0;
  2097. $selectedIds = array_column($selectedQuestions, 'id');
  2098. $taken = 0;
  2099. foreach ($questionsByType[$type] as $q) {
  2100. if ($taken >= $target) break;
  2101. $qid = $q['id'] ?? null;
  2102. if ($qid && !in_array($qid, $selectedIds)) {
  2103. $selectedQuestions[] = $q;
  2104. $selectedIds[] = $qid;
  2105. $taken++;
  2106. }
  2107. }
  2108. $typeTargets[$type . '_actual'] = $taken;
  2109. Log::debug('题型按比例分配', [
  2110. 'type' => $type,
  2111. 'target' => $target,
  2112. 'actual' => $taken
  2113. ]);
  2114. }
  2115. }
  2116. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  2117. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  2118. // 【重要】添加排序前的知识点分布日志
  2119. $preSortKpDistribution = [];
  2120. foreach ($allQuestions as $q) {
  2121. $kpCode = $q['kp_code'] ?? '';
  2122. if (!isset($preSortKpDistribution[$kpCode])) {
  2123. $preSortKpDistribution[$kpCode] = 0;
  2124. }
  2125. $preSortKpDistribution[$kpCode]++;
  2126. }
  2127. Log::debug('selectQuestionsByMastery: 排序前知识点分布', [
  2128. 'total_questions' => count($allQuestions),
  2129. 'kp_distribution' => $preSortKpDistribution
  2130. ]);
  2131. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  2132. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  2133. $kpA = $a['kp_code'] ?? '';
  2134. $kpB = $b['kp_code'] ?? '';
  2135. $weightA = $kpWeights[$kpA] ?? 1.0;
  2136. $weightB = $kpWeights[$kpB] ?? 1.0;
  2137. // 主要按权重排序
  2138. if ($weightA != $weightB) {
  2139. return $weightB <=> $weightA;
  2140. }
  2141. // 权重相同时,添加随机排序而不是按ID排序
  2142. // 使用随机因子确保相同权重的知识点有公平的选中机会
  2143. return mt_rand(-1, 1);
  2144. });
  2145. // 【重要】添加排序后的知识点分布日志
  2146. $postSortKpDistribution = [];
  2147. $postSortFirst50 = []; // 记录前50题的知识点分布
  2148. foreach ($allQuestions as $idx => $q) {
  2149. $kpCode = $q['kp_code'] ?? '';
  2150. if (!isset($postSortKpDistribution[$kpCode])) {
  2151. $postSortKpDistribution[$kpCode] = 0;
  2152. }
  2153. $postSortKpDistribution[$kpCode]++;
  2154. // 记录前50题的知识点
  2155. if ($idx < 50) {
  2156. $postSortFirst50[] = $kpCode;
  2157. }
  2158. }
  2159. Log::debug('selectQuestionsByMastery: 排序后知识点分布', [
  2160. 'total_questions' => count($allQuestions),
  2161. 'kp_distribution' => $postSortKpDistribution
  2162. ]);
  2163. // 【修复】摸底测试继续选择题目:记录详细的选题过程
  2164. Log::debug('摸底测试继续选择题目开始', [
  2165. 'selected_count_after_basic' => count($selectedQuestions),
  2166. 'total_questions' => $totalQuestions,
  2167. 'selected_kp_codes' => array_keys($kpSelected),
  2168. 'available_kp_count' => count($preSortKpDistribution),
  2169. 'strategy' => $useKnowledgePointPriority ? '知识点覆盖优先' : '无知识点限制'
  2170. ]);
  2171. if ($useKnowledgePointPriority) {
  2172. // 知识点优先:assemble_type=2 先补齐原始请求知识点,再允许请求知识点重复,最后才使用 fallback KP
  2173. $initialSelectedCount = count($selectedQuestions);
  2174. $prioritySelectedCount = 0;
  2175. $selectedIds = array_values(array_filter(array_column($selectedQuestions, 'id')));
  2176. if ($shouldRestrictToRequestedKps) {
  2177. foreach ($allQuestions as $q) {
  2178. if (count($selectedQuestions) >= $totalQuestions) {
  2179. break;
  2180. }
  2181. $kpCode = $q['kp_code'] ?? '';
  2182. $qid = $q['id'] ?? null;
  2183. if (!isset($requestedKpSet[$kpCode]) || $qid === null || in_array($qid, $selectedIds)) {
  2184. continue;
  2185. }
  2186. if (!isset($kpSelected[$kpCode])) {
  2187. $selectedQuestions[] = $q;
  2188. $selectedIds[] = $qid;
  2189. $kpSelected[$kpCode] = true;
  2190. $prioritySelectedCount++;
  2191. Log::debug('继续选择题目(请求知识点优先)', [
  2192. 'kp' => $kpCode,
  2193. 'id' => $qid,
  2194. 'priority_selected_count' => $prioritySelectedCount,
  2195. 'total_selected' => count($selectedQuestions)
  2196. ]);
  2197. }
  2198. }
  2199. } else {
  2200. foreach ($allQuestions as $q) {
  2201. if (count($selectedQuestions) >= $totalQuestions) break;
  2202. $kpCode = $q['kp_code'] ?? '';
  2203. if (!isset($kpSelected[$kpCode])) {
  2204. $selectedQuestions[] = $q;
  2205. $kpSelected[$kpCode] = true;
  2206. $prioritySelectedCount++;
  2207. Log::debug('继续选择题目(知识点优先)', [
  2208. 'kp' => $kpCode,
  2209. 'id' => $q['id'] ?? 'unknown',
  2210. 'priority_selected_count' => $prioritySelectedCount,
  2211. 'total_selected' => count($selectedQuestions)
  2212. ]);
  2213. }
  2214. }
  2215. }
  2216. Log::debug('摸底测试优先阶段完成', [
  2217. 'priority_selected_count' => $prioritySelectedCount,
  2218. 'total_selected' => count($selectedQuestions),
  2219. 'unique_kp_count' => count($kpSelected),
  2220. 'note' => '优先选择未选过知识点的题目'
  2221. ]);
  2222. // 【修复】降级策略:如果仍未达到目标数量,允许重复选择知识点
  2223. if (count($selectedQuestions) < $totalQuestions) {
  2224. Log::warning('selectQuestionsByMastery: 知识点优先策略无法满足数量要求,启用降级策略', [
  2225. 'requested_count' => $totalQuestions,
  2226. 'selected_count' => count($selectedQuestions),
  2227. 'priority_selected_count' => $prioritySelectedCount,
  2228. 'unique_kp_count' => count($kpSelected),
  2229. 'available_kp_count' => count($preSortKpDistribution),
  2230. 'note' => '将允许重复选择知识点以达到目标数量'
  2231. ]);
  2232. $fallbackSelectedCount = 0;
  2233. $selectedIds = array_values(array_filter(array_column($selectedQuestions, 'id')));
  2234. if ($shouldRestrictToRequestedKps) {
  2235. foreach ($allQuestions as $q) {
  2236. if (count($selectedQuestions) >= $totalQuestions) {
  2237. break;
  2238. }
  2239. $kpCode = $q['kp_code'] ?? '';
  2240. $qid = $q['id'] ?? null;
  2241. if ($qid === null || in_array($qid, $selectedIds) || !isset($requestedKpSet[$kpCode])) {
  2242. continue;
  2243. }
  2244. $selectedQuestions[] = $q;
  2245. $selectedIds[] = $qid;
  2246. $fallbackSelectedCount++;
  2247. Log::debug('降级选择题目(请求知识点重复)', [
  2248. 'kp' => $kpCode,
  2249. 'id' => $qid,
  2250. 'fallback_selected_count' => $fallbackSelectedCount,
  2251. 'current_count' => count($selectedQuestions)
  2252. ]);
  2253. }
  2254. }
  2255. foreach ($allQuestions as $q) {
  2256. if (count($selectedQuestions) >= $totalQuestions) break;
  2257. $qid = $q['id'] ?? null;
  2258. if ($qid && !in_array($qid, $selectedIds)) {
  2259. $selectedQuestions[] = $q;
  2260. $selectedIds[] = $qid;
  2261. $fallbackSelectedCount++;
  2262. Log::debug('降级选择题目(允许知识点重复)', [
  2263. 'kp' => $q['kp_code'] ?? 'unknown',
  2264. 'id' => $qid,
  2265. 'fallback_selected_count' => $fallbackSelectedCount,
  2266. 'current_count' => count($selectedQuestions)
  2267. ]);
  2268. }
  2269. }
  2270. Log::debug('摸底测试降级阶段完成', [
  2271. 'fallback_selected_count' => $fallbackSelectedCount,
  2272. 'total_selected' => count($selectedQuestions),
  2273. 'note' => '允许重复选择知识点补充数量'
  2274. ]);
  2275. }
  2276. } else {
  2277. // 非摸底:题型不足时,缺口按优先级补到其他题型
  2278. $totalSelected = count($selectedQuestions);
  2279. if ($totalSelected < $totalQuestions) {
  2280. $deficit = $totalQuestions - $totalSelected;
  2281. $selectedIds = array_column($selectedQuestions, 'id');
  2282. // 按补充优先级:填空 > 解答 > 选择(避免解答题独占缺口)
  2283. $supplementOrder = ['fill', 'answer', 'choice'];
  2284. Log::debug('题型缺口补充开始', [
  2285. 'deficit' => $deficit,
  2286. 'current_count' => $totalSelected,
  2287. 'target' => $totalQuestions,
  2288. 'supplement_order' => $supplementOrder,
  2289. ]);
  2290. foreach ($supplementOrder as $type) {
  2291. if ($deficit <= 0) break;
  2292. foreach ($questionsByType[$type] as $q) {
  2293. if ($deficit <= 0) break;
  2294. $qid = $q['id'] ?? null;
  2295. if ($qid && !in_array($qid, $selectedIds)) {
  2296. $selectedQuestions[] = $q;
  2297. $selectedIds[] = $qid;
  2298. $deficit--;
  2299. }
  2300. }
  2301. }
  2302. Log::debug('题型缺口补充完成', [
  2303. 'final_count' => count($selectedQuestions),
  2304. 'target' => $totalQuestions,
  2305. ]);
  2306. }
  2307. }
  2308. // 【移除】删除步骤3的多余逻辑
  2309. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2310. Log::info('selectQuestionsByMastery 完成', [
  2311. 'total_questions' => $totalQuestions,
  2312. 'selected_count' => count($selectedQuestions),
  2313. 'success' => count($selectedQuestions) === $totalQuestions,
  2314. 'assemble_type' => $assembleType,
  2315. 'strategy' => $useKnowledgePointPriority ? '知识点覆盖优先' : '无知识点限制',
  2316. 'requested_kp_selection' => $this->buildRequestedKpSelectionStats($selectedQuestions, $requestedKpCodes),
  2317. 'type_distribution' => array_count_values(array_map(function($q) {
  2318. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2319. if ($qid && isset($questionTypeCache[$qid])) {
  2320. return $questionTypeCache[$qid];
  2321. }
  2322. return $this->determineQuestionType($q);
  2323. }, $selectedQuestions)),
  2324. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2325. ]);
  2326. // 【重要】最终截取到目标数量(如果超过)
  2327. if (count($selectedQuestions) > $totalQuestions) {
  2328. Log::info('题目数量超过目标,进行最终截取', [
  2329. 'before' => count($selectedQuestions),
  2330. 'after' => $totalQuestions
  2331. ]);
  2332. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2333. }
  2334. // 【重要】添加最终数量验证日志
  2335. Log::debug('selectQuestionsByMastery: 最终题目数量验证', [
  2336. 'before_final_check' => count($selectedQuestions),
  2337. 'target_count' => $totalQuestions,
  2338. 'is_array' => is_array($selectedQuestions)
  2339. ]);
  2340. // 【新增】最终知识点分布统计
  2341. $finalKpDistribution = array_count_values(array_column($selectedQuestions, 'kp_code'));
  2342. Log::debug('摸底测试最终知识点分布', [
  2343. 'final_total_count' => count($selectedQuestions),
  2344. 'target_count' => $totalQuestions,
  2345. 'final_kp_distribution' => $finalKpDistribution,
  2346. 'unique_kp_count' => count($finalKpDistribution),
  2347. 'success' => count($selectedQuestions) === $totalQuestions,
  2348. 'kp_coverage_rate' => count($finalKpDistribution) / max(count($preSortKpDistribution), 1) * 100
  2349. ]);
  2350. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2351. $finalQuestions = [];
  2352. $seenQuestionIds = [];
  2353. $duplicateCount = 0;
  2354. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2355. foreach ($selectedQuestions as $question) {
  2356. $qbId = $question['question_bank_id'] ?? $question['id'];
  2357. if (!in_array($qbId, $seenQuestionIds)) {
  2358. $seenQuestionIds[] = $qbId;
  2359. $finalQuestions[] = $question;
  2360. // 统计题型分布
  2361. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2362. $type = null;
  2363. if ($qid && isset($questionTypeCache[$qid])) {
  2364. $type = $questionTypeCache[$qid];
  2365. } else {
  2366. $type = $this->determineQuestionType($question);
  2367. if ($qid) {
  2368. $questionTypeCache[$qid] = $type;
  2369. }
  2370. }
  2371. if (isset($typeDistribution[$type])) {
  2372. $typeDistribution[$type]++;
  2373. }
  2374. } else {
  2375. $duplicateCount++;
  2376. Log::warning('发现重复题目(已自动移除)', [
  2377. 'question_id' => $qbId,
  2378. 'duplicate_count' => $duplicateCount
  2379. ]);
  2380. }
  2381. }
  2382. // 【重要】如果去重后数量不足,补充到目标数量
  2383. if (count($finalQuestions) < $totalQuestions) {
  2384. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2385. 'final_count' => count($finalQuestions),
  2386. 'target_count' => $totalQuestions,
  2387. 'need_more' => $totalQuestions - count($finalQuestions)
  2388. ]);
  2389. // 从原始题目中选择未选过的题目补充
  2390. $usedIds = array_column($finalQuestions, 'id');
  2391. $supplementCount = 0;
  2392. foreach ($selectedQuestions as $question) {
  2393. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2394. $qid = $question['id'] ?? null;
  2395. if ($qid && !in_array($qid, $usedIds)) {
  2396. $finalQuestions[] = $question;
  2397. $usedIds[] = $qid;
  2398. $supplementCount++;
  2399. }
  2400. }
  2401. Log::debug('selectQuestionsByMastery: 补充完成', [
  2402. 'supplement_added' => $supplementCount,
  2403. 'final_count_after_supplement' => count($finalQuestions)
  2404. ]);
  2405. }
  2406. Log::debug('最终排查完成', [
  2407. 'original_count' => count($selectedQuestions),
  2408. 'final_count' => count($finalQuestions),
  2409. 'duplicate_removed' => $duplicateCount,
  2410. 'final_type_distribution' => $typeDistribution,
  2411. 'target_count' => $totalQuestions
  2412. ]);
  2413. // 【重要】确保返回的题目数量正确
  2414. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2415. Log::debug('selectQuestionsByMastery: 返回结果', [
  2416. 'return_count' => count($finalQuestions),
  2417. 'target_count' => $totalQuestions,
  2418. 'success' => count($finalQuestions) === $totalQuestions
  2419. ]);
  2420. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2421. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2422. return $finalQuestions;
  2423. }
  2424. /**
  2425. * 错题追练复用知识点组卷时使用:按计划里的 KP 配额、题型配额和难度上限选题。
  2426. *
  2427. * @param array<int, array<string, mixed>> $questions
  2428. * @param array<int, string> $requestedKpCodes
  2429. * @param array<string, int> $kpTargetCounts
  2430. * @param array<string, float|int|string> $maxDifficultyByKp
  2431. * @param array<string, array<string, int>> $typeTargetsByKp
  2432. * @return array<int, array<string, mixed>>
  2433. */
  2434. private function selectQuestionsByKpTargets(
  2435. array $questions,
  2436. int $totalQuestions,
  2437. array $requestedKpCodes,
  2438. array $kpTargetCounts,
  2439. array $maxDifficultyByKp,
  2440. array $typeTargetsByKp
  2441. ): array {
  2442. $normalizedKpTargetCounts = [];
  2443. foreach ($kpTargetCounts as $kpCode => $count) {
  2444. $count = (int) $count;
  2445. if ($count > 0) {
  2446. $normalizedKpTargetCounts[(string) $kpCode] = $count;
  2447. }
  2448. }
  2449. $kpTargetCounts = $normalizedKpTargetCounts;
  2450. if ($kpTargetCounts === [] || $totalQuestions <= 0) {
  2451. return [];
  2452. }
  2453. $targetKpOrder = array_values(array_filter($requestedKpCodes, static fn ($kp) => isset($kpTargetCounts[$kp])));
  2454. foreach (array_keys($kpTargetCounts) as $kpCode) {
  2455. if (! in_array($kpCode, $targetKpOrder, true)) {
  2456. $targetKpOrder[] = $kpCode;
  2457. }
  2458. }
  2459. $targetKpSet = array_fill_keys(array_keys($kpTargetCounts), true);
  2460. $questionsByKp = [];
  2461. $supplementQuestions = [];
  2462. foreach ($questions as $question) {
  2463. $kpCode = (string) ($question['kp_code'] ?? '');
  2464. if ($kpCode === '') {
  2465. continue;
  2466. }
  2467. $questionsByKp[$kpCode][] = $question;
  2468. if (! isset($targetKpSet[$kpCode])) {
  2469. $supplementQuestions[] = $question;
  2470. }
  2471. }
  2472. $selected = [];
  2473. $usedIds = [];
  2474. $shortageByKp = [];
  2475. foreach ($targetKpOrder as $kpCode) {
  2476. $need = min((int) ($kpTargetCounts[$kpCode] ?? 0), max(0, $totalQuestions - count($selected)));
  2477. if ($need <= 0) {
  2478. continue;
  2479. }
  2480. $maxDifficulty = $this->normalizeAssemblyDifficulty($maxDifficultyByKp[$kpCode] ?? null);
  2481. $typeTargets = $typeTargetsByKp[$kpCode] ?? [];
  2482. $directSelected = $this->takeQuestionsForPracticeTarget(
  2483. $questionsByKp[$kpCode] ?? [],
  2484. $need,
  2485. $maxDifficulty,
  2486. $typeTargets,
  2487. $usedIds
  2488. );
  2489. foreach ($directSelected as $question) {
  2490. $question['practice_target_kp_code'] = $kpCode;
  2491. $question['practice_target_difficulty'] = $maxDifficulty;
  2492. $selected[] = $question;
  2493. }
  2494. $remainingNeed = $need - count($directSelected);
  2495. if ($remainingNeed > 0 && $supplementQuestions !== []) {
  2496. $supplementSelected = $this->takeQuestionsForPracticeTarget(
  2497. $supplementQuestions,
  2498. $remainingNeed,
  2499. $maxDifficulty,
  2500. [],
  2501. $usedIds
  2502. );
  2503. foreach ($supplementSelected as $question) {
  2504. $question['practice_target_kp_code'] = $kpCode;
  2505. $question['practice_target_difficulty'] = $maxDifficulty;
  2506. $question['practice_supplement_kp_code'] = $question['kp_code'] ?? null;
  2507. $selected[] = $question;
  2508. }
  2509. $remainingNeed -= count($supplementSelected);
  2510. }
  2511. if ($remainingNeed > 0) {
  2512. $shortageByKp[$kpCode] = $remainingNeed;
  2513. }
  2514. }
  2515. if (count($selected) < $totalQuestions) {
  2516. $remainingNeed = $totalQuestions - count($selected);
  2517. $targetPool = [];
  2518. foreach ($targetKpOrder as $kpCode) {
  2519. $targetPool = array_merge($targetPool, $questionsByKp[$kpCode] ?? []);
  2520. }
  2521. $backfillSelected = $this->takeQuestionsForPracticeTarget(
  2522. $targetPool,
  2523. $remainingNeed,
  2524. null,
  2525. [],
  2526. $usedIds
  2527. );
  2528. foreach ($backfillSelected as $question) {
  2529. $question['practice_backfill_reason'] = 'target_kp_shortage';
  2530. $selected[] = $question;
  2531. }
  2532. $remainingNeed = $totalQuestions - count($selected);
  2533. if ($remainingNeed > 0 && $supplementQuestions !== []) {
  2534. $supplementBackfill = $this->takeQuestionsForPracticeTarget(
  2535. $supplementQuestions,
  2536. $remainingNeed,
  2537. null,
  2538. [],
  2539. $usedIds
  2540. );
  2541. foreach ($supplementBackfill as $question) {
  2542. $question['practice_backfill_reason'] = 'supplement_kp_shortage';
  2543. $selected[] = $question;
  2544. }
  2545. }
  2546. Log::info('selectQuestionsByKpTargets: applied global backfill', [
  2547. 'target_count' => $totalQuestions,
  2548. 'selected_count' => count($selected),
  2549. 'shortage_by_kp' => $shortageByKp,
  2550. 'backfill_count' => count($selected) - ($totalQuestions - array_sum($shortageByKp)),
  2551. ]);
  2552. }
  2553. if (count($selected) < $totalQuestions) {
  2554. Log::warning('selectQuestionsByKpTargets: planned KP selection produced fewer questions', [
  2555. 'target_count' => $totalQuestions,
  2556. 'selected_count' => count($selected),
  2557. 'shortage_by_kp' => $shortageByKp,
  2558. 'kp_target_counts' => $kpTargetCounts,
  2559. 'available_kp_distribution' => array_map('count', $questionsByKp),
  2560. ]);
  2561. }
  2562. Log::info('selectQuestionsByKpTargets 完成', [
  2563. 'target_count' => $totalQuestions,
  2564. 'selected_count' => count($selected),
  2565. 'kp_target_counts' => $kpTargetCounts,
  2566. 'selected_kp_distribution' => array_count_values(array_column($selected, 'kp_code')),
  2567. 'practice_target_distribution' => array_count_values(array_column($selected, 'practice_target_kp_code')),
  2568. ]);
  2569. return array_slice($selected, 0, $totalQuestions);
  2570. }
  2571. /**
  2572. * @param array<int, array<string, mixed>> $pool
  2573. * @param array<string, int> $typeTargets
  2574. * @param array<string, bool> $usedIds
  2575. * @return array<int, array<string, mixed>>
  2576. */
  2577. private function takeQuestionsForPracticeTarget(
  2578. array $pool,
  2579. int $need,
  2580. ?float $maxDifficulty,
  2581. array $typeTargets,
  2582. array &$usedIds
  2583. ): array {
  2584. if ($need <= 0 || $pool === []) {
  2585. return [];
  2586. }
  2587. $candidateBuckets = ['choice' => [], 'fill' => [], 'answer' => []];
  2588. $questionPayloadMapper = app(QuestionPayloadMapper::class);
  2589. foreach ($pool as $question) {
  2590. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2591. if ($id === '' || isset($usedIds[$id])) {
  2592. continue;
  2593. }
  2594. $difficulty = $this->normalizeAssemblyDifficulty($question['difficulty'] ?? null) ?? 0.5;
  2595. $type = $questionPayloadMapper->normalizeQuestionType((string) ($question['question_type'] ?? $question['type'] ?? ''))
  2596. ?? $this->determineQuestionType($question);
  2597. if (! isset($candidateBuckets[$type])) {
  2598. $type = 'answer';
  2599. }
  2600. $question['practice_match_delta'] = $maxDifficulty !== null ? round($maxDifficulty - $difficulty, 4) : 0.0;
  2601. $question['practice_candidate_difficulty'] = $difficulty;
  2602. $candidateBuckets[$type][] = $question;
  2603. }
  2604. foreach ($candidateBuckets as &$bucket) {
  2605. usort($bucket, function (array $a, array $b) use ($maxDifficulty): int {
  2606. return $this->comparePracticeDifficulty($a, $b, $maxDifficulty);
  2607. });
  2608. }
  2609. unset($bucket);
  2610. $selected = [];
  2611. foreach (['choice', 'fill', 'answer'] as $type) {
  2612. $target = min((int) ($typeTargets[$type] ?? 0), $need - count($selected));
  2613. if ($target <= 0) {
  2614. continue;
  2615. }
  2616. while ($target > 0 && ! empty($candidateBuckets[$type])) {
  2617. $question = array_shift($candidateBuckets[$type]);
  2618. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2619. if ($id === '' || isset($usedIds[$id])) {
  2620. continue;
  2621. }
  2622. $selected[] = $question;
  2623. $usedIds[$id] = true;
  2624. $target--;
  2625. }
  2626. }
  2627. $remaining = array_merge($candidateBuckets['choice'], $candidateBuckets['fill'], $candidateBuckets['answer']);
  2628. usort($remaining, function (array $a, array $b) use ($maxDifficulty): int {
  2629. return $this->comparePracticeDifficulty($a, $b, $maxDifficulty);
  2630. });
  2631. foreach ($remaining as $question) {
  2632. if (count($selected) >= $need) {
  2633. break;
  2634. }
  2635. $id = (string) ($question['id'] ?? $question['question_id'] ?? '');
  2636. if ($id === '' || isset($usedIds[$id])) {
  2637. continue;
  2638. }
  2639. $selected[] = $question;
  2640. $usedIds[$id] = true;
  2641. }
  2642. return $selected;
  2643. }
  2644. private function comparePracticeDifficulty(array $a, array $b, ?float $targetDifficulty): int
  2645. {
  2646. $da = $this->normalizeAssemblyDifficulty($a['difficulty'] ?? null) ?? 0.5;
  2647. $db = $this->normalizeAssemblyDifficulty($b['difficulty'] ?? null) ?? 0.5;
  2648. if ($targetDifficulty === null) {
  2649. $scoreA = abs(0.5 - $da);
  2650. $scoreB = abs(0.5 - $db);
  2651. } else {
  2652. $scoreA = $da <= $targetDifficulty
  2653. ? $targetDifficulty - $da
  2654. : 1 + ($da - $targetDifficulty);
  2655. $scoreB = $db <= $targetDifficulty
  2656. ? $targetDifficulty - $db
  2657. : 1 + ($db - $targetDifficulty);
  2658. }
  2659. if ($scoreA !== $scoreB) {
  2660. return $scoreA <=> $scoreB;
  2661. }
  2662. return ((int) ($a['id'] ?? $a['question_id'] ?? 0)) <=> ((int) ($b['id'] ?? $b['question_id'] ?? 0));
  2663. }
  2664. private function normalizeAssemblyDifficulty(mixed $difficulty): ?float
  2665. {
  2666. if ($difficulty === null || $difficulty === '') {
  2667. return null;
  2668. }
  2669. if (! is_numeric($difficulty)) {
  2670. return null;
  2671. }
  2672. $value = (float) $difficulty;
  2673. if ($value > 1) {
  2674. $value = $value / 5;
  2675. }
  2676. return max(0.0, min(1.0, $value));
  2677. }
  2678. /**
  2679. * @param array<int, array<string, mixed>> $questions
  2680. * @param array<int, string> $requestedKpCodes
  2681. * @return array<string, mixed>
  2682. */
  2683. private function buildRequestedKpSelectionStats(array $questions, array $requestedKpCodes): array
  2684. {
  2685. $requestedKpCodes = array_values(array_unique(array_filter($requestedKpCodes)));
  2686. if ($requestedKpCodes === []) {
  2687. return [
  2688. 'requested_kp_codes' => [],
  2689. 'requested_kp_selected_count' => 0,
  2690. 'related_kp_selected_count' => 0,
  2691. 'requested_kp_distribution' => [],
  2692. 'related_kp_distribution' => [],
  2693. ];
  2694. }
  2695. $requestedKpSet = array_fill_keys($requestedKpCodes, true);
  2696. $requestedDistribution = [];
  2697. $relatedDistribution = [];
  2698. foreach ($questions as $question) {
  2699. $kpCode = (string) ($question['kp_code'] ?? '');
  2700. if ($kpCode === '') {
  2701. continue;
  2702. }
  2703. if (isset($requestedKpSet[$kpCode])) {
  2704. $requestedDistribution[$kpCode] = ($requestedDistribution[$kpCode] ?? 0) + 1;
  2705. } else {
  2706. $relatedDistribution[$kpCode] = ($relatedDistribution[$kpCode] ?? 0) + 1;
  2707. }
  2708. }
  2709. return [
  2710. 'requested_kp_codes' => $requestedKpCodes,
  2711. 'requested_kp_selected_count' => array_sum($requestedDistribution),
  2712. 'related_kp_selected_count' => array_sum($relatedDistribution),
  2713. 'requested_kp_distribution' => $requestedDistribution,
  2714. 'related_kp_distribution' => $relatedDistribution,
  2715. ];
  2716. }
  2717. /**
  2718. * @param array<int, array<string, mixed>> $questions
  2719. * @return array<string, mixed>
  2720. */
  2721. private function buildSupplementQuestionStats(array $questions): array
  2722. {
  2723. $kpDistribution = array_count_values(array_filter(array_map(
  2724. static fn ($question) => (string) ($question['kp_code'] ?? ''),
  2725. $questions
  2726. )));
  2727. arsort($kpDistribution);
  2728. return [
  2729. 'supplement_kp_distribution_topn' => array_slice($kpDistribution, 0, 10, true),
  2730. 'supplement_kp_sample' => array_slice(array_keys($kpDistribution), 0, 10),
  2731. ];
  2732. }
  2733. /**
  2734. * 获取学生对特定知识点的掌握度
  2735. */
  2736. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2737. {
  2738. try {
  2739. $mastery = DB::table('student_mastery')
  2740. ->where('student_id', $studentId)
  2741. ->where('kp', $kpCode)
  2742. ->value('mastery');
  2743. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2744. } catch (\Exception $e) {
  2745. Log::error('Get Student Kp Mastery Error', [
  2746. 'student_id' => $studentId,
  2747. 'kp_code' => $kpCode,
  2748. 'error' => $e->getMessage()
  2749. ]);
  2750. return 0.5;
  2751. }
  2752. }
  2753. /**
  2754. * 根据题型和难度配比调整题目
  2755. */
  2756. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2757. {
  2758. Log::debug('开始题型配比调整', [
  2759. 'input_questions' => count($questions),
  2760. 'target_count' => $targetCount,
  2761. 'type_ratio' => $typeRatio
  2762. ]);
  2763. // 缓存题目类型,避免重复计算
  2764. $questionTypeCache = [];
  2765. // 按题型分桶
  2766. $buckets = [
  2767. 'choice' => [],
  2768. 'fill' => [],
  2769. 'answer' => [],
  2770. ];
  2771. foreach ($questions as $q) {
  2772. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2773. if ($qid && isset($questionTypeCache[$qid])) {
  2774. $type = $questionTypeCache[$qid];
  2775. } else {
  2776. $type = $this->determineQuestionType($q);
  2777. if ($qid) {
  2778. $questionTypeCache[$qid] = $type;
  2779. }
  2780. }
  2781. if (!isset($buckets[$type])) {
  2782. $type = 'answer';
  2783. }
  2784. $buckets[$type][] = $q;
  2785. }
  2786. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2787. // 修复:不自动减少目标数量,确保达到用户要求
  2788. $availableCount = count($questions);
  2789. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2790. Log::debug('题型配比调整前桶统计', [
  2791. 'target_count' => $targetCount,
  2792. 'available_count' => $availableCount,
  2793. 'targets' => $targets,
  2794. 'bucket_counts' => [
  2795. 'choice' => count($buckets['choice']),
  2796. 'fill' => count($buckets['fill']),
  2797. 'answer' => count($buckets['answer']),
  2798. ],
  2799. 'raw_ratio' => $typeRatio,
  2800. ]);
  2801. // 随机打乱桶
  2802. foreach ($buckets as $k => $v) {
  2803. if (!empty($v)) {
  2804. shuffle($v);
  2805. $buckets[$k] = $v;
  2806. }
  2807. }
  2808. $selected = [];
  2809. $selectedIds = [];
  2810. // 按目标数依次取题
  2811. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2812. $need = $targets[$typeKey] ?? 0;
  2813. if ($need <= 0 || empty($buckets[$typeKey])) {
  2814. continue;
  2815. }
  2816. $take = min($need, count($buckets[$typeKey]));
  2817. $slice = array_slice($buckets[$typeKey], 0, $take);
  2818. foreach ($slice as $q) {
  2819. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2820. if (isset($selectedIds[$id])) {
  2821. continue;
  2822. }
  2823. $selected[] = $q;
  2824. $selectedIds[$id] = true;
  2825. }
  2826. }
  2827. // 不足则从剩余题中补齐
  2828. if (count($selected) < $targetCount) {
  2829. $remaining = [];
  2830. foreach ($buckets as $v) {
  2831. foreach ($v as $q) {
  2832. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2833. if (!isset($selectedIds[$id])) {
  2834. $remaining[] = $q;
  2835. }
  2836. }
  2837. }
  2838. shuffle($remaining);
  2839. $needMore = $targetCount - count($selected);
  2840. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2841. }
  2842. // 截断至目标数
  2843. $selected = array_slice($selected, 0, $targetCount);
  2844. // 使用缓存统计题型分布
  2845. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2846. foreach ($selected as $q) {
  2847. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2848. if ($qid && isset($questionTypeCache[$qid])) {
  2849. $type = $questionTypeCache[$qid];
  2850. } else {
  2851. $type = $this->determineQuestionType($q);
  2852. }
  2853. if (isset($selectedCounts[$type])) {
  2854. $selectedCounts[$type]++;
  2855. }
  2856. }
  2857. Log::debug('题型配比调整完成', [
  2858. 'target_count' => $targetCount,
  2859. 'targets' => $targets,
  2860. 'selected_counts' => $selectedCounts,
  2861. 'final_selected_count' => count($selected)
  2862. ]);
  2863. return $selected;
  2864. }
  2865. private function determineQuestionType(array $q): string
  2866. {
  2867. // 优先根据题目内容判断(而不是数据库字段)
  2868. $stem = $q['stem'] ?? $q['content'] ?? '';
  2869. // 处理 stem 可能是数组的情况
  2870. if (is_array($stem)) {
  2871. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2872. }
  2873. $tags = $q['tags'] ?? '';
  2874. // 处理 tags 可能是数组的情况
  2875. if (is_array($tags)) {
  2876. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2877. }
  2878. $skills = $q['skills'] ?? [];
  2879. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2880. if (is_string($stem)) {
  2881. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2882. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2883. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2884. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2885. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2886. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2887. // 至少有2个选项就认为是选择题(降低阈值)
  2888. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2889. if ($optionCount >= 2) {
  2890. return 'choice';
  2891. }
  2892. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2893. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2894. return 'choice';
  2895. }
  2896. }
  2897. // 2. 根据技能点判断
  2898. if (is_array($skills) && !empty($skills)) {
  2899. // 过滤非字符串元素,避免 implode 报错
  2900. $skillsFiltered = array_filter($skills, 'is_string');
  2901. if (!empty($skillsFiltered)) {
  2902. $skillsStr = implode(',', $skillsFiltered);
  2903. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2904. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2905. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2906. }
  2907. }
  2908. // 3. 根据题目已有类型字段判断(作为后备)
  2909. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2910. if (is_string($typeField)) {
  2911. $t = strtolower($typeField);
  2912. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2913. return 'choice';
  2914. }
  2915. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2916. return 'fill';
  2917. }
  2918. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2919. return 'answer';
  2920. }
  2921. }
  2922. // 4. 根据标签判断
  2923. if (is_string($tags)) {
  2924. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2925. return 'choice';
  2926. }
  2927. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2928. return 'fill';
  2929. }
  2930. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2931. return 'answer';
  2932. }
  2933. }
  2934. // 5. 根据options字段判断
  2935. if (!empty($q['options']) && is_array($q['options'])) {
  2936. return 'choice';
  2937. }
  2938. // 6. 填空题特征:连续下划线或明显的填空括号
  2939. if (is_string($stem)) {
  2940. // 检查填空题特征:连续下划线
  2941. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2942. return 'fill';
  2943. }
  2944. // 空括号填空
  2945. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2946. return 'fill';
  2947. }
  2948. }
  2949. // 7. 根据题干内容关键词判断
  2950. if (is_string($stem)) {
  2951. // 有证明、解答、计算、求证等关键词的是解答题
  2952. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2953. return 'answer';
  2954. }
  2955. }
  2956. // 默认是解答题(更安全的默认值)
  2957. return 'answer';
  2958. }
  2959. // 【移除】删除未使用的mapDifficultyLevel方法
  2960. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2961. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2962. {
  2963. $map = [
  2964. '选择题' => 'choice',
  2965. '填空题' => 'fill',
  2966. '解答题' => 'answer',
  2967. ];
  2968. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2969. foreach ($questionTypeRatio as $label => $ratio) {
  2970. $key = $map[$label] ?? null;
  2971. if (!$key) {
  2972. continue;
  2973. }
  2974. $cnt = (int) round($targetCount * ($ratio / 100));
  2975. if ($ratio > 0 && $cnt < 1) {
  2976. $cnt = 1;
  2977. }
  2978. $targets[$key] = $cnt;
  2979. }
  2980. $sum = array_sum($targets);
  2981. if ($sum === 0) {
  2982. $targets['answer'] = $targetCount;
  2983. return $targets;
  2984. }
  2985. while ($sum > $targetCount) {
  2986. arsort($targets);
  2987. foreach ($targets as $k => $v) {
  2988. if ($v > 1) {
  2989. $targets[$k]--;
  2990. $sum--;
  2991. break;
  2992. }
  2993. }
  2994. }
  2995. if ($sum < $targetCount) {
  2996. $ratioByKey = [
  2997. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2998. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2999. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  3000. ];
  3001. while ($sum < $targetCount) {
  3002. arsort($ratioByKey);
  3003. $k = array_key_first($ratioByKey);
  3004. $targets[$k]++;
  3005. $sum++;
  3006. }
  3007. }
  3008. return $targets;
  3009. }
  3010. /**
  3011. * 提交手动评分结果到 LearningAnalytics
  3012. *
  3013. * @param array $data 包含 student_id, paper_id, grades 的数组
  3014. * @return array
  3015. */
  3016. public function submitManualGrading(array $data): array
  3017. {
  3018. try {
  3019. $response = Http::timeout($this->timeout)
  3020. ->post($this->baseUrl . '/api/ocr/analyze', [
  3021. 'student_id' => $data['student_id'],
  3022. 'paper_id' => $data['paper_id'],
  3023. 'answers' => $data['grades'],
  3024. ]);
  3025. if ($response->successful()) {
  3026. Log::info('Manual grading submitted successfully', [
  3027. 'student_id' => $data['student_id'],
  3028. 'paper_id' => $data['paper_id'],
  3029. 'question_count' => count($data['grades'])
  3030. ]);
  3031. return $response->json();
  3032. }
  3033. Log::error('Submit Manual Grading Error', [
  3034. 'data' => $data,
  3035. 'status' => $response->status(),
  3036. 'response' => $response->body()
  3037. ]);
  3038. return [
  3039. 'error' => true,
  3040. 'message' => 'Failed to submit manual grading'
  3041. ];
  3042. } catch (\Exception $e) {
  3043. Log::error('Submit Manual Grading Exception', [
  3044. 'error' => $e->getMessage(),
  3045. 'data' => $data
  3046. ]);
  3047. return [
  3048. 'error' => true,
  3049. 'message' => $e->getMessage()
  3050. ];
  3051. }
  3052. }
  3053. /**
  3054. * 分析学生作答结果
  3055. *
  3056. * @param array $data 包含 paper_id, student_id, answers 等
  3057. * @return array
  3058. */
  3059. public function analyzeStudentAnswers(array $data): array
  3060. {
  3061. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  3062. 'student_id' => $data['student_id'] ?? null,
  3063. 'paper_id' => $data['paper_id'] ?? null,
  3064. ]);
  3065. return [
  3066. 'success' => false,
  3067. 'message' => 'analysis_api_disabled',
  3068. ];
  3069. }
  3070. /**
  3071. * 智能补充题目(当指定知识点的题目不足时)
  3072. *
  3073. * @param int $grade 年级
  3074. * @param array $existingKpCodes 已有的知识点代码(用于排除)
  3075. * @param int $needCount 需要补充的题目数量
  3076. * @param int $difficultyCategory 难度类别
  3077. * @param int|null $textbookId 教材ID(用于限制补充范围,避免超纲)
  3078. * @param array $excludeQuestionIds 排除的题目ID(学生已做过,避免重复)
  3079. * @param array|null $textbookCatalogNodeIds 当前选中的章节节点ID;与 textbookId 同时传入时,仅从同教材的前章节补充(未学章节不补充)
  3080. * @param string|null $studentId 学生ID(无教材时用于获取「已学知识点」,仅从已学内容补充,避免未学章节)
  3081. * @return array 补充的题目列表
  3082. */
  3083. private function getSupplementaryQuestionsForGrade(
  3084. int $grade,
  3085. array $existingKpCodes,
  3086. int $needCount,
  3087. int $difficultyCategory,
  3088. ?int $textbookId = null,
  3089. array $excludeQuestionIds = [],
  3090. ?array $textbookCatalogNodeIds = null,
  3091. ?string $studentId = null
  3092. ): array {
  3093. try {
  3094. Log::info('getSupplementaryQuestionsForGrade: 开始智能补充', [
  3095. 'grade' => $grade,
  3096. 'existing_kp_count' => count($existingKpCodes),
  3097. 'need_count' => $needCount,
  3098. 'difficulty_category' => $difficultyCategory,
  3099. 'textbook_id' => $textbookId,
  3100. 'student_id' => $studentId ? '(有)' : '(无)',
  3101. 'exclude_count' => count($excludeQuestionIds),
  3102. 'has_chapter_scope' => !empty($textbookCatalogNodeIds),
  3103. ]);
  3104. // 【核心】补充范围:只从「学过的」内容补充,不能从未学知识点或年级对应章节中选
  3105. // - 有 textbookId:从 textbook_id -> 章节 -> 章节知识点关联表 取 kp_code(若有 chapter scope 再收缩到前章节)
  3106. // - 无 textbookId 且有 studentId:从学生做过的题目对应知识点(getStudentLearnedKpCodes)补充
  3107. // - 无 textbookId 且无 studentId:无法确定学过的内容,不补充
  3108. $gradeKpCodes = [];
  3109. if ($textbookId) {
  3110. $allCatalogNodeIds = DB::table('textbook_catalog_nodes')
  3111. ->where('textbook_id', $textbookId)
  3112. ->pluck('id')
  3113. ->map(static fn ($id) => (int) $id)
  3114. ->toArray();
  3115. $gradeKpCodes = $this->getKpCodesForCatalogChapterIds($allCatalogNodeIds);
  3116. Log::info('getSupplementaryQuestionsForGrade: 教材模式,按章节关联知识点补题', [
  3117. 'kp_count' => count($gradeKpCodes),
  3118. 'textbook_id' => $textbookId,
  3119. 'catalog_node_count' => count($allCatalogNodeIds),
  3120. ]);
  3121. } elseif ($studentId) {
  3122. $learnedKps = $this->getStudentLearnedKpCodes($studentId);
  3123. $gradeKpCodes = array_values(array_diff($learnedKps, $existingKpCodes));
  3124. Log::info('getSupplementaryQuestionsForGrade: 无教材模式,使用学生已学知识点', [
  3125. 'learned_count' => count($learnedKps),
  3126. 'after_exclude_existing' => count($gradeKpCodes),
  3127. ]);
  3128. } else {
  3129. Log::warning('getSupplementaryQuestionsForGrade: 无教材且无学生ID,无法确定学过的内容,不补充');
  3130. return [];
  3131. }
  3132. if (empty($gradeKpCodes)) {
  3133. Log::warning('getSupplementaryQuestionsForGrade: 无可用知识点,跳过补充', [
  3134. 'grade' => $grade,
  3135. 'textbook_id' => $textbookId,
  3136. 'note' => $textbookId ? '教材知识点不足' : '学生已学知识点不足或与当前选题重复',
  3137. ]);
  3138. return [];
  3139. }
  3140. // 有教材且带章节:用 textbook_chapter_knowledge_relation 由「前章节」解析知识点,再按 kp_code 选题(不用 questions.textbook_catalog_nodes_id)
  3141. $effectiveKpCodes = $gradeKpCodes;
  3142. if ($textbookId && ! empty($textbookCatalogNodeIds)) {
  3143. $allowedNodeIds = $this->getEarlierChapterNodeIds((int) $textbookId, $textbookCatalogNodeIds);
  3144. if (empty($allowedNodeIds)) {
  3145. Log::warning('getSupplementaryQuestionsForGrade: 未找到前章节节点,跳过补充');
  3146. return [];
  3147. }
  3148. $chapterKpCodes = $this->getKpCodesForCatalogChapterIds($allowedNodeIds);
  3149. if (empty($chapterKpCodes)) {
  3150. Log::warning('getSupplementaryQuestionsForGrade: 前章节在 textbook_chapter_knowledge_relation 中无知识点', [
  3151. 'allowed_node_ids' => $allowedNodeIds,
  3152. ]);
  3153. return [];
  3154. }
  3155. $effectiveKpCodes = array_values(array_intersect($gradeKpCodes, $chapterKpCodes));
  3156. if (empty($effectiveKpCodes)) {
  3157. Log::warning('getSupplementaryQuestionsForGrade: 教材年级知识点与章节关联知识点无交集', [
  3158. 'grade_kp_count' => count($gradeKpCodes),
  3159. 'chapter_kp_count' => count($chapterKpCodes),
  3160. ]);
  3161. return [];
  3162. }
  3163. Log::info('getSupplementaryQuestionsForGrade: 按章节关联知识点缩小补充范围', [
  3164. 'allowed_chapter_nodes' => count($allowedNodeIds),
  3165. 'chapter_kp_count' => count($chapterKpCodes),
  3166. 'effective_kp_count' => count($effectiveKpCodes),
  3167. ]);
  3168. }
  3169. // 查询同年级其他知识点的题目
  3170. $query = \App\Models\Question::query();
  3171. // 只获取审核通过的题目
  3172. $query->where('audit_status', 0);
  3173. // 【新增】排除学生已做过的题目
  3174. if (!empty($excludeQuestionIds)) {
  3175. $query->whereNotIn('id', $excludeQuestionIds);
  3176. }
  3177. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  3178. if ($stageGrade !== null) {
  3179. $query->where('grade', $stageGrade);
  3180. Log::info('getSupplementaryQuestionsForGrade: 应用学段筛选', [
  3181. 'input_grade' => $grade,
  3182. 'stage_grade' => $stageGrade
  3183. ]);
  3184. }
  3185. // 排除已选知识点
  3186. if (!empty($existingKpCodes)) {
  3187. $query->whereNotIn('kp_code', $existingKpCodes);
  3188. }
  3189. $query->whereIn('kp_code', $effectiveKpCodes);
  3190. // 筛选有解题思路的题目
  3191. $query->whereNotNull('solution')
  3192. ->where('solution', '!=', '')
  3193. ->where('solution', '!=', '[]');
  3194. // 【重要】移除题目分类限制,允许补充其他分类的题目
  3195. // $query->where('question_category', 1); // 移除这行
  3196. // 根据难度类别调整查询
  3197. $difficultyRanges = $this->getDifficultyRangesForCategory($difficultyCategory);
  3198. $query->where(function ($q) use ($difficultyRanges) {
  3199. foreach ($difficultyRanges as $range) {
  3200. $q->orWhereBetween('difficulty', [$range['min'], $range['max']]);
  3201. }
  3202. });
  3203. // 随机排序,增加多样性
  3204. $query->inRandomOrder()
  3205. ->limit($needCount * 2); // 多取一些,后续筛选
  3206. $supplementaryQuestions = $query->get();
  3207. Log::info('getSupplementaryQuestionsForGrade: 查询完成', [
  3208. 'found_count' => $supplementaryQuestions->count(),
  3209. 'need_count' => $needCount
  3210. ]);
  3211. // 格式化题目
  3212. $formatted = [];
  3213. foreach ($supplementaryQuestions as $question) {
  3214. // 优先使用题库原始题型
  3215. $stem = $question->stem ?? '';
  3216. $options = is_array($question->options) ? $question->options : (json_decode($question->options ?? '[]', true) ?: []);
  3217. $correctAnswer = $question->correct_answer ?? '';
  3218. $questionType = $question->question_type ?? 'answer';
  3219. $formatted[] = [
  3220. 'id' => $question->id,
  3221. 'question_bank_id' => $question->id,
  3222. 'question_type' => $questionType,
  3223. 'kp_code' => $question->kp_code,
  3224. 'difficulty' => $question->difficulty !== null ? (float) $question->difficulty : 0.5,
  3225. 'stem' => $stem,
  3226. 'options' => $options,
  3227. 'correct_answer' => $correctAnswer,
  3228. 'solution' => $question->solution,
  3229. 'score' => $question->score ?? 4,
  3230. 'estimated_time' => $question->estimated_time ?? 300,
  3231. 'metadata' => [
  3232. 'question_type_label' => $questionType === 'choice' ? '选择题' : ($questionType === 'fill' ? '填空题' : '解答题'),
  3233. 'difficulty_label' => $this->getDifficultyLabelFromObject($question->difficulty ?? 0.5),
  3234. 'is_supplementary' => true
  3235. ]
  3236. ];
  3237. }
  3238. // 随机选择需要的数量
  3239. shuffle($formatted);
  3240. $selected = array_slice($formatted, 0, $needCount);
  3241. Log::info('getSupplementaryQuestionsForGrade: 补充完成', [
  3242. 'supplementary_count' => count($selected),
  3243. 'kp_distribution' => array_count_values(array_column($selected, 'kp_code'))
  3244. ]);
  3245. return $selected;
  3246. } catch (\Exception $e) {
  3247. Log::error('getSupplementaryQuestionsForGrade: 补充失败', [
  3248. 'grade' => $grade,
  3249. 'need_count' => $needCount,
  3250. 'error' => $e->getMessage()
  3251. ]);
  3252. return [];
  3253. }
  3254. }
  3255. /**
  3256. * 获取同教材中「当前选中章节及之前」的节点 ID 列表(用于前章节补充,避免未学章节)
  3257. *
  3258. * @param int $textbookId 教材ID
  3259. * @param array $chapterNodeIds 当前选中的章节节点ID
  3260. * @return array 允许的节点ID列表(sort_order <= 选中章节的最大 sort_order)
  3261. */
  3262. private function getEarlierChapterNodeIds(int $textbookId, array $chapterNodeIds): array
  3263. {
  3264. if (empty($chapterNodeIds)) {
  3265. return [];
  3266. }
  3267. try {
  3268. $maxSortOrder = DB::table('textbook_catalog_nodes')
  3269. ->where('textbook_id', $textbookId)
  3270. ->whereIn('id', $chapterNodeIds)
  3271. ->max('sort_order');
  3272. if ($maxSortOrder === null) {
  3273. Log::warning('getEarlierChapterNodeIds: 未找到选中章节的 sort_order', [
  3274. 'textbook_id' => $textbookId,
  3275. 'chapter_node_ids' => $chapterNodeIds
  3276. ]);
  3277. return [];
  3278. }
  3279. $allowedNodeIds = DB::table('textbook_catalog_nodes')
  3280. ->where('textbook_id', $textbookId)
  3281. ->where('sort_order', '<=', $maxSortOrder)
  3282. ->pluck('id')
  3283. ->toArray();
  3284. Log::info('getEarlierChapterNodeIds: 前章节节点', [
  3285. 'textbook_id' => $textbookId,
  3286. 'max_sort_order' => $maxSortOrder,
  3287. 'allowed_node_count' => count($allowedNodeIds)
  3288. ]);
  3289. return $allowedNodeIds;
  3290. } catch (\Exception $e) {
  3291. Log::error('getEarlierChapterNodeIds: 查询失败', [
  3292. 'textbook_id' => $textbookId,
  3293. 'error' => $e->getMessage()
  3294. ]);
  3295. return [];
  3296. }
  3297. }
  3298. /**
  3299. * 获取指定年级的知识点列表
  3300. *
  3301. * @param int $grade 年级
  3302. * @param int|null $textbookId 教材ID(可选,用于限制在特定教材范围内,避免超纲)
  3303. * @return array 知识点代码列表
  3304. */
  3305. /**
  3306. * 获取学生「已学知识点」:通过该学生做过的题目(paper_questions)对应的 kp_code 推断
  3307. * 用于无教材信息时,智能补充仅从已学知识点中选,避免出现未学内容
  3308. *
  3309. * @param string|null $studentId 学生ID
  3310. * @return array 知识点代码列表(去重、非空)
  3311. */
  3312. private function getStudentLearnedKpCodes(?string $studentId): array
  3313. {
  3314. if (empty($studentId)) {
  3315. return [];
  3316. }
  3317. try {
  3318. $questionBankIds = \App\Models\PaperQuestion::query()
  3319. ->whereHas('paper', fn($q) => $q->where('student_id', $studentId))
  3320. ->pluck('question_bank_id')
  3321. ->unique()
  3322. ->filter()
  3323. ->values()
  3324. ->toArray();
  3325. if (empty($questionBankIds)) {
  3326. Log::info('getStudentLearnedKpCodes: 学生暂无做题记录', ['student_id' => $studentId]);
  3327. return [];
  3328. }
  3329. $kpCodes = \App\Models\Question::query()
  3330. ->whereIn('id', $questionBankIds)
  3331. ->whereNotNull('kp_code')
  3332. ->where('kp_code', '!=', '')
  3333. ->pluck('kp_code')
  3334. ->unique()
  3335. ->values()
  3336. ->toArray();
  3337. Log::info('getStudentLearnedKpCodes: 已学知识点', [
  3338. 'student_id' => $studentId,
  3339. 'kp_count' => count($kpCodes),
  3340. ]);
  3341. return $kpCodes;
  3342. } catch (\Exception $e) {
  3343. Log::error('getStudentLearnedKpCodes: 查询失败', [
  3344. 'student_id' => $studentId,
  3345. 'error' => $e->getMessage(),
  3346. ]);
  3347. return [];
  3348. }
  3349. }
  3350. /**
  3351. * 由 catalog 章节节点 ID 列表,从 textbook_chapter_knowledge_relation 取关联的知识点编码(用于选题,而非题目表上的章节字段)。
  3352. *
  3353. * @param array<int> $catalogChapterIds textbook_catalog_nodes.id
  3354. * @return list<string>
  3355. */
  3356. private function getKpCodesForCatalogChapterIds(array $catalogChapterIds): array
  3357. {
  3358. $ids = array_values(array_unique(array_filter(array_map(
  3359. static fn ($id) => (int) $id,
  3360. $catalogChapterIds
  3361. ), static fn (int $id) => $id > 0)));
  3362. if ($ids === []) {
  3363. return [];
  3364. }
  3365. return array_values(array_filter(array_unique(DB::table('textbook_chapter_knowledge_relation')
  3366. ->whereIn('catalog_chapter_id', $ids)
  3367. ->where(function ($q) {
  3368. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  3369. })
  3370. ->pluck('kp_code')
  3371. ->toArray())));
  3372. }
  3373. private function getGradeKnowledgePoints(int $grade, ?int $textbookId = null): array
  3374. {
  3375. try {
  3376. $query = DB::table('textbook_chapter_knowledge_relation as tckr')
  3377. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  3378. ->join('textbooks as t', 'tcn.textbook_id', '=', 't.id')
  3379. ->where('t.grade', $grade)
  3380. ->where(function ($q) {
  3381. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  3382. });
  3383. // 【修复超纲问题】如果有 textbook_id,严格限制在该教材范围内
  3384. // 避免七年级上册学生拿到七年级下册的知识点
  3385. if ($textbookId) {
  3386. $query->where('t.id', $textbookId);
  3387. Log::info('getGradeKnowledgePoints: 限制在指定教材范围内', [
  3388. 'grade' => $grade,
  3389. 'textbook_id' => $textbookId
  3390. ]);
  3391. }
  3392. $kpCodes = $query->distinct()
  3393. ->pluck('tckr.kp_code')
  3394. ->toArray();
  3395. Log::info('getGradeKnowledgePoints: 获取知识点完成', [
  3396. 'grade' => $grade,
  3397. 'textbook_id' => $textbookId,
  3398. 'kp_count' => count($kpCodes)
  3399. ]);
  3400. return array_filter($kpCodes);
  3401. } catch (\Exception $e) {
  3402. Log::error('getGradeKnowledgePoints: 查询失败', [
  3403. 'grade' => $grade,
  3404. 'textbook_id' => $textbookId,
  3405. 'error' => $e->getMessage()
  3406. ]);
  3407. return [];
  3408. }
  3409. }
  3410. /**
  3411. * 【新增】根据难度类别获取难度范围
  3412. */
  3413. private function getDifficultyRangesForCategory(int $difficultyCategory): array
  3414. {
  3415. return match($difficultyCategory) {
  3416. 1 => [
  3417. ['min' => 0.0, 'max' => 0.5], // 基础型:偏向低难度
  3418. ['min' => 0.5, 'max' => 1.0],
  3419. ],
  3420. 2 => [
  3421. ['min' => 0.0, 'max' => 0.5], // 进阶型:均衡分布
  3422. ['min' => 0.5, 'max' => 1.0],
  3423. ],
  3424. 3 => [
  3425. ['min' => 0.25, 'max' => 0.75], // 中等型:偏向中等难度
  3426. ['min' => 0.0, 'max' => 1.0],
  3427. ],
  3428. 4 => [
  3429. ['min' => 0.5, 'max' => 1.0], // 拔高型:偏向高难度
  3430. ['min' => 0.0, 'max' => 0.5],
  3431. ],
  3432. default => [
  3433. ['min' => 0.0, 'max' => 1.0],
  3434. ]
  3435. };
  3436. }
  3437. private function normalizeQuestionStageGrade(int $grade): ?int
  3438. {
  3439. if ($grade <= 0) {
  3440. return null;
  3441. }
  3442. // 年级转学段 todo:下一步需要视频小学
  3443. return $grade <= 9 ? 2 : 3;
  3444. }
  3445. /**
  3446. * 【新增】获取难度标签(重载版本)
  3447. */
  3448. private function getDifficultyLabelFromObject(?float $difficulty): string
  3449. {
  3450. if ($difficulty === null) return '未知';
  3451. if ($difficulty < 0.3) return '基础';
  3452. if ($difficulty < 0.7) return '中等';
  3453. return '拔高';
  3454. }
  3455. private function buildDifficultyDistributionStats(array $questions, int $difficultyCategory): array
  3456. {
  3457. if (empty($questions)) {
  3458. return [];
  3459. }
  3460. $service = app(DifficultyDistributionService::class);
  3461. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3462. $total = max(1, count($questions));
  3463. return array_map(static function ($bucket) use ($total) {
  3464. $count = count($bucket);
  3465. return [
  3466. 'count' => $count,
  3467. 'ratio' => round(($count / $total) * 100, 2),
  3468. ];
  3469. }, $buckets);
  3470. }
  3471. private function buildDifficultyDistributionShortage(array $questions, int $difficultyCategory, int $totalQuestions): array
  3472. {
  3473. $service = app(DifficultyDistributionService::class);
  3474. $distribution = $service->calculateDistribution($difficultyCategory, $totalQuestions);
  3475. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3476. $expected = [
  3477. 'primary_low' => 0,
  3478. 'primary_medium' => 0,
  3479. 'primary_high' => 0,
  3480. 'secondary' => 0,
  3481. 'other' => 0,
  3482. ];
  3483. foreach ($distribution as $level => $config) {
  3484. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3485. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  3486. }
  3487. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  3488. $shortage = [];
  3489. foreach ($expected as $bucketKey => $count) {
  3490. $actualCount = $actual[$bucketKey] ?? 0;
  3491. $shortage[$bucketKey] = [
  3492. 'expected' => $count,
  3493. 'actual' => $actualCount,
  3494. 'short' => max(0, $count - $actualCount),
  3495. ];
  3496. }
  3497. return $shortage;
  3498. }
  3499. /**
  3500. * 题型感知的难度分布选题
  3501. * 在每种题型内部应用难度分布,确保题型比例和难度分布同时被满足
  3502. */
  3503. private function applyTypeAwareDifficultyDistribution(
  3504. array $allQuestions,
  3505. array $selectedQuestions,
  3506. int $totalQuestions,
  3507. int $difficultyCategory,
  3508. array $questionTypeRatio
  3509. ): array {
  3510. $diffService = app(DifficultyDistributionService::class);
  3511. $distribution = $diffService->calculateDistribution($difficultyCategory, $totalQuestions);
  3512. // 1. 计算每种题型的目标数量
  3513. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  3514. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  3515. $typeTargets = [];
  3516. $fractions = [];
  3517. $allocated = 0;
  3518. foreach ($ratioMap as $type => $ratioKey) {
  3519. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  3520. $exact = $totalQuestions * $ratio / $totalRatio;
  3521. $typeTargets[$type] = (int) floor($exact);
  3522. $fractions[$type] = $exact - floor($exact);
  3523. $allocated += $typeTargets[$type];
  3524. }
  3525. $remainder = $totalQuestions - $allocated;
  3526. arsort($fractions);
  3527. foreach ($fractions as $type => $frac) {
  3528. if ($remainder <= 0) break;
  3529. $typeTargets[$type]++;
  3530. $remainder--;
  3531. }
  3532. // 2. 构建候选题池(合并 allQuestions + selectedQuestions 去重)
  3533. $candidatePool = [];
  3534. $seen = [];
  3535. foreach (array_merge($allQuestions, $selectedQuestions) as $q) {
  3536. $id = $q['id'] ?? null;
  3537. if ($id && !isset($seen[$id])) {
  3538. $seen[$id] = true;
  3539. $candidatePool[] = $q;
  3540. }
  3541. }
  3542. // 3. 按题型分组候选题
  3543. $candidatesByType = ['choice' => [], 'fill' => [], 'answer' => []];
  3544. foreach ($candidatePool as $q) {
  3545. $qType = $q['question_type'] ?? '';
  3546. if (isset($candidatesByType[$qType])) {
  3547. $candidatesByType[$qType][] = $q;
  3548. }
  3549. }
  3550. // 4. 在每种题型内按难度分桶选题
  3551. $result = [];
  3552. $usedIds = [];
  3553. $typeActual = [];
  3554. foreach ($ratioMap as $type => $ratioKey) {
  3555. $target = $typeTargets[$type];
  3556. if ($target <= 0) {
  3557. $typeActual[$type] = 0;
  3558. continue;
  3559. }
  3560. $typeCandidates = $candidatesByType[$type];
  3561. $buckets = $diffService->groupQuestionsByDifficultyRange($typeCandidates, $difficultyCategory);
  3562. // 按 distribution 比例在该题型内选题
  3563. $typeSelected = [];
  3564. foreach ($distribution as $level => $config) {
  3565. $levelRatio = $config['percentage'];
  3566. $levelTarget = max(0, (int) round($target * $levelRatio / 100));
  3567. if ($levelTarget <= 0) continue;
  3568. $rangeKey = $diffService->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3569. $bucket = $buckets[$rangeKey] ?? [];
  3570. shuffle($bucket);
  3571. $taken = 0;
  3572. foreach ($bucket as $q) {
  3573. if ($taken >= $levelTarget) break;
  3574. $qid = $q['id'] ?? null;
  3575. if ($qid && !isset($usedIds[$qid])) {
  3576. $typeSelected[] = $q;
  3577. $usedIds[$qid] = true;
  3578. $taken++;
  3579. }
  3580. }
  3581. }
  3582. // 如果难度分布不满足目标数,从该题型剩余题目补充
  3583. if (count($typeSelected) < $target) {
  3584. $allTypeBuckets = array_merge(
  3585. $buckets['primary_medium'] ?? [],
  3586. $buckets['primary_low'] ?? [],
  3587. $buckets['primary_high'] ?? [],
  3588. $buckets['secondary'] ?? [],
  3589. $buckets['other'] ?? []
  3590. );
  3591. shuffle($allTypeBuckets);
  3592. foreach ($allTypeBuckets as $q) {
  3593. if (count($typeSelected) >= $target) break;
  3594. $qid = $q['id'] ?? null;
  3595. if ($qid && !isset($usedIds[$qid])) {
  3596. $typeSelected[] = $q;
  3597. $usedIds[$qid] = true;
  3598. }
  3599. }
  3600. }
  3601. $typeActual[$type] = count($typeSelected);
  3602. $result = array_merge($result, $typeSelected);
  3603. }
  3604. // 5. 如果总数不足(某题型候选不够),跨题型补充
  3605. if (count($result) < $totalQuestions) {
  3606. $deficit = $totalQuestions - count($result);
  3607. // 按 fill > choice > answer 优先级补充
  3608. $supplementOrder = ['fill', 'choice', 'answer'];
  3609. foreach ($supplementOrder as $type) {
  3610. if ($deficit <= 0) break;
  3611. $bucket = $candidatesByType[$type];
  3612. shuffle($bucket);
  3613. foreach ($bucket as $q) {
  3614. if ($deficit <= 0) break;
  3615. $qid = $q['id'] ?? null;
  3616. if ($qid && !isset($usedIds[$qid])) {
  3617. $result[] = $q;
  3618. $usedIds[$qid] = true;
  3619. $deficit--;
  3620. }
  3621. }
  3622. }
  3623. }
  3624. Log::info('LearningAnalyticsService: 题型感知难度分布详情', [
  3625. 'type_targets' => $typeTargets,
  3626. 'type_actual' => $typeActual,
  3627. 'total_result' => count($result),
  3628. 'difficulty_category' => $difficultyCategory,
  3629. 'candidates_by_type' => array_map('count', $candidatesByType),
  3630. ]);
  3631. return array_slice($result, 0, $totalQuestions);
  3632. }
  3633. /**
  3634. * 统计题目列表中各题型的数量
  3635. */
  3636. private function countByType(array $questions): array
  3637. {
  3638. $counts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  3639. foreach ($questions as $q) {
  3640. $type = $q['question_type'] ?? '';
  3641. if (isset($counts[$type])) {
  3642. $counts[$type]++;
  3643. }
  3644. }
  3645. return $counts;
  3646. }
  3647. private function buildDistributionCandidates(array $allQuestions, array $selectedQuestions, int $difficultyCategory): array
  3648. {
  3649. if (empty($allQuestions)) {
  3650. return $selectedQuestions;
  3651. }
  3652. $service = app(DifficultyDistributionService::class);
  3653. $distribution = $service->calculateDistribution($difficultyCategory, max(1, count($selectedQuestions)));
  3654. $buckets = $service->groupQuestionsByDifficultyRange($allQuestions, $difficultyCategory);
  3655. $preferredBuckets = [];
  3656. foreach ($distribution as $level => $config) {
  3657. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3658. $preferredBuckets[$bucketKey] = true;
  3659. }
  3660. $candidates = [];
  3661. foreach (array_keys($preferredBuckets) as $bucketKey) {
  3662. foreach ($buckets[$bucketKey] ?? [] as $q) {
  3663. $candidates[] = $q;
  3664. }
  3665. }
  3666. foreach ($selectedQuestions as $q) {
  3667. $candidates[] = $q;
  3668. }
  3669. $seen = [];
  3670. $unique = [];
  3671. foreach ($candidates as $q) {
  3672. $id = $q['id'] ?? null;
  3673. if (!$id || isset($seen[$id])) {
  3674. continue;
  3675. }
  3676. $seen[$id] = true;
  3677. $unique[] = $q;
  3678. }
  3679. return $unique;
  3680. }
  3681. }