LearningAnalyticsService.php 144 KB

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