LearningAnalyticsService.php 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\DB;
  6. use App\Services\ExamTypeStrategy;
  7. use App\Services\QuestionExpansionService;
  8. /**
  9. * 学习分析服务(本地化重构版)
  10. *
  11. * 原先调用外部 LearningAnalytics API (localhost:5016)
  12. * 现已重构为使用本地服务:MasteryCalculator、KnowledgeMasteryService 等
  13. */
  14. class LearningAnalyticsService
  15. {
  16. protected string $baseUrl;
  17. protected int $timeout = 10;
  18. protected ?QuestionExpansionService $questionExpansionService;
  19. protected ?MasteryCalculator $masteryCalculator;
  20. protected ?LocalAIAnalysisService $aiAnalysisService;
  21. public function __construct(
  22. ?QuestionExpansionService $questionExpansionService = null,
  23. ?MasteryCalculator $masteryCalculator = null,
  24. ?LocalAIAnalysisService $aiAnalysisService = null
  25. ) {
  26. // 保留baseUrl用于兼容,但不再实际调用
  27. $this->baseUrl = config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016'));
  28. $this->questionExpansionService = $questionExpansionService;
  29. $this->masteryCalculator = $masteryCalculator ?? app(MasteryCalculator::class);
  30. $this->aiAnalysisService = $aiAnalysisService ?? app(LocalAIAnalysisService::class);
  31. }
  32. /**
  33. * 获取学生掌握度(本地化)
  34. */
  35. public function getStudentMastery(string $studentId, string $kpCode = null): array
  36. {
  37. try {
  38. Log::info('LearningAnalyticsService: 获取学生掌握度 (本地)', [
  39. 'student_id' => $studentId,
  40. 'kp_code' => $kpCode
  41. ]);
  42. if ($kpCode) {
  43. // 获取特定知识点掌握度
  44. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  45. return [
  46. 'student_id' => $studentId,
  47. 'kp_code' => $kpCode,
  48. 'mastery_level' => $result['mastery'],
  49. 'confidence' => $result['confidence'],
  50. 'trend' => $result['trend'],
  51. 'total_attempts' => $result['total_attempts'],
  52. 'correct_attempts' => $result['correct_attempts'],
  53. ];
  54. }
  55. // 获取全部知识点掌握度概览
  56. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  57. return [
  58. 'student_id' => $studentId,
  59. 'total_knowledge_points' => $overview['total_knowledge_points'],
  60. 'average_mastery' => $overview['average_mastery_level'],
  61. 'mastered_count' => $overview['mastered_knowledge_points'],
  62. 'good_count' => $overview['good_knowledge_points'],
  63. 'weak_count' => $overview['weak_knowledge_points'],
  64. 'weak_list' => $overview['weak_knowledge_points_list'],
  65. 'details' => $overview['details'],
  66. ];
  67. } catch (\Exception $e) {
  68. Log::error('LearningAnalyticsService: 获取掌握度失败', [
  69. 'student_id' => $studentId,
  70. 'error' => $e->getMessage(),
  71. ]);
  72. return [
  73. 'error' => true,
  74. 'message' => $e->getMessage()
  75. ];
  76. }
  77. }
  78. /**
  79. * 更新学生掌握度(本地化)
  80. */
  81. public function updateMastery(array $data): array
  82. {
  83. try {
  84. $studentId = $data['student_id'];
  85. $kpCode = $data['kp_code'];
  86. $isCorrect = $data['is_correct'] ?? false;
  87. $difficulty = $data['difficulty_level'] ?? 0.5;
  88. Log::info('LearningAnalyticsService: 更新掌握度 (本地)', [
  89. 'student_id' => $studentId,
  90. 'kp_code' => $kpCode,
  91. ]);
  92. // 获取当前掌握度
  93. $currentMastery = DB::table('student_knowledge_mastery')
  94. ->where('student_id', $studentId)
  95. ->where('kp_code', $kpCode)
  96. ->value('mastery_level') ?? 0.5;
  97. // 使用LocalAIAnalysisService更新掌握度
  98. $result = $this->aiAnalysisService->updateMastery(
  99. $studentId,
  100. $kpCode,
  101. $currentMastery,
  102. $isCorrect,
  103. $difficulty
  104. );
  105. return [
  106. 'success' => true,
  107. 'data' => $result
  108. ];
  109. } catch (\Exception $e) {
  110. Log::error('LearningAnalyticsService: 更新掌握度失败', [
  111. 'data' => $data,
  112. 'error' => $e->getMessage(),
  113. ]);
  114. return [
  115. 'error' => true,
  116. 'message' => $e->getMessage()
  117. ];
  118. }
  119. }
  120. /**
  121. * 获取老师名下的所有学生
  122. */
  123. public function getTeacherStudents(string $teacherId): array
  124. {
  125. try {
  126. // 从本地MySQL获取学生
  127. $students = DB::table('students as s')
  128. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  129. ->where('s.teacher_id', $teacherId)
  130. ->select(
  131. 's.student_id',
  132. 's.name',
  133. 's.grade',
  134. 's.class_name',
  135. 'u.username',
  136. 'u.email'
  137. )
  138. ->get()
  139. ->toArray();
  140. return $students;
  141. } catch (\Exception $e) {
  142. Log::error('Get Teacher Students Error', [
  143. 'teacher_id' => $teacherId,
  144. 'error' => $e->getMessage()
  145. ]);
  146. return [];
  147. }
  148. }
  149. /**
  150. * 获取学生学习分析
  151. */
  152. public function getStudentAnalysis(string $studentId): array
  153. {
  154. // 从LearningAnalytics获取掌握度
  155. $masteryData = $this->getStudentMastery($studentId);
  156. // 从MySQL获取练习历史
  157. $exercises = DB::table('student_exercises')
  158. ->where('student_id', $studentId)
  159. ->orderBy('created_at', 'desc')
  160. ->limit(50)
  161. ->get()
  162. ->toArray();
  163. // 从MySQL获取掌握度记录
  164. $masteryRecords = DB::table('student_mastery')
  165. ->where('student_id', $studentId)
  166. ->get()
  167. ->toArray();
  168. return [
  169. 'student_id' => $studentId,
  170. 'mastery_from_la' => $masteryData,
  171. 'exercises' => $exercises,
  172. 'mastery_records' => $masteryRecords,
  173. 'total_exercises' => count($exercises),
  174. 'total_mastery_records' => count($masteryRecords),
  175. ];
  176. }
  177. /**
  178. * 生成学习测试数据
  179. */
  180. public function generateLearningData(string $studentId, array $params): array
  181. {
  182. $results = [];
  183. foreach ($params as $param) {
  184. $data = [
  185. 'student_id' => $studentId,
  186. 'kp_code' => $param['kp_code'],
  187. 'is_correct' => $param['is_correct'],
  188. 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
  189. 'difficulty_level' => $param['difficulty_level'] ?? 3,
  190. ];
  191. $result = $this->updateMastery($data);
  192. $results[] = $result;
  193. }
  194. return $results;
  195. }
  196. /**
  197. * 获取学习推荐
  198. */
  199. public function getLearningRecommendations(string $studentId): array
  200. {
  201. try {
  202. Log::info('LearningAnalytics Request: Get Learning Recommendations', [
  203. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend"
  204. ]);
  205. $response = Http::timeout($this->timeout)
  206. ->post($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
  207. Log::info('LearningAnalytics Response: Get Learning Recommendations', [
  208. 'status' => $response->status(),
  209. 'body' => $response->json()
  210. ]);
  211. if ($response->successful()) {
  212. return $response->json();
  213. }
  214. return ['error' => true, 'message' => 'Failed to fetch recommendations'];
  215. } catch (\Exception $e) {
  216. return ['error' => true, 'message' => $e->getMessage()];
  217. }
  218. }
  219. /**
  220. * 获取知识点列表(从知识图谱API)
  221. */
  222. public function getKnowledgePoints(array $filters = []): array
  223. {
  224. try {
  225. $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
  226. Log::info('LearningAnalytics Request: Get Knowledge Points', [
  227. 'url' => $kgBaseUrl . '/knowledge-points/',
  228. 'filters' => $filters
  229. ]);
  230. $response = Http::timeout($this->timeout)
  231. ->get($kgBaseUrl . '/knowledge-points/', $filters);
  232. Log::info('LearningAnalytics Response: Get Knowledge Points', [
  233. 'status' => $response->status(),
  234. 'count' => count($response->json()['data'] ?? [])
  235. ]);
  236. if ($response->successful()) {
  237. return $response->json()['data'] ?? [];
  238. }
  239. return [];
  240. } catch (\Exception $e) {
  241. Log::error('LearningAnalytics Knowledge Points Error', [
  242. 'error' => $e->getMessage()
  243. ]);
  244. return [];
  245. }
  246. }
  247. /**
  248. * 获取学生技能熟练度
  249. */
  250. public function getStudentSkillProficiency(string $studentId): array
  251. {
  252. try {
  253. Log::info('LearningAnalytics Request: Get Student Skill Proficiency', [
  254. 'url' => $this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}"
  255. ]);
  256. $response = Http::timeout($this->timeout)
  257. ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
  258. Log::info('LearningAnalytics Response: Get Student Skill Proficiency', [
  259. 'status' => $response->status(),
  260. 'body' => $response->json()
  261. ]);
  262. if ($response->successful()) {
  263. return $response->json();
  264. }
  265. Log::warning('LearningAnalytics Skill Proficiency API Error', [
  266. 'student_id' => $studentId,
  267. 'status' => $response->status(),
  268. 'response' => $response->body()
  269. ]);
  270. // API失败时返回空数据,不报错
  271. return [
  272. 'student_id' => $studentId,
  273. 'total_count' => 0,
  274. 'data' => []
  275. ];
  276. } catch (\Exception $e) {
  277. Log::warning('LearningAnalytics Skill Proficiency API Exception', [
  278. 'student_id' => $studentId,
  279. 'error' => $e->getMessage()
  280. ]);
  281. // 发生异常时返回空数据,不报错
  282. return [
  283. 'student_id' => $studentId,
  284. 'total_count' => 0,
  285. 'data' => []
  286. ];
  287. }
  288. }
  289. /**
  290. * 获取学生掌握度列表(别名方法)
  291. */
  292. public function getStudentMasteryList(string $studentId): array
  293. {
  294. return $this->getStudentMastery($studentId);
  295. }
  296. /**
  297. * 获取知识点依赖关系
  298. */
  299. public function getKnowledgeDependencies(): array
  300. {
  301. try {
  302. Log::info('LearningAnalytics Request: Get Knowledge Dependencies', [
  303. 'url' => $this->baseUrl . '/knowledge-dependencies/'
  304. ]);
  305. $response = Http::timeout($this->timeout)
  306. ->get($this->baseUrl . '/knowledge-dependencies/');
  307. Log::info('LearningAnalytics Response: Get Knowledge Dependencies', [
  308. 'status' => $response->status(),
  309. 'count' => count($response->json()['data'] ?? [])
  310. ]);
  311. if ($response->successful()) {
  312. return $response->json()['data'] ?? [];
  313. }
  314. return [];
  315. } catch (\Exception $e) {
  316. Log::error('LearningAnalytics Knowledge Dependencies Error', [
  317. 'error' => $e->getMessage()
  318. ]);
  319. return [];
  320. }
  321. }
  322. /**
  323. * 提交学生答题记录
  324. */
  325. public function submitAttempt(string $studentId, array $attemptData): array
  326. {
  327. try {
  328. Log::info('LearningAnalytics Request: Submit Attempt', [
  329. 'url' => $this->baseUrl . "/api/v1/attempts/student/{$studentId}",
  330. 'data' => $attemptData
  331. ]);
  332. $response = Http::timeout($this->timeout)
  333. ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
  334. Log::info('LearningAnalytics Response: Submit Attempt', [
  335. 'status' => $response->status(),
  336. 'body' => $response->json()
  337. ]);
  338. if ($response->successful()) {
  339. return $response->json();
  340. }
  341. Log::error('Submit Attempt Error', [
  342. 'student_id' => $studentId,
  343. 'data' => $attemptData,
  344. 'status' => $response->status(),
  345. 'response' => $response->body()
  346. ]);
  347. return [
  348. 'error' => true,
  349. 'message' => 'Failed to submit attempt'
  350. ];
  351. } catch (\Exception $e) {
  352. Log::error('Submit Attempt Exception', [
  353. 'student_id' => $studentId,
  354. 'error' => $e->getMessage(),
  355. 'data' => $attemptData
  356. ]);
  357. return [
  358. 'error' => true,
  359. 'message' => $e->getMessage()
  360. ];
  361. }
  362. }
  363. /**
  364. * 批量提交学生答题记录
  365. */
  366. public function submitBatchAttempts(string $studentId, array $data): array
  367. {
  368. try {
  369. Log::info('LearningAnalytics Request: Submit Batch Attempts', [
  370. 'url' => $this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}",
  371. 'data_count' => count($data['answers'] ?? []),
  372. 'paper_id' => $data['paper_id'] ?? null
  373. ]);
  374. $response = Http::timeout($this->timeout)
  375. ->post($this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}", $data);
  376. Log::info('LearningAnalytics Response: Submit Batch Attempts', [
  377. 'status' => $response->status(),
  378. 'body' => $response->json()
  379. ]);
  380. if ($response->successful()) {
  381. return $response->json();
  382. }
  383. Log::error('Submit Batch Attempts Error', [
  384. 'student_id' => $studentId,
  385. 'data_count' => count($data['answers'] ?? []),
  386. 'status' => $response->status(),
  387. 'response' => $response->body()
  388. ]);
  389. return [
  390. 'error' => true,
  391. 'message' => 'Failed to submit batch attempts: ' . $response->body()
  392. ];
  393. } catch (\Exception $e) {
  394. Log::error('Submit Batch Attempts Exception', [
  395. 'student_id' => $studentId,
  396. 'error' => $e->getMessage()
  397. ]);
  398. return [
  399. 'error' => true,
  400. 'message' => $e->getMessage()
  401. ];
  402. }
  403. }
  404. /**
  405. * 提交OCR分析请求
  406. */
  407. public function submitOCRAnalysis(array $data): array
  408. {
  409. Log::warning('submitOCRAnalysis 已停用:分析项目已下线', [
  410. 'student_id' => $data['student_id'] ?? 'unknown',
  411. 'exam_id' => $data['exam_id'] ?? 'unknown',
  412. ]);
  413. return [
  414. 'success' => false,
  415. 'message' => 'analysis_api_disabled',
  416. ];
  417. }
  418. /**
  419. * 获取分析结果详情
  420. */
  421. public function getAnalysisResult(string $analysisId): array
  422. {
  423. Log::warning('getAnalysisResult 已停用:分析项目已下线', [
  424. 'analysis_id' => $analysisId,
  425. ]);
  426. return [
  427. 'success' => false,
  428. 'message' => 'analysis_api_disabled',
  429. ];
  430. }
  431. /**
  432. * 检查服务健康状态(本地化)
  433. */
  434. public function checkHealth(): bool
  435. {
  436. // 检查本地服务是否可用
  437. try {
  438. $this->masteryCalculator->getStudentMasteryOverview('test');
  439. return true;
  440. } catch (\Exception $e) {
  441. return false;
  442. }
  443. }
  444. /**
  445. * 获取学生掌握度概览(本地化)
  446. */
  447. public function getStudentMasteryOverview(string $studentId): array
  448. {
  449. try {
  450. // 直接使用MasteryCalculator
  451. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  452. return [
  453. 'total_knowledge_points' => $overview['total_knowledge_points'],
  454. 'average_mastery_level' => $overview['average_mastery_level'],
  455. 'mastered_knowledge_points' => $overview['mastered_knowledge_points'],
  456. 'good_knowledge_points' => $overview['good_knowledge_points'],
  457. 'weak_knowledge_points' => $overview['weak_knowledge_points'],
  458. 'weak_knowledge_points_list' => $overview['weak_knowledge_points_list'],
  459. 'details' => $overview['details']
  460. ];
  461. } catch (\Exception $e) {
  462. Log::error('Get Student Mastery Overview Error', [
  463. 'student_id' => $studentId,
  464. 'error' => $e->getMessage()
  465. ]);
  466. return [
  467. 'total_knowledge_points' => 0,
  468. 'average_mastery_level' => 0,
  469. 'mastered_knowledge_points' => 0,
  470. 'good_knowledge_points' => 0,
  471. 'weak_knowledge_points' => 0,
  472. 'weak_knowledge_points_list' => [],
  473. 'details' => []
  474. ];
  475. }
  476. }
  477. /**
  478. * 获取学生技能摘要
  479. */
  480. public function getStudentSkillSummary(string $studentId): array
  481. {
  482. try {
  483. $proficiency = $this->getStudentSkillProficiency($studentId);
  484. // 无论是否有error,都继续处理,返回空数据
  485. $data = $proficiency['data'] ?? [];
  486. $totalSkills = count($data);
  487. $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
  488. // 计算总答题数
  489. $totalQuestions = 0;
  490. foreach ($data as $skill) {
  491. $totalQuestions += $skill['total_questions_attempted'] ?? 0;
  492. }
  493. return [
  494. 'total_skills' => $totalSkills,
  495. 'average_proficiency_level' => $averageLevel,
  496. 'total_questions_attempted' => $totalQuestions,
  497. 'skill_list' => $data
  498. ];
  499. } catch (\Exception $e) {
  500. Log::warning('Get Student Skill Summary Error', [
  501. 'student_id' => $studentId,
  502. 'error' => $e->getMessage()
  503. ]);
  504. // 发生异常时返回空数据
  505. return [
  506. 'total_skills' => 0,
  507. 'average_proficiency_level' => 0,
  508. 'total_questions_attempted' => 0,
  509. 'skill_list' => []
  510. ];
  511. }
  512. }
  513. /**
  514. * 获取学生预测数据(本地化 - 已停用外部API)
  515. */
  516. public function getStudentPredictions(string $studentId, int $count = 5): array
  517. {
  518. // 外部API已停用,基于本地数据生成预测
  519. try {
  520. Log::info('LearningAnalyticsService: 获取学生预测 (本地)', [
  521. 'student_id' => $studentId,
  522. ]);
  523. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  524. $avgMastery = $overview['average_mastery_level'] ?? 0;
  525. // 基于掌握度生成简单预测
  526. $predictions = [];
  527. if ($avgMastery > 0) {
  528. $predictions[] = [
  529. 'type' => 'score_improvement',
  530. 'current_level' => round($avgMastery * 100),
  531. 'predicted_improvement' => rand(5, 15),
  532. 'confidence' => 0.75,
  533. ];
  534. }
  535. return [
  536. 'predictions' => $predictions
  537. ];
  538. } catch (\Exception $e) {
  539. Log::error('Get Student Predictions Error', [
  540. 'student_id' => $studentId,
  541. 'error' => $e->getMessage()
  542. ]);
  543. return [
  544. 'predictions' => []
  545. ];
  546. }
  547. }
  548. /**
  549. * 获取学生学习路径(本地化 - 已停用外部API)
  550. */
  551. public function getStudentLearningPaths(string $studentId, int $count = 3): array
  552. {
  553. // 外部API已停用,基于薄弱点生成学习路径
  554. try {
  555. Log::info('LearningAnalyticsService: 获取学习路径 (本地)', [
  556. 'student_id' => $studentId,
  557. ]);
  558. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  559. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  560. $paths = [];
  561. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  562. $paths[] = [
  563. 'kp_code' => $weak->kp_code ?? $weak['kp_code'] ?? '',
  564. 'current_mastery' => $weak->mastery_level ?? $weak['mastery_level'] ?? 0,
  565. 'target_mastery' => 0.85,
  566. 'recommended_practice' => 5,
  567. ];
  568. }
  569. return [
  570. 'paths' => $paths
  571. ];
  572. } catch (\Exception $e) {
  573. Log::error('Get Student Learning Paths Error', [
  574. 'student_id' => $studentId,
  575. 'error' => $e->getMessage()
  576. ]);
  577. return [
  578. 'paths' => []
  579. ];
  580. }
  581. }
  582. /**
  583. * 获取预测分析数据
  584. */
  585. public function getPredictionAnalytics(string $studentId): array
  586. {
  587. try {
  588. $predictions = $this->getStudentPredictions($studentId, 10);
  589. if (empty($predictions)) {
  590. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  591. }
  592. $accuracy = 0;
  593. $confidence = 0;
  594. if (!empty($predictions)) {
  595. $accuracy = rand(75, 95); // 模拟准确率
  596. $confidence = rand(70, 90); // 模拟置信度
  597. }
  598. $trend = 'improving'; // improving, stable, declining
  599. return [
  600. 'accuracy' => $accuracy,
  601. 'trend' => $trend,
  602. 'confidence' => $confidence,
  603. 'sample_size' => count($predictions)
  604. ];
  605. } catch (\Exception $e) {
  606. Log::error('Get Prediction Analytics Error', [
  607. 'student_id' => $studentId,
  608. 'error' => $e->getMessage()
  609. ]);
  610. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  611. }
  612. }
  613. /**
  614. * 获取学习路径分析数据
  615. */
  616. public function getLearningPathAnalytics(string $studentId): array
  617. {
  618. try {
  619. $paths = $this->getStudentLearningPaths($studentId, 5);
  620. if (empty($paths)) {
  621. return [
  622. 'active_paths' => 0,
  623. 'completed_paths' => 0,
  624. 'average_efficiency_score' => 0,
  625. 'completion_rate' => 0,
  626. 'average_time' => 0,
  627. 'total_paths' => 0
  628. ];
  629. }
  630. $activePaths = 0;
  631. $completedPaths = 0;
  632. $efficiencyScores = [];
  633. foreach ($paths as $path) {
  634. if (($path['status'] ?? '') === 'active') {
  635. $activePaths++;
  636. }
  637. if (($path['status'] ?? '') === 'completed') {
  638. $completedPaths++;
  639. }
  640. if (isset($path['efficiency_score'])) {
  641. $efficiencyScores[] = $path['efficiency_score'];
  642. }
  643. }
  644. $averageEfficiency = !empty($efficiencyScores)
  645. ? array_sum($efficiencyScores) / count($efficiencyScores)
  646. : rand(60, 85) / 100;
  647. $completionRate = count($paths) > 0
  648. ? ($completedPaths / count($paths)) * 100
  649. : 0;
  650. $averageTime = rand(30, 60); // 模拟平均时间(分钟)
  651. return [
  652. 'active_paths' => $activePaths,
  653. 'completed_paths' => $completedPaths,
  654. 'average_efficiency_score' => $averageEfficiency,
  655. 'completion_rate' => $completionRate,
  656. 'average_time' => $averageTime,
  657. 'total_paths' => count($paths)
  658. ];
  659. } catch (\Exception $e) {
  660. Log::error('Get Learning Path Analytics Error', [
  661. 'student_id' => $studentId,
  662. 'error' => $e->getMessage()
  663. ]);
  664. return [
  665. 'active_paths' => 0,
  666. 'completed_paths' => 0,
  667. 'average_efficiency_score' => 0,
  668. 'completion_rate' => 0,
  669. 'average_time' => 0,
  670. 'total_paths' => 0
  671. ];
  672. }
  673. }
  674. /**
  675. * 快速分数预测
  676. */
  677. public function quickScorePrediction(string $studentId): array
  678. {
  679. Log::info('开始调用快速预测API', ['student_id' => $studentId]);
  680. $response = Http::timeout($this->timeout)
  681. ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction");
  682. Log::info('快速预测API响应', [
  683. 'student_id' => $studentId,
  684. 'status' => $response->status(),
  685. 'body' => $response->body()
  686. ]);
  687. if (!$response->successful()) {
  688. throw new \Exception(sprintf(
  689. '快速预测接口失败: %s %s',
  690. $response->status(),
  691. $response->body()
  692. ));
  693. }
  694. $data = $response->json();
  695. Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
  696. // API 返回结构:{ student_id, current_assumption, target_assumption, quick_prediction, prediction_id, message }
  697. $quickPredictionData = $data['quick_prediction'] ?? [];
  698. return [
  699. 'quick_prediction' => [
  700. 'current_score' => $quickPredictionData['current_score'] ?? $data['current_assumption'] ?? 0,
  701. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  702. 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? (($data['target_assumption'] ?? 0) - ($data['current_assumption'] ?? 0)),
  703. 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 0,
  704. 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0,
  705. 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
  706. 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
  707. 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
  708. 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
  709. ],
  710. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  711. 'confidence' => isset($quickPredictionData['confidence_level']) ? $quickPredictionData['confidence_level'] * 100 : 0,
  712. 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 0,
  713. 'prediction_id' => $data['prediction_id'] ?? null,
  714. 'message' => $data['message'] ?? null,
  715. ];
  716. }
  717. /**
  718. * 推荐学习路径(本地化)
  719. */
  720. public function recommendLearningPaths(string $studentId, int $count = 3): array
  721. {
  722. try {
  723. Log::info('LearningAnalyticsService: 推荐学习路径 (本地)', [
  724. 'student_id' => $studentId,
  725. ]);
  726. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  727. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  728. $recommendations = [];
  729. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  730. $kpCode = is_object($weak) ? $weak->kp_code : ($weak['kp_code'] ?? '');
  731. $masteryLevel = is_object($weak) ? $weak->mastery_level : ($weak['mastery_level'] ?? 0);
  732. $recommendations[] = [
  733. 'kp_code' => $kpCode,
  734. 'kp_name' => $this->getKnowledgePointName($kpCode),
  735. 'current_mastery' => $masteryLevel,
  736. 'target_mastery' => 0.85,
  737. 'priority' => 1 - $masteryLevel,
  738. 'recommended_practice_count' => max(3, intval((0.85 - $masteryLevel) * 10)),
  739. 'estimated_time_minutes' => max(15, intval((0.85 - $masteryLevel) * 60)),
  740. ];
  741. }
  742. return [
  743. 'recommendations' => $recommendations
  744. ];
  745. } catch (\Exception $e) {
  746. Log::error('Recommend Learning Paths Error', [
  747. 'student_id' => $studentId,
  748. 'error' => $e->getMessage()
  749. ]);
  750. return [
  751. 'recommendations' => []
  752. ];
  753. }
  754. }
  755. /**
  756. * 获取知识点名称
  757. */
  758. private function getKnowledgePointName(string $kpCode): string
  759. {
  760. try {
  761. $kp = DB::table('knowledge_points')
  762. ->where('kp_code', $kpCode)
  763. ->value('name');
  764. return $kp ?? $kpCode;
  765. } catch (\Exception $e) {
  766. return $kpCode;
  767. }
  768. }
  769. /**
  770. * 重新计算掌握度(本地化)
  771. */
  772. public function recalculateMastery(string $studentId, string $kpCode): bool
  773. {
  774. try {
  775. Log::info('LearningAnalyticsService: 重新计算掌握度 (本地)', [
  776. 'student_id' => $studentId,
  777. 'kp_code' => $kpCode,
  778. ]);
  779. // 使用MasteryCalculator重新计算
  780. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  781. // 更新到数据库
  782. DB::table('student_knowledge_mastery')
  783. ->updateOrInsert(
  784. ['student_id' => $studentId, 'kp_code' => $kpCode],
  785. [
  786. 'mastery_level' => $result['mastery'],
  787. 'confidence_level' => $result['confidence'],
  788. 'total_attempts' => $result['total_attempts'],
  789. 'correct_attempts' => $result['correct_attempts'],
  790. 'mastery_trend' => $result['trend'],
  791. 'last_mastery_update' => now(),
  792. 'updated_at' => now(),
  793. ]
  794. );
  795. return true;
  796. } catch (\Exception $e) {
  797. Log::error('Recalculate Mastery Error', [
  798. 'student_id' => $studentId,
  799. 'kp_code' => $kpCode,
  800. 'error' => $e->getMessage()
  801. ]);
  802. return false;
  803. }
  804. }
  805. /**
  806. * 批量更新技能熟练度(本地化)
  807. */
  808. public function batchUpdateSkillProficiency(string $studentId): bool
  809. {
  810. try {
  811. Log::info('LearningAnalyticsService: 批量更新技能熟练度 (本地)', [
  812. 'student_id' => $studentId,
  813. ]);
  814. // 获取学生所有知识点
  815. $kpCodes = DB::table('student_knowledge_mastery')
  816. ->where('student_id', $studentId)
  817. ->pluck('kp_code')
  818. ->toArray();
  819. // 批量更新
  820. $this->masteryCalculator->batchUpdateMastery($studentId, $kpCodes);
  821. return true;
  822. } catch (\Exception $e) {
  823. Log::error('Batch Update Skill Proficiency Error', [
  824. 'student_id' => $studentId,
  825. 'error' => $e->getMessage()
  826. ]);
  827. return false;
  828. }
  829. }
  830. /**
  831. * 清空学生所有答题数据(本地化)
  832. */
  833. public function clearStudentData(string $studentId): bool
  834. {
  835. try {
  836. Log::info('LearningAnalyticsService: 清空学生数据 (本地)', [
  837. 'student_id' => $studentId,
  838. ]);
  839. // 清空MySQL中的数据
  840. $this->clearStudentMySQLData($studentId);
  841. Log::info('Student Data Cleared Successfully', [
  842. 'student_id' => $studentId,
  843. ]);
  844. return true;
  845. } catch (\Exception $e) {
  846. Log::error('Clear Student Data Error', [
  847. 'student_id' => $studentId,
  848. 'error' => $e->getMessage()
  849. ]);
  850. return false;
  851. }
  852. }
  853. /**
  854. * 清空学生MySQL中的答题数据
  855. */
  856. private function clearStudentMySQLData(string $studentId): void
  857. {
  858. try {
  859. // 清空student_exercises表
  860. DB::table('student_exercises')
  861. ->where('student_id', $studentId)
  862. ->delete();
  863. // 清空student_mastery表
  864. DB::table('student_mastery')
  865. ->where('student_id', $studentId)
  866. ->delete();
  867. Log::info('Student MySQL Data Cleared', [
  868. 'student_id' => $studentId
  869. ]);
  870. } catch (\Exception $e) {
  871. Log::error('Clear Student MySQL Data Error', [
  872. 'student_id' => $studentId,
  873. 'error' => $e->getMessage()
  874. ]);
  875. throw $e; // 重新抛出异常,让上层处理
  876. }
  877. }
  878. /**
  879. * 获取学生列表(供智能出卷使用)
  880. */
  881. public function getStudentsList(): array
  882. {
  883. try {
  884. $response = Http::timeout($this->timeout)
  885. ->get($this->baseUrl . '/api/v1/students/list');
  886. if ($response->successful()) {
  887. return $response->json('data', []);
  888. }
  889. // 如果API失败,尝试从MySQL直接读取
  890. return $this->getStudentsFromMySQL();
  891. } catch (\Exception $e) {
  892. Log::error('Get Students List Error', [
  893. 'error' => $e->getMessage()
  894. ]);
  895. // 返回模拟数据
  896. return [
  897. ['student_id' => 'stu_001', 'name' => '张三'],
  898. ['student_id' => 'stu_002', 'name' => '李四'],
  899. ['student_id' => 'stu_003', 'name' => '王五'],
  900. ];
  901. }
  902. }
  903. /**
  904. * 从MySQL获取学生列表
  905. */
  906. private function getStudentsFromMySQL(): array
  907. {
  908. try {
  909. return DB::table('students')
  910. ->select('student_id', 'name')
  911. ->limit(100)
  912. ->get()
  913. ->toArray();
  914. } catch (\Exception $e) {
  915. Log::error('Get Students From MySQL Error', [
  916. 'error' => $e->getMessage()
  917. ]);
  918. return [];
  919. }
  920. }
  921. /**
  922. * 获取学生薄弱点列表
  923. * 策略:MySQL作为权威数据源,LearningAnalytics API仅作为辅助/缓存
  924. */
  925. public function getStudentWeaknesses(string $studentId, int $limit = 10): array
  926. {
  927. try {
  928. // 从本地MySQL数据库获取学生薄弱点
  929. Log::info('从本地MySQL数据库获取学生薄弱点', [
  930. 'student_id' => $studentId,
  931. 'limit' => $limit
  932. ]);
  933. $weaknesses = $this->getStudentWeaknessesFromMySQL($studentId, $limit);
  934. if (!empty($weaknesses)) {
  935. Log::info('从本地数据库获取到薄弱点数据', [
  936. 'student_id' => $studentId,
  937. 'count' => count($weaknesses)
  938. ]);
  939. return $weaknesses;
  940. }
  941. Log::warning('本地数据库中无该学生薄弱点数据', [
  942. 'student_id' => $studentId
  943. ]);
  944. return [];
  945. } catch (\Exception $e) {
  946. Log::error('Get Student Weaknesses Error', [
  947. 'student_id' => $studentId,
  948. 'error' => $e->getMessage()
  949. ]);
  950. // 发生异常时,返回空数组
  951. return [];
  952. }
  953. }
  954. /**
  955. * 从MySQL获取学生薄弱点
  956. */
  957. private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
  958. {
  959. try {
  960. // 优先从 student_knowledge_mastery 表读取(更完整的掌握度数据)
  961. $weaknesses = DB::table('student_knowledge_mastery as skm')
  962. ->where('skm.student_id', $studentId)
  963. ->where('skm.mastery_level', '<', 0.7) // 掌握度低于70%视为薄弱点
  964. ->orderBy('skm.mastery_level', 'asc')
  965. ->limit($limit)
  966. ->select([
  967. 'skm.kp_code',
  968. 'skm.mastery_level',
  969. 'skm.total_attempts',
  970. 'skm.correct_attempts',
  971. 'skm.incorrect_attempts',
  972. 'skm.confidence_level',
  973. 'skm.mastery_trend'
  974. ])
  975. ->get()
  976. ->toArray();
  977. // 如果student_knowledge_mastery表没有数据,尝试从student_mastery表读取
  978. if (empty($weaknesses)) {
  979. Log::info('student_knowledge_mastery表无数据,尝试从student_mastery表读取', [
  980. 'student_id' => $studentId
  981. ]);
  982. $weaknesses = DB::table('student_mastery as sm')
  983. ->leftJoin('knowledge_points as kp', 'sm.kp', '=', 'kp.kp_code')
  984. ->where('sm.student_id', $studentId)
  985. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  986. ->orderBy('sm.mastery', 'asc')
  987. ->limit($limit)
  988. ->select([
  989. 'sm.kp as kp_code',
  990. 'kp.name as kp_name',
  991. 'sm.mastery',
  992. 'sm.attempts',
  993. 'sm.correct'
  994. ])
  995. ->get()
  996. ->toArray();
  997. // 转换为统一格式
  998. return array_map(function ($item) {
  999. $mastery = (float) ($item->mastery ?? 0);
  1000. $attempts = (int) ($item->attempts ?? 0);
  1001. $correct = (int) ($item->correct ?? 0);
  1002. return [
  1003. 'kp_code' => $item->kp_code,
  1004. 'kp_name' => $item->kp_name ?? $item->kp_code,
  1005. 'mastery' => $mastery,
  1006. 'stability' => 0.5, // 默认稳定性
  1007. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1008. 'practice_count' => $attempts,
  1009. 'success_rate' => $attempts > 0 ? ($correct / $attempts) : 0,
  1010. 'priority' => $mastery < 0.3 ? '高' : ($mastery < 0.5 ? '中' : '低'),
  1011. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)) // 掌握度越低,建议题目越多
  1012. ];
  1013. }, $weaknesses);
  1014. }
  1015. // 转换student_knowledge_mastery表的数据格式
  1016. return array_map(function ($item) {
  1017. $mastery = (float) ($item->mastery_level ?? 0);
  1018. $totalAttempts = (int) ($item->total_attempts ?? 0);
  1019. $correctAttempts = (int) ($item->correct_attempts ?? 0);
  1020. $incorrectAttempts = (int) ($item->incorrect_attempts ?? 0);
  1021. $confidence = (float) ($item->confidence_level ?? 0.5);
  1022. $trend = $item->mastery_trend ?? 'stable';
  1023. // 计算成功率
  1024. $successRate = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : 0;
  1025. // 确定优先级
  1026. $priority = '中';
  1027. if ($mastery < 0.3) {
  1028. $priority = '高';
  1029. } elseif ($mastery < 0.5) {
  1030. $priority = '中';
  1031. } else {
  1032. $priority = '低';
  1033. }
  1034. return [
  1035. 'kp_code' => $item->kp_code,
  1036. 'kp_name' => $item->kp_code, // 如果没有中文名,使用代码作为名称
  1037. 'mastery' => $mastery,
  1038. 'stability' => $confidence,
  1039. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1040. 'practice_count' => $totalAttempts,
  1041. 'success_rate' => $successRate,
  1042. 'priority' => $priority,
  1043. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)), // 掌握度越低,建议题目越多
  1044. 'trend' => $trend,
  1045. 'correct_attempts' => $correctAttempts,
  1046. 'incorrect_attempts' => $incorrectAttempts
  1047. ];
  1048. }, $weaknesses);
  1049. } catch (\Exception $e) {
  1050. Log::error('Get Student Weaknesses From MySQL Error', [
  1051. 'student_id' => $studentId,
  1052. 'error' => $e->getMessage(),
  1053. 'trace' => $e->getTraceAsString()
  1054. ]);
  1055. return [];
  1056. }
  1057. }
  1058. /**
  1059. * 智能出卷:根据学生掌握度智能选择题目
  1060. */
  1061. public function generateIntelligentExam(array $params): array
  1062. {
  1063. $startTime = microtime(true);
  1064. try {
  1065. // 应用组卷类型策略
  1066. $assembleType = (int) ($params['assemble_type'] ?? 4); // 默认为通用类型(4)
  1067. $examTypeLegacy = $params['exam_type'] ?? 'general'; // 兼容旧版参数
  1068. Log::info('LearningAnalyticsService: 检查组卷策略', [
  1069. 'assemble_type' => $assembleType,
  1070. 'exam_type_legacy' => $examTypeLegacy,
  1071. 'has_question_expansion_service' => !empty($this->questionExpansionService)
  1072. ]);
  1073. // 如果有 assemble_type 参数,优先使用新的参数系统
  1074. if (isset($params['assemble_type'])) {
  1075. try {
  1076. // 确保QuestionExpansionService和QuestionLocalService可用
  1077. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1078. $questionLocalService = app(QuestionLocalService::class);
  1079. Log::info('LearningAnalyticsService: 从容器获取服务实例');
  1080. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1081. $params = $strategy->buildParams($params, $assembleType);
  1082. Log::info('LearningAnalyticsService: 已应用组卷策略', [
  1083. 'assemble_type' => $assembleType,
  1084. 'enhanced_params_keys' => array_keys($params)
  1085. ]);
  1086. } catch (Exception $e) {
  1087. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1088. 'assemble_type' => $assembleType,
  1089. 'error' => $e->getMessage(),
  1090. 'trace' => $e->getTraceAsString()
  1091. ]);
  1092. }
  1093. } elseif ($examTypeLegacy !== 'general') {
  1094. // 兼容旧版 exam_type 参数
  1095. try {
  1096. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1097. $questionLocalService = app(QuestionLocalService::class);
  1098. Log::info('LearningAnalyticsService: 从容器获取服务实例(兼容模式)');
  1099. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1100. $params = $strategy->buildParamsLegacy($params, $examTypeLegacy);
  1101. Log::info('LearningAnalyticsService: 已应用组卷策略(兼容模式)', [
  1102. 'exam_type' => $examTypeLegacy,
  1103. 'enhanced_params_keys' => array_keys($params)
  1104. ]);
  1105. } catch (Exception $e) {
  1106. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1107. 'exam_type' => $examTypeLegacy,
  1108. 'error' => $e->getMessage(),
  1109. 'trace' => $e->getTraceAsString()
  1110. ]);
  1111. }
  1112. } else {
  1113. Log::info('LearningAnalyticsService: 跳过组卷策略', [
  1114. 'reason' => '通用类型不需要特殊策略'
  1115. ]);
  1116. }
  1117. $studentId = $params['student_id'] ?? null;
  1118. $grade = $params['grade'] ?? null; // 用户选择的年级
  1119. $totalQuestions = $params['total_questions'] ?? 20;
  1120. // 【修复】参数映射:支持 kp_codes 和 kp_code_list 两种参数名
  1121. $kpCodes = $params['kp_codes'] ?? $params['kp_code_list'] ?? [];
  1122. if (!is_array($kpCodes)) {
  1123. $kpCodes = [];
  1124. }
  1125. $skills = $params['skills'] ?? [];
  1126. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1127. '选择题' => 40,
  1128. '填空题' => 30,
  1129. '解答题' => 30,
  1130. ];
  1131. // 新增:题目分类筛选
  1132. $questionCategory = $params['question_category'] ?? null;
  1133. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  1134. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1135. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1136. Log::info("generateIntelligentExam 开始", [
  1137. 'student_id' => $studentId,
  1138. 'total_questions' => $totalQuestions,
  1139. 'kp_codes' => $kpCodes,
  1140. 'skills' => $skills,
  1141. 'assemble_type' => $assembleType,
  1142. 'exam_type_legacy' => $examTypeLegacy,
  1143. 'question_category' => $questionCategory,
  1144. ]);
  1145. // 1. 如果指定了学生,获取学生的薄弱点
  1146. $weaknessFilter = [];
  1147. if ($studentId) {
  1148. Log::info("获取学生薄弱点: $studentId");
  1149. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1150. Log::info("薄弱点数量: " . count($weaknesses), [
  1151. '薄弱点' => $weaknesses,
  1152. ]);
  1153. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1154. // 如果用户没有指定知识点,使用学生的薄弱点
  1155. if (empty($kpCodes)) {
  1156. $kpCodes = $weaknessFilter;
  1157. Log::info("用户未选择知识点,使用薄弱点作为kp_codes", [
  1158. '最终kp_codes' => $kpCodes,
  1159. ]);
  1160. }
  1161. // 【修复】教材出卷(assemble_type=3)不使用薄弱点,只按章节筛选
  1162. if ($assembleType == 3) {
  1163. $kpCodes = [];
  1164. Log::info("LearningAnalyticsService: 教材出卷不使用薄弱点,清空知识点", [
  1165. 'assemble_type' => $assembleType,
  1166. 'chapter_ids' => $params['chapter_id_list'] ?? [],
  1167. ]);
  1168. }
  1169. }
  1170. Log::info("准备调用 getQuestionsFromBank", [
  1171. 'kp_codes' => $kpCodes,
  1172. 'skills' => $skills,
  1173. ]);
  1174. // 2. 优先使用学生错题(如果存在)
  1175. $mistakeQuestionIds = $params['mistake_question_ids'] ?? [];
  1176. $priorityQuestions = [];
  1177. $maxQuestions = 50; // 全局最大题目数限制
  1178. if (!empty($mistakeQuestionIds)) {
  1179. Log::info('LearningAnalyticsService: 优先获取学生错题', [
  1180. 'mistake_question_ids' => $mistakeQuestionIds,
  1181. 'count' => count($mistakeQuestionIds),
  1182. 'max_limit' => $maxQuestions
  1183. ]);
  1184. // 如果错题超过最大值,截取到最大值
  1185. $truncatedMistakeIds = $mistakeQuestionIds;
  1186. if (count($mistakeQuestionIds) > $maxQuestions) {
  1187. Log::warning('LearningAnalyticsService: 错题数量超过最大值限制,已截取', [
  1188. 'mistake_count' => count($mistakeQuestionIds),
  1189. 'max_limit' => $maxQuestions,
  1190. 'truncated_count' => $maxQuestions
  1191. ]);
  1192. $truncatedMistakeIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  1193. }
  1194. // 获取学生错题的详细信息
  1195. $priorityQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $truncatedMistakeIds, [], null, null);
  1196. Log::info('LearningAnalyticsService: 错题获取完成', [
  1197. 'priority_questions_count' => count($priorityQuestions),
  1198. 'expected_count' => count($truncatedMistakeIds)
  1199. ]);
  1200. // 如果获取的错题数量少于预期,记录警告
  1201. if (count($priorityQuestions) < count($truncatedMistakeIds)) {
  1202. Log::warning('LearningAnalyticsService: 错题获取不完整', [
  1203. 'expected' => count($truncatedMistakeIds),
  1204. 'actual' => count($priorityQuestions),
  1205. 'missing_ids' => array_diff($truncatedMistakeIds, array_column($priorityQuestions, 'id'))
  1206. ]);
  1207. }
  1208. }
  1209. // 3. 处理错题本逻辑
  1210. $allQuestions = $priorityQuestions;
  1211. $isMistakeBook = ($assembleType === 5); // 错题本类型
  1212. // 如果是错题本类型,且有错题但数量不足,获取原卷子的所有题目
  1213. if ($isMistakeBook && !empty($priorityQuestions) && count($priorityQuestions) < 5 && !empty($params['paper_ids'])) {
  1214. Log::info('LearningAnalyticsService: 错题本错题不足,获取原卷子题目补充', [
  1215. 'mistake_count' => count($priorityQuestions),
  1216. 'paper_ids' => $params['paper_ids']
  1217. ]);
  1218. // 获取原卷子的所有题目
  1219. $paperQuestionIds = $this->getPaperAllQuestions($params['paper_ids']);
  1220. if (!empty($paperQuestionIds)) {
  1221. Log::info('LearningAnalyticsService: 获取原卷子题目', [
  1222. 'paper_question_count' => count($paperQuestionIds)
  1223. ]);
  1224. // 使用原卷子题目补充到目标数量
  1225. $additionalNeeded = max(5, count($priorityQuestions)) - count($priorityQuestions);
  1226. $paperQuestionIds = array_diff($paperQuestionIds, array_column($priorityQuestions, 'id'));
  1227. $additionalPaperQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $additionalNeeded, $paperQuestionIds, [], null, null);
  1228. $allQuestions = array_merge($priorityQuestions, $additionalPaperQuestions);
  1229. Log::info('LearningAnalyticsService: 错题本题目补充完成', [
  1230. 'final_count' => count($allQuestions)
  1231. ]);
  1232. }
  1233. }
  1234. // 如果是错题本类型,但完全没有错题,使用原卷子的所有题目
  1235. if ($isMistakeBook && empty($priorityQuestions) && !empty($params['paper_ids'])) {
  1236. Log::info('LearningAnalyticsService: 错题本无错题,使用原卷子题目', [
  1237. 'paper_ids' => $params['paper_ids']
  1238. ]);
  1239. // 获取原卷子的所有题目
  1240. $paperQuestionIds = $this->getPaperAllQuestions($params['paper_ids']);
  1241. if (!empty($paperQuestionIds)) {
  1242. $allQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $paperQuestionIds, [], null, null);
  1243. // 检查是否获取到题目
  1244. if (empty($allQuestions)) {
  1245. Log::warning('LearningAnalyticsService: 错题本无法获取任何题目', [
  1246. 'paper_ids' => $params['paper_ids'],
  1247. 'paper_question_ids' => $paperQuestionIds,
  1248. 'reason' => '原卷子题目在题库中不存在或已删除'
  1249. ]);
  1250. throw new \Exception('抱歉,您选择的卷子中的题目在题库中不存在或已被删除,无法生成错题本。请选择其他卷子或联系管理员更新题库。');
  1251. }
  1252. Log::info('LearningAnalyticsService: 错题本使用原卷子题目', [
  1253. 'question_count' => count($allQuestions)
  1254. ]);
  1255. } else {
  1256. throw new \Exception('抱歉,指定的卷子中没有找到题目,无法生成错题本。');
  1257. }
  1258. }
  1259. // 错题本类型但既无错题又无卷子题目
  1260. if ($isMistakeBook && empty($priorityQuestions) && empty($allQuestions)) {
  1261. Log::warning('LearningAnalyticsService: 错题本既无错题又无卷子题目', [
  1262. 'student_id' => $studentId,
  1263. 'paper_ids' => $params['paper_ids'] ?? []
  1264. ]);
  1265. throw new \Exception('抱歉,您在这个卷子中没有错题记录,且卷子题目无法获取,无法生成错题本。请确认卷子ID是否正确或联系管理员。');
  1266. }
  1267. if (!$isMistakeBook && count($priorityQuestions) < $totalQuestions) {
  1268. try {
  1269. // 【修复】教材出卷(assemble_type=3)只按章节筛选,不按知识点筛选
  1270. if ($assembleType == 3) {
  1271. $kpCodes = [];
  1272. Log::info('LearningAnalyticsService: 教材出卷模式,清空知识点筛选', [
  1273. 'assemble_type' => $assembleType,
  1274. 'chapter_ids' => $params['chapter_id_list'] ?? [],
  1275. ]);
  1276. }
  1277. Log::info('开始调用 getQuestionsFromBank 补充题目', [
  1278. 'kp_codes_count' => count($kpCodes),
  1279. 'skills_count' => count($skills),
  1280. 'has_mistake_priority' => !empty($mistakeQuestionIds),
  1281. 'need_more' => $totalQuestions - count($priorityQuestions),
  1282. 'assemble_type' => $assembleType
  1283. ]);
  1284. // 【优化】获取textbook_catalog_node_ids参数(教材组卷时使用)
  1285. $textbookCatalogNodeIds = $params['textbook_catalog_node_ids'] ?? null;
  1286. $additionalQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId, $questionTypeRatio, $maxQuestions, [], [], $questionCategory, $textbookCatalogNodeIds);
  1287. $allQuestions = array_merge($priorityQuestions, $additionalQuestions);
  1288. Log::info('getQuestionsFromBank 调用完成', [
  1289. 'questions_count' => count($allQuestions),
  1290. 'is_array' => is_array($allQuestions),
  1291. 'first_question_id' => !empty($allQuestions) ? ($allQuestions[0]['id'] ?? 'N/A') : 'N/A',
  1292. '耗时' => round((microtime(true) - $startTime) * 1000, 2) . 'ms',
  1293. ]);
  1294. Log::info('getQuestionsFromBank 返回', [
  1295. 'questions_count' => count($allQuestions),
  1296. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1297. ]);
  1298. } catch (\Exception $e) {
  1299. Log::error('getQuestionsFromBank 调用失败', [
  1300. 'error' => $e->getMessage(),
  1301. 'trace' => $e->getTraceAsString()
  1302. ]);
  1303. throw $e;
  1304. }
  1305. } elseif ($isMistakeBook) {
  1306. // 错题本类型:不补充题目,只使用错题
  1307. Log::info('错题本类型:不补充题目,只使用错题', [
  1308. 'assemble_type' => $assembleType,
  1309. 'mistake_questions_count' => count($priorityQuestions),
  1310. 'total_questions_requested' => $totalQuestions
  1311. ]);
  1312. }
  1313. if (empty($allQuestions)) {
  1314. // 如果指定了知识点但题库为空,给出明确提示
  1315. if (!empty($kpCodes)) {
  1316. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1317. } else {
  1318. // 没有选择知识点时,从所有题目中选择
  1319. // 如果仍然没有题目,说明题库为空,提示补充题库
  1320. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1321. }
  1322. Log::warning('智能出卷失败 - 未找到题目', [
  1323. 'student_id' => $studentId,
  1324. 'selected_kp_codes' => $kpCodes,
  1325. 'kp_codes_count' => count($kpCodes),
  1326. 'message' => $message,
  1327. 'hint' => '如果选择了知识点但题库为空,请检查知识点代码是否正确,或尝试取消知识点选择'
  1328. ]);
  1329. return [
  1330. 'success' => false,
  1331. 'message' => $message,
  1332. 'questions' => []
  1333. ];
  1334. }
  1335. // 3. 根据掌握度对题目进行筛选和排序
  1336. // 错题本类型:使用所有错题,但不超过最大值限制
  1337. $targetQuestionCount = $isMistakeBook ? min(count($allQuestions), $maxQuestions) : $totalQuestions;
  1338. Log::info('开始调用 selectQuestionsByMastery', [
  1339. 'input_count' => count($allQuestions),
  1340. 'target_count' => $targetQuestionCount,
  1341. 'is_mistake_book' => $isMistakeBook,
  1342. 'assemble_type' => $assembleType,
  1343. 'total_questions_param' => $totalQuestions
  1344. ]);
  1345. $startTime = microtime(true);
  1346. $selectedQuestions = $this->selectQuestionsByMastery(
  1347. $allQuestions,
  1348. $studentId,
  1349. $targetQuestionCount,
  1350. $questionTypeRatio,
  1351. $difficultyLevels,
  1352. $weaknessFilter,
  1353. $assembleType // 新增assembleType参数
  1354. );
  1355. $selectTime = (microtime(true) - $startTime) * 1000;
  1356. Log::info('题目筛选结果', [
  1357. 'input_count' => count($allQuestions),
  1358. 'selected_count' => count($selectedQuestions),
  1359. 'target_count' => $targetQuestionCount,
  1360. 'is_mistake_book' => $isMistakeBook,
  1361. 'select_time_ms' => round($selectTime, 2)
  1362. ]);
  1363. if (empty($selectedQuestions)) {
  1364. return [
  1365. 'success' => false,
  1366. 'message' => '题目筛选失败',
  1367. 'questions' => []
  1368. ];
  1369. }
  1370. // 【恢复】简化难度分布检查
  1371. $difficultyCategory = $params['difficulty_category'] ?? 1;
  1372. $enableDistribution = $params['enable_difficulty_distribution'] ?? false;
  1373. $isExcludedType = ($assembleType === 5); // 只有错题本类型(assembleType=5)不应用难度分布
  1374. // 【重要】添加详细的difficulty_category追踪日志
  1375. Log::info('LearningAnalyticsService: 难度分布检查开始', [
  1376. 'input_difficulty_category' => $difficultyCategory,
  1377. 'assemble_type' => $assembleType,
  1378. 'enable_distribution' => $enableDistribution,
  1379. 'is_excluded_type' => $isExcludedType,
  1380. 'selected_questions_before' => count($selectedQuestions),
  1381. 'params_keys' => array_keys($params)
  1382. ]);
  1383. if ($enableDistribution && !$isExcludedType) {
  1384. Log::info('LearningAnalyticsService: 应用难度系数分布', [
  1385. 'difficulty_category_before' => $difficultyCategory,
  1386. 'assemble_type' => $assembleType,
  1387. 'before_count' => count($selectedQuestions)
  1388. ]);
  1389. try {
  1390. // 使用 ExamTypeStrategy 的独立方法应用难度分布
  1391. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1392. $examStrategy = new ExamTypeStrategy($questionExpansionService);
  1393. $selectedQuestions = $examStrategy->applyDifficultyDistributionToQuestions(
  1394. $selectedQuestions,
  1395. $totalQuestions,
  1396. $difficultyCategory,
  1397. $params
  1398. );
  1399. Log::info('LearningAnalyticsService: 难度分布应用完成', [
  1400. 'difficulty_category_after' => $difficultyCategory,
  1401. 'after_count' => count($selectedQuestions)
  1402. ]);
  1403. } catch (\Exception $e) {
  1404. Log::warning('LearningAnalyticsService: 难度分布应用失败,继续使用原结果', [
  1405. 'error' => $e->getMessage(),
  1406. 'difficulty_category_when_error' => $difficultyCategory
  1407. ]);
  1408. }
  1409. }
  1410. return [
  1411. 'success' => true,
  1412. 'message' => '智能出卷成功',
  1413. 'questions' => $selectedQuestions,
  1414. 'stats' => [
  1415. 'total_selected' => count($selectedQuestions),
  1416. 'source_questions' => count($allQuestions),
  1417. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1418. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1419. })) : 0,
  1420. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1421. 'difficulty_category' => $difficultyCategory,
  1422. // 【新增】章节知识点数量统计(教材组卷时)
  1423. 'chapter_knowledge_point_stats' => $params['chapter_knowledge_point_stats'] ?? null,
  1424. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? null
  1425. ]
  1426. ];
  1427. } catch (\Exception $e) {
  1428. Log::error('Generate Intelligent Exam Error', [
  1429. 'error' => $e->getMessage(),
  1430. 'trace' => $e->getTraceAsString()
  1431. ]);
  1432. return [
  1433. 'success' => false,
  1434. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1435. 'questions' => []
  1436. ];
  1437. }
  1438. }
  1439. /**
  1440. * 从本地题库获取题目(错题回顾优先)
  1441. * 支持优先获取指定题目ID的题目
  1442. * 【优化】新增textbookCatalogNodeIds参数,支持按textbook_catalog_node_id筛选题目
  1443. */
  1444. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], int $totalNeeded = 100, array $priorityQuestionIds = [], array $excludeQuestionIds = [], ?int $questionCategory = null, ?array $textbookCatalogNodeIds = null): array
  1445. {
  1446. $startTime = microtime(true);
  1447. try {
  1448. // 错题回顾:优先获取指定的学生错题
  1449. if (!empty($priorityQuestionIds)) {
  1450. Log::info('getQuestionsFromBank: 优先获取学生错题', [
  1451. 'priority_count' => count($priorityQuestionIds),
  1452. 'priority_ids' => $priorityQuestionIds
  1453. ]);
  1454. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1455. if (!empty($priorityQuestions)) {
  1456. Log::info('getQuestionsFromBank: 优先错题获取成功', [
  1457. 'count' => count($priorityQuestions)
  1458. ]);
  1459. return $priorityQuestions;
  1460. } else {
  1461. Log::warning('getQuestionsFromBank: 优先错题获取失败,返回空数组让上层处理');
  1462. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1463. return [];
  1464. }
  1465. }
  1466. // 从本地数据库查询题目
  1467. Log::info('getQuestionsFromBank: 从本地数据库查询题目', [
  1468. 'kp_codes' => $kpCodes,
  1469. 'skills' => $skills,
  1470. 'total_needed' => $totalNeeded,
  1471. 'question_type_ratio' => $questionTypeRatio,
  1472. 'note' => '难度筛选由 QuestionLocalService 处理'
  1473. ]);
  1474. $query = \App\Models\Question::query();
  1475. // 按知识点筛选
  1476. if (!empty($kpCodes)) {
  1477. $query->whereIn('kp_code', $kpCodes);
  1478. Log::info('应用知识点筛选', ['kp_codes' => $kpCodes]);
  1479. }
  1480. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1481. if (!empty($skills)) {
  1482. $query->where(function ($q) use ($skills) {
  1483. foreach ($skills as $skill) {
  1484. $q->orWhere('tags', 'like', "%{$skill}%");
  1485. }
  1486. });
  1487. Log::info('应用技能筛选', ['skills' => $skills]);
  1488. }
  1489. // 排除学生已做过的题目
  1490. if (!empty($excludeQuestionIds)) {
  1491. $query->whereNotIn('id', $excludeQuestionIds);
  1492. Log::info('应用排除筛选', ['exclude_count' => count($excludeQuestionIds)]);
  1493. }
  1494. // 按题目分类筛选(如果指定了 question_category)
  1495. if ($questionCategory !== null) {
  1496. $query->where('question_category', $questionCategory);
  1497. Log::info('应用题目分类筛选', ['question_category' => $questionCategory]);
  1498. }
  1499. // 【优化】按教材章节节点筛选(textbook_catalog_nodes_id)
  1500. if (!empty($textbookCatalogNodeIds)) {
  1501. $query->whereIn('textbook_catalog_nodes_id', $textbookCatalogNodeIds);
  1502. Log::info('应用教材章节节点筛选', ['textbook_catalog_nodes_ids' => $textbookCatalogNodeIds]);
  1503. }
  1504. // 筛选有解题思路的题目
  1505. $query->whereNotNull('solution')
  1506. ->where('solution', '!=', '')
  1507. ->where('solution', '!=', '[]');
  1508. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1509. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1510. // 【重要】移除数量限制,获取所有符合条件的题目
  1511. // 不使用limit()限制查询结果,让后续处理逻辑决定最终数量
  1512. $query->inRandomOrder();
  1513. $questions = $query->get();
  1514. Log::info('getQuestionsFromBank: 查询完成', [
  1515. 'raw_count' => $questions->count(),
  1516. 'total_needed' => $totalNeeded,
  1517. 'note' => '移除limit限制,获取所有符合条件的题目',
  1518. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1519. ]);
  1520. // 【重要】添加更详细的日志来追踪题目筛选过程
  1521. Log::info('getQuestionsFromBank: 题目筛选过程详情', [
  1522. 'database_query_count' => $questions->count(),
  1523. 'kp_codes_filter' => $kpCodes,
  1524. 'skills_filter' => $skills,
  1525. 'exclude_count' => count($excludeQuestionIds),
  1526. 'question_category' => $questionCategory,
  1527. 'textbook_catalog_node_ids_filter' => $textbookCatalogNodeIds,
  1528. 'note' => '将返回所有符合条件的题目,不限制数量'
  1529. ]);
  1530. // 转换为标准格式
  1531. $formattedQuestions = $questions->map(function ($q) {
  1532. return [
  1533. 'id' => $q->id,
  1534. 'question_code' => $q->question_code,
  1535. 'kp_code' => $q->kp_code,
  1536. 'question_type' => $q->question_type,
  1537. 'difficulty' => (float) $q->difficulty,
  1538. 'stem' => $q->stem,
  1539. 'solution' => $q->solution,
  1540. 'metadata' => [
  1541. 'has_solution' => true,
  1542. 'is_choice' => $q->question_type === 'choice',
  1543. 'is_fill' => $q->question_type === 'fill',
  1544. 'is_answer' => $q->question_type === 'answer',
  1545. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty),
  1546. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1547. ]
  1548. ];
  1549. })->toArray();
  1550. // 【重要】返回所有符合条件的题目,不限制数量
  1551. // 让上层调用者根据需要选择题目数量
  1552. $selectedQuestions = $formattedQuestions;
  1553. Log::info('getQuestionsFromBank 完成', [
  1554. 'final_count' => count($selectedQuestions),
  1555. 'raw_database_count' => $questions->count(),
  1556. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1557. ]);
  1558. return $selectedQuestions;
  1559. } catch (\Exception $e) {
  1560. Log::error('getQuestionsFromBank 查询失败', [
  1561. 'error' => $e->getMessage(),
  1562. 'trace' => $e->getTraceAsString()
  1563. ]);
  1564. throw $e;
  1565. }
  1566. }
  1567. /**
  1568. * 获取指定ID的题目详情
  1569. */
  1570. private function getLocalQuestionsByIds(array $questionIds): array
  1571. {
  1572. try {
  1573. // 通过QuestionBankService获取题目详情
  1574. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1575. // 批量获取题目详情
  1576. $response = $questionBankService->getQuestionsByIds($questionIds);
  1577. if (empty($response['data'])) {
  1578. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1579. 'requested_ids' => $questionIds
  1580. ]);
  1581. return [];
  1582. }
  1583. $questions = $response['data'];
  1584. // 转换为标准格式
  1585. $result = array_map(function ($q) {
  1586. $difficulty = $q['difficulty'] ?? 0.5;
  1587. return [
  1588. 'id' => $q['id'],
  1589. 'question_code' => $q['question_code'] ?? '',
  1590. 'kp_code' => $q['kp_code'] ?? '',
  1591. 'question_type' => $q['question_type'] ?? 'choice',
  1592. 'difficulty' => (float) $difficulty,
  1593. 'stem' => $q['stem'] ?? '',
  1594. 'solution' => $q['solution'] ?? '',
  1595. 'answer' => $q['answer'] ?? '',
  1596. 'metadata' => [
  1597. 'has_solution' => !empty($q['solution']),
  1598. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1599. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1600. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1601. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1602. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1603. ]
  1604. ];
  1605. }, $questions);
  1606. Log::info('getLocalQuestionsByIds 获取成功', [
  1607. 'requested_count' => count($questionIds),
  1608. 'found_count' => count($result),
  1609. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1610. 'question_ids' => array_slice($questionIds, 0, 20),
  1611. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1612. ]);
  1613. return $result;
  1614. } catch (\Exception $e) {
  1615. Log::error('getLocalQuestionsByIds 获取失败', [
  1616. 'question_ids' => $questionIds,
  1617. 'error' => $e->getMessage(),
  1618. 'trace' => $e->getTraceAsString()
  1619. ]);
  1620. return [];
  1621. }
  1622. }
  1623. /**
  1624. * 获取卷子的所有题目ID(不区分对错)
  1625. */
  1626. private function getPaperAllQuestions(array $paperIds): array
  1627. {
  1628. try {
  1629. // 查询 paper_questions 表获取所有题目ID
  1630. $questionIds = DB::table('paper_questions')
  1631. ->whereIn('paper_id', $paperIds)
  1632. ->pluck('question_bank_id')
  1633. ->unique()
  1634. ->filter()
  1635. ->values()
  1636. ->toArray();
  1637. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1638. 'paper_ids' => $paperIds,
  1639. 'question_count' => count($questionIds)
  1640. ]);
  1641. return $questionIds;
  1642. } catch (\Exception $e) {
  1643. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1644. 'paper_ids' => $paperIds,
  1645. 'error' => $e->getMessage()
  1646. ]);
  1647. return [];
  1648. }
  1649. }
  1650. /**
  1651. * 获取难度标签
  1652. */
  1653. private function getDifficultyLabel(float $difficulty): string
  1654. {
  1655. return match (true) {
  1656. $difficulty < 0.4 => '基础',
  1657. $difficulty < 0.7 => '中等',
  1658. default => '拔高'
  1659. };
  1660. }
  1661. /**
  1662. * 获取题型标签
  1663. */
  1664. private function getQuestionTypeLabel(string $questionType): string
  1665. {
  1666. return match ($questionType) {
  1667. 'choice' => '选择题',
  1668. 'fill' => '填空题',
  1669. 'answer' => '解答题',
  1670. default => '未知题型'
  1671. };
  1672. }
  1673. /**
  1674. * 根据题型配比选择题目
  1675. * 注意: 难度配比调整由 QuestionLocalService 处理
  1676. */
  1677. private function selectQuestionsByRatio(
  1678. array $questions,
  1679. int $totalNeeded,
  1680. array $questionTypeRatio = []
  1681. ): array {
  1682. if (empty($questions)) {
  1683. return [];
  1684. }
  1685. // 如果没有配比要求,直接返回
  1686. if (empty($questionTypeRatio)) {
  1687. return array_slice($questions, 0, $totalNeeded);
  1688. }
  1689. $selected = [];
  1690. $usedIndices = [];
  1691. // 按题型配比选择
  1692. if (!empty($questionTypeRatio)) {
  1693. foreach ($questionTypeRatio as $type => $ratio) {
  1694. $count = (int) round(($ratio / 100) * $totalNeeded);
  1695. if ($count <= 0) continue;
  1696. $typeQuestions = [];
  1697. foreach ($questions as $idx => $q) {
  1698. if (in_array($idx, $usedIndices)) continue;
  1699. $qType = $q['question_type'] ?? '';
  1700. $label = $this->getQuestionTypeLabel($qType);
  1701. if ($label === $type) {
  1702. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1703. }
  1704. }
  1705. // 随机选择
  1706. shuffle($typeQuestions);
  1707. $selectedCount = min($count, count($typeQuestions));
  1708. for ($i = 0; $i < $selectedCount; $i++) {
  1709. $selected[] = $typeQuestions[$i]['question'];
  1710. $usedIndices[] = $typeQuestions[$i]['idx'];
  1711. }
  1712. }
  1713. }
  1714. // 如果还有空缺,补充剩余题目
  1715. // 注意: 难度配比调整由 QuestionLocalService 处理
  1716. if (count($selected) < $totalNeeded) {
  1717. foreach ($questions as $idx => $q) {
  1718. if (count($selected) >= $totalNeeded) break;
  1719. if (!in_array($idx, $usedIndices)) {
  1720. $selected[] = $q;
  1721. $usedIndices[] = $idx;
  1722. }
  1723. }
  1724. }
  1725. return array_slice($selected, 0, $totalNeeded);
  1726. }
  1727. /**
  1728. * 根据学生掌握度筛选题目
  1729. */
  1730. private function selectQuestionsByMastery(
  1731. array $questions,
  1732. ?string $studentId,
  1733. int $totalQuestions,
  1734. array $questionTypeRatio,
  1735. array $difficultyLevels,
  1736. array $weaknessFilter,
  1737. int $assembleType // 新增assembleType参数
  1738. ): array {
  1739. Log::info('selectQuestionsByMastery 开始', [
  1740. 'question_count' => count($questions),
  1741. 'student_id' => $studentId,
  1742. 'total_questions' => $totalQuestions
  1743. ]);
  1744. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1745. // 如果题目数量超过目标,则截取到目标数量
  1746. // 如果题目数量不足,则使用所有题目,并记录警告
  1747. if (count($questions) > $totalQuestions) {
  1748. Log::info('题目数量超过目标,进行截取', [
  1749. 'question_count' => count($questions),
  1750. 'total_questions' => $totalQuestions,
  1751. 'note' => '将按权重选择最合适的题目'
  1752. ]);
  1753. } else {
  1754. Log::warning('题目数量不足,将使用所有可用题目', [
  1755. 'available_count' => count($questions),
  1756. 'requested_count' => $totalQuestions,
  1757. 'note' => '可能需要补充题库或放宽筛选条件'
  1758. ]);
  1759. }
  1760. // 【移除】删除多余的难度筛选逻辑
  1761. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1762. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1763. Log::info('跳过多余的难度筛选,使用题目原始难度分布', [
  1764. 'question_count' => count($questions),
  1765. 'note' => '由QuestionLocalService处理难度分布'
  1766. ]);
  1767. // 1. 按知识点分组
  1768. Log::info('开始按知识点分组', [
  1769. 'question_count' => count($questions)
  1770. ]);
  1771. $groupStartTime = microtime(true);
  1772. $questionsByKp = [];
  1773. foreach ($questions as $question) {
  1774. $kpCode = $question['kp_code'] ?? '';
  1775. if (!isset($questionsByKp[$kpCode])) {
  1776. $questionsByKp[$kpCode] = [];
  1777. }
  1778. $questionsByKp[$kpCode][] = $question;
  1779. }
  1780. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1781. Log::info('按知识点分组完成', [
  1782. 'kp_count' => count($questionsByKp),
  1783. 'group_time_ms' => round($groupTime, 2)
  1784. ]);
  1785. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1786. $kpWeights = [];
  1787. $kpCodes = array_keys($questionsByKp);
  1788. Log::info('开始计算知识点权重(用于题型内排序)', [
  1789. 'kp_count' => count($kpCodes),
  1790. 'student_id' => $studentId
  1791. ]);
  1792. $startTime = microtime(true);
  1793. $allMastery = [];
  1794. if ($studentId) {
  1795. // 批量获取所有知识点的掌握度(一次查询)
  1796. $masteryStart = microtime(true);
  1797. try {
  1798. $masteryRecords = DB::table('student_mastery')
  1799. ->where('student_id', $studentId)
  1800. ->whereIn('kp', $kpCodes)
  1801. ->pluck('mastery', 'kp')
  1802. ->all();
  1803. Log::debug('批量获取掌握度', [
  1804. 'student_id' => $studentId,
  1805. 'kp_count' => count($kpCodes),
  1806. 'found_count' => count($masteryRecords),
  1807. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1808. ]);
  1809. $allMastery = $masteryRecords;
  1810. } catch (\Exception $e) {
  1811. Log::warning('批量获取掌握度失败,将使用默认值', [
  1812. 'student_id' => $studentId,
  1813. 'error' => $e->getMessage()
  1814. ]);
  1815. }
  1816. }
  1817. foreach ($kpCodes as $kpCode) {
  1818. if ($studentId) {
  1819. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1820. // 薄弱点权重更高
  1821. if (in_array($kpCode, $weaknessFilter)) {
  1822. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1823. } else {
  1824. // 掌握度越低,权重越高
  1825. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1826. }
  1827. Log::debug('计算知识点权重', [
  1828. 'kp_code' => $kpCode,
  1829. 'mastery' => $mastery,
  1830. 'weight' => $kpWeights[$kpCode]
  1831. ]);
  1832. } else {
  1833. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1834. }
  1835. }
  1836. $totalWeightTime = (microtime(true) - $startTime) * 1000;
  1837. Log::info('知识点权重计算完成', [
  1838. 'total_kp_count' => count($kpCodes),
  1839. 'total_weight_time_ms' => round($totalWeightTime, 2),
  1840. 'avg_time_per_kp_ms' => count($kpCodes) > 0 ? round($totalWeightTime / count($kpCodes), 2) : 0
  1841. ]);
  1842. // 3. 按题型分配题目数量(权重用于题型内排序)
  1843. $selectedQuestions = [];
  1844. // 将所有题目合并
  1845. $weightedQuestions = [];
  1846. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1847. foreach ($kpQuestions as $q) {
  1848. $q['kp_code'] = $kpCode;
  1849. $weightedQuestions[] = $q;
  1850. }
  1851. }
  1852. // ========== 知识点优先选择机制 ==========
  1853. // 摸底测试的核心目标是最大化知识点覆盖
  1854. // 题型只是约束条件(每种至少1题)
  1855. // 首先按题型分组
  1856. $questionsByType = [
  1857. 'choice' => [],
  1858. 'fill' => [],
  1859. 'answer' => [],
  1860. ];
  1861. foreach ($weightedQuestions as $q) {
  1862. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1863. if ($qid && isset($questionTypeCache[$qid])) {
  1864. $type = $questionTypeCache[$qid];
  1865. } else {
  1866. $type = $this->determineQuestionType($q);
  1867. if ($qid) {
  1868. $questionTypeCache[$qid] = $type;
  1869. }
  1870. }
  1871. if (!isset($questionsByType[$type])) {
  1872. $type = 'answer'; // 默认归类为answer
  1873. }
  1874. $questionsByType[$type][] = $q;
  1875. }
  1876. // ========== 步骤1:按题型分配题目 ==========
  1877. $selectedQuestions = [];
  1878. // 【区分】根据assembleType决定是否使用知识点优先机制
  1879. $useKnowledgePointPriority = ($assembleType === 0); // 摸底测试需要知识点优先
  1880. $kpSelected = []; // 已选知识点记录
  1881. Log::info('selectQuestionsByMastery: 知识点优先策略', [
  1882. 'assemble_type' => $assembleType,
  1883. 'use_knowledge_point_priority' => $useKnowledgePointPriority,
  1884. 'note' => $useKnowledgePointPriority ? '摸底测试:需要均衡分配知识点' : '知识点组卷:允许同一知识点选多题'
  1885. ]);
  1886. // 确保每种题型至少选1题
  1887. foreach (['choice', 'fill', 'answer'] as $type) {
  1888. if (empty($questionsByType[$type])) {
  1889. Log::warning('题型分配:题型无题目', ['type' => $type]);
  1890. continue;
  1891. }
  1892. // 按权重排序该题型的题目
  1893. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  1894. $kpA = $a['kp_code'] ?? '';
  1895. $kpB = $b['kp_code'] ?? '';
  1896. $weightA = $kpWeights[$kpA] ?? 1.0;
  1897. $weightB = $kpWeights[$kpB] ?? 1.0;
  1898. return $weightB <=> $weightA;
  1899. });
  1900. // 根据策略选择题目
  1901. if ($useKnowledgePointPriority) {
  1902. // 摸底测试:选择第一个未选过知识点的题目
  1903. foreach ($questionsByType[$type] as $q) {
  1904. $kpCode = $q['kp_code'] ?? '';
  1905. if (!isset($kpSelected[$kpCode])) {
  1906. $selectedQuestions[] = $q;
  1907. $kpSelected[$kpCode] = true;
  1908. Log::debug('题型基础分配(知识点优先)', ['type' => $type, 'kp' => $kpCode]);
  1909. break;
  1910. }
  1911. }
  1912. } else {
  1913. // 【修复】知识点组卷:随机选择该题型的一道题,避免固定选择第一个导致知识点分布不均
  1914. $randomIndex = array_rand($questionsByType[$type]);
  1915. $selectedQuestions[] = $questionsByType[$type][$randomIndex];
  1916. Log::debug('题型基础分配(随机选择)', [
  1917. 'type' => $type,
  1918. 'kp' => $questionsByType[$type][$randomIndex]['kp_code'] ?? 'unknown',
  1919. 'random_index' => $randomIndex,
  1920. 'total_in_type' => count($questionsByType[$type])
  1921. ]);
  1922. }
  1923. }
  1924. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  1925. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  1926. // 【重要】添加排序前的知识点分布日志
  1927. $preSortKpDistribution = [];
  1928. foreach ($allQuestions as $q) {
  1929. $kpCode = $q['kp_code'] ?? '';
  1930. if (!isset($preSortKpDistribution[$kpCode])) {
  1931. $preSortKpDistribution[$kpCode] = 0;
  1932. }
  1933. $preSortKpDistribution[$kpCode]++;
  1934. }
  1935. Log::info('selectQuestionsByMastery: 排序前知识点分布', [
  1936. 'total_questions' => count($allQuestions),
  1937. 'kp_distribution' => $preSortKpDistribution,
  1938. 'note' => '用于对比排序后的分布变化'
  1939. ]);
  1940. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  1941. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  1942. $kpA = $a['kp_code'] ?? '';
  1943. $kpB = $b['kp_code'] ?? '';
  1944. $weightA = $kpWeights[$kpA] ?? 1.0;
  1945. $weightB = $kpWeights[$kpB] ?? 1.0;
  1946. // 主要按权重排序
  1947. if ($weightA != $weightB) {
  1948. return $weightB <=> $weightA;
  1949. }
  1950. // 权重相同时,添加随机排序而不是按ID排序
  1951. // 使用随机因子确保相同权重的知识点有公平的选中机会
  1952. return mt_rand(-1, 1);
  1953. });
  1954. // 【重要】添加排序后的知识点分布日志
  1955. $postSortKpDistribution = [];
  1956. $postSortFirst50 = []; // 记录前50题的知识点分布
  1957. foreach ($allQuestions as $idx => $q) {
  1958. $kpCode = $q['kp_code'] ?? '';
  1959. if (!isset($postSortKpDistribution[$kpCode])) {
  1960. $postSortKpDistribution[$kpCode] = 0;
  1961. }
  1962. $postSortKpDistribution[$kpCode]++;
  1963. // 记录前50题的知识点
  1964. if ($idx < 50) {
  1965. $postSortFirst50[] = $kpCode;
  1966. }
  1967. }
  1968. Log::info('selectQuestionsByMastery: 排序后知识点分布', [
  1969. 'total_questions' => count($allQuestions),
  1970. 'kp_distribution' => $postSortKpDistribution,
  1971. 'first_50_kp_codes' => $postSortFirst50,
  1972. 'note' => '观察排序是否均衡分布A07和A08'
  1973. ]);
  1974. // 根据策略继续选择题目
  1975. if ($useKnowledgePointPriority) {
  1976. // 摸底测试:选择未选过知识点的题目(优先)
  1977. foreach ($allQuestions as $q) {
  1978. if (count($selectedQuestions) >= $totalQuestions) break;
  1979. $kpCode = $q['kp_code'] ?? '';
  1980. if (!isset($kpSelected[$kpCode])) {
  1981. $selectedQuestions[] = $q;
  1982. $kpSelected[$kpCode] = true;
  1983. Log::debug('继续选择题目(知识点优先)', ['kp' => $kpCode, 'id' => $q['id'] ?? 'unknown']);
  1984. }
  1985. }
  1986. } else {
  1987. // 知识点组卷:选择未选过的题目(不要求知识点不重复)
  1988. $selectedIds = array_column($selectedQuestions, 'id');
  1989. foreach ($allQuestions as $q) {
  1990. if (count($selectedQuestions) >= $totalQuestions) break;
  1991. $qid = $q['id'] ?? null;
  1992. if ($qid && !in_array($qid, $selectedIds)) {
  1993. $selectedQuestions[] = $q;
  1994. $selectedIds[] = $qid;
  1995. Log::debug('继续选择题目(无知识点限制)', ['kp' => $q['kp_code'] ?? 'unknown', 'id' => $qid]);
  1996. }
  1997. }
  1998. }
  1999. // 【移除】删除步骤3的多余逻辑
  2000. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2001. Log::info('selectQuestionsByMastery: 题目选择完成', [
  2002. 'total_questions' => $totalQuestions,
  2003. 'selected_count' => count($selectedQuestions),
  2004. 'success' => count($selectedQuestions) === $totalQuestions,
  2005. 'assemble_type' => $assembleType,
  2006. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制',
  2007. 'type_distribution' => array_count_values(array_map(function($q) {
  2008. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2009. if ($qid && isset($questionTypeCache[$qid])) {
  2010. return $questionTypeCache[$qid];
  2011. }
  2012. return $this->determineQuestionType($q);
  2013. }, $selectedQuestions)),
  2014. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2015. ]);
  2016. // 【重要】最终截取到目标数量(如果超过)
  2017. if (count($selectedQuestions) > $totalQuestions) {
  2018. Log::info('题目数量超过目标,进行最终截取', [
  2019. 'before' => count($selectedQuestions),
  2020. 'after' => $totalQuestions
  2021. ]);
  2022. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2023. }
  2024. // 【重要】添加最终数量验证日志
  2025. Log::info('selectQuestionsByMastery: 最终题目数量验证', [
  2026. 'before_final_check' => count($selectedQuestions),
  2027. 'target_count' => $totalQuestions,
  2028. 'is_array' => is_array($selectedQuestions)
  2029. ]);
  2030. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2031. $finalQuestions = [];
  2032. $seenQuestionIds = [];
  2033. $duplicateCount = 0;
  2034. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2035. foreach ($selectedQuestions as $question) {
  2036. $qbId = $question['question_bank_id'] ?? $question['id'];
  2037. if (!in_array($qbId, $seenQuestionIds)) {
  2038. $seenQuestionIds[] = $qbId;
  2039. $finalQuestions[] = $question;
  2040. // 统计题型分布
  2041. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2042. $type = null;
  2043. if ($qid && isset($questionTypeCache[$qid])) {
  2044. $type = $questionTypeCache[$qid];
  2045. } else {
  2046. $type = $this->determineQuestionType($question);
  2047. if ($qid) {
  2048. $questionTypeCache[$qid] = $type;
  2049. }
  2050. }
  2051. if (isset($typeDistribution[$type])) {
  2052. $typeDistribution[$type]++;
  2053. }
  2054. } else {
  2055. $duplicateCount++;
  2056. Log::warning('发现重复题目(已自动移除)', [
  2057. 'question_id' => $qbId,
  2058. 'duplicate_count' => $duplicateCount
  2059. ]);
  2060. }
  2061. }
  2062. // 【重要】如果去重后数量不足,补充到目标数量
  2063. if (count($finalQuestions) < $totalQuestions) {
  2064. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2065. 'final_count' => count($finalQuestions),
  2066. 'target_count' => $totalQuestions,
  2067. 'need_more' => $totalQuestions - count($finalQuestions)
  2068. ]);
  2069. // 从原始题目中选择未选过的题目补充
  2070. $usedIds = array_column($finalQuestions, 'id');
  2071. $supplementCount = 0;
  2072. foreach ($selectedQuestions as $question) {
  2073. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2074. $qid = $question['id'] ?? null;
  2075. if ($qid && !in_array($qid, $usedIds)) {
  2076. $finalQuestions[] = $question;
  2077. $usedIds[] = $qid;
  2078. $supplementCount++;
  2079. }
  2080. }
  2081. Log::info('selectQuestionsByMastery: 补充完成', [
  2082. 'supplement_added' => $supplementCount,
  2083. 'final_count_after_supplement' => count($finalQuestions)
  2084. ]);
  2085. }
  2086. Log::info('最终排查完成', [
  2087. 'original_count' => count($selectedQuestions),
  2088. 'final_count' => count($finalQuestions),
  2089. 'duplicate_removed' => $duplicateCount,
  2090. 'final_type_distribution' => $typeDistribution,
  2091. 'target_count' => $totalQuestions
  2092. ]);
  2093. // 【重要】确保返回的题目数量正确
  2094. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2095. Log::info('selectQuestionsByMastery: 返回结果', [
  2096. 'return_count' => count($finalQuestions),
  2097. 'target_count' => $totalQuestions,
  2098. 'success' => count($finalQuestions) === $totalQuestions
  2099. ]);
  2100. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2101. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2102. return $finalQuestions;
  2103. }
  2104. /**
  2105. * 获取学生对特定知识点的掌握度
  2106. */
  2107. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2108. {
  2109. try {
  2110. $mastery = DB::table('student_mastery')
  2111. ->where('student_id', $studentId)
  2112. ->where('kp', $kpCode)
  2113. ->value('mastery');
  2114. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2115. } catch (\Exception $e) {
  2116. Log::error('Get Student Kp Mastery Error', [
  2117. 'student_id' => $studentId,
  2118. 'kp_code' => $kpCode,
  2119. 'error' => $e->getMessage()
  2120. ]);
  2121. return 0.5;
  2122. }
  2123. }
  2124. /**
  2125. * 根据题型和难度配比调整题目
  2126. */
  2127. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2128. {
  2129. Log::info('开始题型配比调整', [
  2130. 'input_questions' => count($questions),
  2131. 'target_count' => $targetCount,
  2132. 'type_ratio' => $typeRatio
  2133. ]);
  2134. // 缓存题目类型,避免重复计算
  2135. $questionTypeCache = [];
  2136. // 按题型分桶
  2137. $buckets = [
  2138. 'choice' => [],
  2139. 'fill' => [],
  2140. 'answer' => [],
  2141. ];
  2142. foreach ($questions as $q) {
  2143. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2144. if ($qid && isset($questionTypeCache[$qid])) {
  2145. $type = $questionTypeCache[$qid];
  2146. } else {
  2147. $type = $this->determineQuestionType($q);
  2148. if ($qid) {
  2149. $questionTypeCache[$qid] = $type;
  2150. }
  2151. }
  2152. if (!isset($buckets[$type])) {
  2153. $type = 'answer';
  2154. }
  2155. $buckets[$type][] = $q;
  2156. }
  2157. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2158. // 修复:不自动减少目标数量,确保达到用户要求
  2159. $availableCount = count($questions);
  2160. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2161. Log::info('题型配比调整前桶统计', [
  2162. 'target_count' => $targetCount,
  2163. 'available_count' => $availableCount,
  2164. 'targets' => $targets,
  2165. 'bucket_counts' => [
  2166. 'choice' => count($buckets['choice']),
  2167. 'fill' => count($buckets['fill']),
  2168. 'answer' => count($buckets['answer']),
  2169. ],
  2170. 'raw_ratio' => $typeRatio,
  2171. ]);
  2172. // 随机打乱桶
  2173. foreach ($buckets as $k => $v) {
  2174. if (!empty($v)) {
  2175. shuffle($v);
  2176. $buckets[$k] = $v;
  2177. }
  2178. }
  2179. $selected = [];
  2180. $selectedIds = [];
  2181. // 按目标数依次取题
  2182. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2183. $need = $targets[$typeKey] ?? 0;
  2184. if ($need <= 0 || empty($buckets[$typeKey])) {
  2185. continue;
  2186. }
  2187. $take = min($need, count($buckets[$typeKey]));
  2188. $slice = array_slice($buckets[$typeKey], 0, $take);
  2189. foreach ($slice as $q) {
  2190. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2191. if (isset($selectedIds[$id])) {
  2192. continue;
  2193. }
  2194. $selected[] = $q;
  2195. $selectedIds[$id] = true;
  2196. }
  2197. }
  2198. // 不足则从剩余题中补齐
  2199. if (count($selected) < $targetCount) {
  2200. $remaining = [];
  2201. foreach ($buckets as $v) {
  2202. foreach ($v as $q) {
  2203. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2204. if (!isset($selectedIds[$id])) {
  2205. $remaining[] = $q;
  2206. }
  2207. }
  2208. }
  2209. shuffle($remaining);
  2210. $needMore = $targetCount - count($selected);
  2211. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2212. }
  2213. // 截断至目标数
  2214. $selected = array_slice($selected, 0, $targetCount);
  2215. // 使用缓存统计题型分布
  2216. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2217. foreach ($selected as $q) {
  2218. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2219. if ($qid && isset($questionTypeCache[$qid])) {
  2220. $type = $questionTypeCache[$qid];
  2221. } else {
  2222. $type = $this->determineQuestionType($q);
  2223. }
  2224. if (isset($selectedCounts[$type])) {
  2225. $selectedCounts[$type]++;
  2226. }
  2227. }
  2228. Log::info('题型配比调整完成', [
  2229. 'target_count' => $targetCount,
  2230. 'targets' => $targets,
  2231. 'selected_counts' => $selectedCounts,
  2232. 'final_selected_count' => count($selected)
  2233. ]);
  2234. return $selected;
  2235. }
  2236. private function determineQuestionType(array $q): string
  2237. {
  2238. // 优先根据题目内容判断(而不是数据库字段)
  2239. $stem = $q['stem'] ?? $q['content'] ?? '';
  2240. // 处理 stem 可能是数组的情况
  2241. if (is_array($stem)) {
  2242. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2243. }
  2244. $tags = $q['tags'] ?? '';
  2245. // 处理 tags 可能是数组的情况
  2246. if (is_array($tags)) {
  2247. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2248. }
  2249. $skills = $q['skills'] ?? [];
  2250. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2251. if (is_string($stem)) {
  2252. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2253. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2254. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2255. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2256. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2257. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2258. // 至少有2个选项就认为是选择题(降低阈值)
  2259. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2260. if ($optionCount >= 2) {
  2261. return 'choice';
  2262. }
  2263. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2264. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2265. return 'choice';
  2266. }
  2267. }
  2268. // 2. 根据技能点判断
  2269. if (is_array($skills) && !empty($skills)) {
  2270. // 过滤非字符串元素,避免 implode 报错
  2271. $skillsFiltered = array_filter($skills, 'is_string');
  2272. if (!empty($skillsFiltered)) {
  2273. $skillsStr = implode(',', $skillsFiltered);
  2274. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2275. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2276. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2277. }
  2278. }
  2279. // 3. 根据题目已有类型字段判断(作为后备)
  2280. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2281. if (is_string($typeField)) {
  2282. $t = strtolower($typeField);
  2283. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2284. return 'choice';
  2285. }
  2286. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2287. return 'fill';
  2288. }
  2289. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2290. return 'answer';
  2291. }
  2292. }
  2293. // 4. 根据标签判断
  2294. if (is_string($tags)) {
  2295. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2296. return 'choice';
  2297. }
  2298. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2299. return 'fill';
  2300. }
  2301. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2302. return 'answer';
  2303. }
  2304. }
  2305. // 5. 根据options字段判断
  2306. if (!empty($q['options']) && is_array($q['options'])) {
  2307. return 'choice';
  2308. }
  2309. // 6. 填空题特征:连续下划线或明显的填空括号
  2310. if (is_string($stem)) {
  2311. // 检查填空题特征:连续下划线
  2312. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2313. return 'fill';
  2314. }
  2315. // 空括号填空
  2316. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2317. return 'fill';
  2318. }
  2319. }
  2320. // 7. 根据题干内容关键词判断
  2321. if (is_string($stem)) {
  2322. // 有证明、解答、计算、求证等关键词的是解答题
  2323. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2324. return 'answer';
  2325. }
  2326. }
  2327. // 默认是解答题(更安全的默认值)
  2328. return 'answer';
  2329. }
  2330. // 【移除】删除未使用的mapDifficultyLevel方法
  2331. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2332. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2333. {
  2334. $map = [
  2335. '选择题' => 'choice',
  2336. '填空题' => 'fill',
  2337. '解答题' => 'answer',
  2338. ];
  2339. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2340. foreach ($questionTypeRatio as $label => $ratio) {
  2341. $key = $map[$label] ?? null;
  2342. if (!$key) {
  2343. continue;
  2344. }
  2345. $cnt = (int) round($targetCount * ($ratio / 100));
  2346. if ($ratio > 0 && $cnt < 1) {
  2347. $cnt = 1;
  2348. }
  2349. $targets[$key] = $cnt;
  2350. }
  2351. $sum = array_sum($targets);
  2352. if ($sum === 0) {
  2353. $targets['answer'] = $targetCount;
  2354. return $targets;
  2355. }
  2356. while ($sum > $targetCount) {
  2357. arsort($targets);
  2358. foreach ($targets as $k => $v) {
  2359. if ($v > 1) {
  2360. $targets[$k]--;
  2361. $sum--;
  2362. break;
  2363. }
  2364. }
  2365. }
  2366. if ($sum < $targetCount) {
  2367. $ratioByKey = [
  2368. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2369. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2370. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  2371. ];
  2372. while ($sum < $targetCount) {
  2373. arsort($ratioByKey);
  2374. $k = array_key_first($ratioByKey);
  2375. $targets[$k]++;
  2376. $sum++;
  2377. }
  2378. }
  2379. return $targets;
  2380. }
  2381. /**
  2382. * 提交手动评分结果到 LearningAnalytics
  2383. *
  2384. * @param array $data 包含 student_id, paper_id, grades 的数组
  2385. * @return array
  2386. */
  2387. public function submitManualGrading(array $data): array
  2388. {
  2389. try {
  2390. $response = Http::timeout($this->timeout)
  2391. ->post($this->baseUrl . '/api/ocr/analyze', [
  2392. 'student_id' => $data['student_id'],
  2393. 'paper_id' => $data['paper_id'],
  2394. 'answers' => $data['grades'],
  2395. ]);
  2396. if ($response->successful()) {
  2397. Log::info('Manual grading submitted successfully', [
  2398. 'student_id' => $data['student_id'],
  2399. 'paper_id' => $data['paper_id'],
  2400. 'question_count' => count($data['grades'])
  2401. ]);
  2402. return $response->json();
  2403. }
  2404. Log::error('Submit Manual Grading Error', [
  2405. 'data' => $data,
  2406. 'status' => $response->status(),
  2407. 'response' => $response->body()
  2408. ]);
  2409. return [
  2410. 'error' => true,
  2411. 'message' => 'Failed to submit manual grading'
  2412. ];
  2413. } catch (\Exception $e) {
  2414. Log::error('Submit Manual Grading Exception', [
  2415. 'error' => $e->getMessage(),
  2416. 'data' => $data
  2417. ]);
  2418. return [
  2419. 'error' => true,
  2420. 'message' => $e->getMessage()
  2421. ];
  2422. }
  2423. }
  2424. /**
  2425. * 分析学生作答结果
  2426. *
  2427. * @param array $data 包含 paper_id, student_id, answers 等
  2428. * @return array
  2429. */
  2430. public function analyzeStudentAnswers(array $data): array
  2431. {
  2432. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  2433. 'student_id' => $data['student_id'] ?? null,
  2434. 'paper_id' => $data['paper_id'] ?? null,
  2435. ]);
  2436. return [
  2437. 'success' => false,
  2438. 'message' => 'analysis_api_disabled',
  2439. ];
  2440. }
  2441. }