LearningAnalyticsService.php 151 KB

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