LearningAnalyticsService.php 144 KB

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