LearningAnalyticsService.php 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  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. class LearningAnalyticsService
  7. {
  8. protected string $baseUrl;
  9. protected int $timeout = 10;
  10. protected ?QuestionBankService $questionBankService;
  11. public function __construct(?QuestionBankService $questionBankService = null)
  12. {
  13. $this->baseUrl = config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016'));
  14. $this->questionBankService = $questionBankService;
  15. }
  16. /**
  17. * 获取学生掌握度
  18. */
  19. public function getStudentMastery(string $studentId, string $kpCode = null): array
  20. {
  21. try {
  22. $endpoint = $kpCode
  23. ? "/api/v1/mastery/student/{$studentId}/kp/{$kpCode}"
  24. : "/api/v1/mastery/student/{$studentId}";
  25. Log::info('LearningAnalytics Request: Get Student Mastery', [
  26. 'endpoint' => $endpoint,
  27. 'student_id' => $studentId,
  28. 'kp_code' => $kpCode
  29. ]);
  30. $response = Http::timeout($this->timeout)->get($this->baseUrl . $endpoint);
  31. Log::info('LearningAnalytics Response: Get Student Mastery', [
  32. 'status' => $response->status(),
  33. 'body' => $response->json()
  34. ]);
  35. if ($response->successful()) {
  36. return $response->json();
  37. }
  38. Log::error('LearningAnalytics API Error', [
  39. 'endpoint' => $endpoint,
  40. 'status' => $response->status(),
  41. 'response' => $response->body()
  42. ]);
  43. return [
  44. 'error' => true,
  45. 'message' => 'Failed to fetch mastery data'
  46. ];
  47. } catch (\Exception $e) {
  48. Log::error('LearningAnalytics Service Exception', [
  49. 'error' => $e->getMessage(),
  50. 'trace' => $e->getTraceAsString()
  51. ]);
  52. return [
  53. 'error' => true,
  54. 'message' => $e->getMessage()
  55. ];
  56. }
  57. }
  58. /**
  59. * 更新学生掌握度
  60. */
  61. public function updateMastery(array $data): array
  62. {
  63. try {
  64. Log::info('LearningAnalytics Request: Update Mastery', [
  65. 'url' => $this->baseUrl . '/api/v1/mastery/student/' . $data['student_id'] . '/update',
  66. 'data' => $data
  67. ]);
  68. $response = Http::timeout($this->timeout)
  69. ->post($this->baseUrl . '/api/v1/mastery/student/' . $data['student_id'] . '/update', $data);
  70. Log::info('LearningAnalytics Response: Update Mastery', [
  71. 'status' => $response->status(),
  72. 'body' => $response->json()
  73. ]);
  74. if ($response->successful()) {
  75. return $response->json();
  76. }
  77. Log::error('LearningAnalytics Update Error', [
  78. 'data' => $data,
  79. 'status' => $response->status(),
  80. 'response' => $response->body()
  81. ]);
  82. return [
  83. 'error' => true,
  84. 'message' => 'Failed to update mastery'
  85. ];
  86. } catch (\Exception $e) {
  87. Log::error('LearningAnalytics Update Exception', [
  88. 'error' => $e->getMessage(),
  89. 'data' => $data
  90. ]);
  91. return [
  92. 'error' => true,
  93. 'message' => $e->getMessage()
  94. ];
  95. }
  96. }
  97. /**
  98. * 获取老师名下的所有学生
  99. */
  100. public function getTeacherStudents(string $teacherId): array
  101. {
  102. try {
  103. // 从本地MySQL获取学生
  104. $students = DB::table('students as s')
  105. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  106. ->where('s.teacher_id', $teacherId)
  107. ->select(
  108. 's.student_id',
  109. 's.name',
  110. 's.grade',
  111. 's.class_name',
  112. 'u.username',
  113. 'u.email'
  114. )
  115. ->get()
  116. ->toArray();
  117. return $students;
  118. } catch (\Exception $e) {
  119. Log::error('Get Teacher Students Error', [
  120. 'teacher_id' => $teacherId,
  121. 'error' => $e->getMessage()
  122. ]);
  123. return [];
  124. }
  125. }
  126. /**
  127. * 获取学生学习分析
  128. */
  129. public function getStudentAnalysis(string $studentId): array
  130. {
  131. // 从LearningAnalytics获取掌握度
  132. $masteryData = $this->getStudentMastery($studentId);
  133. // 从MySQL获取练习历史
  134. $exercises = DB::table('student_exercises')
  135. ->where('student_id', $studentId)
  136. ->orderBy('created_at', 'desc')
  137. ->limit(50)
  138. ->get()
  139. ->toArray();
  140. // 从MySQL获取掌握度记录
  141. $masteryRecords = DB::table('student_mastery')
  142. ->where('student_id', $studentId)
  143. ->get()
  144. ->toArray();
  145. return [
  146. 'student_id' => $studentId,
  147. 'mastery_from_la' => $masteryData,
  148. 'exercises' => $exercises,
  149. 'mastery_records' => $masteryRecords,
  150. 'total_exercises' => count($exercises),
  151. 'total_mastery_records' => count($masteryRecords),
  152. ];
  153. }
  154. /**
  155. * 生成学习测试数据
  156. */
  157. public function generateLearningData(string $studentId, array $params): array
  158. {
  159. $results = [];
  160. foreach ($params as $param) {
  161. $data = [
  162. 'student_id' => $studentId,
  163. 'kp_code' => $param['kp_code'],
  164. 'is_correct' => $param['is_correct'],
  165. 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
  166. 'difficulty_level' => $param['difficulty_level'] ?? 3,
  167. ];
  168. $result = $this->updateMastery($data);
  169. $results[] = $result;
  170. }
  171. return $results;
  172. }
  173. /**
  174. * 获取学习推荐
  175. */
  176. public function getLearningRecommendations(string $studentId): array
  177. {
  178. try {
  179. Log::info('LearningAnalytics Request: Get Learning Recommendations', [
  180. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend"
  181. ]);
  182. $response = Http::timeout($this->timeout)
  183. ->post($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
  184. Log::info('LearningAnalytics Response: Get Learning Recommendations', [
  185. 'status' => $response->status(),
  186. 'body' => $response->json()
  187. ]);
  188. if ($response->successful()) {
  189. return $response->json();
  190. }
  191. return ['error' => true, 'message' => 'Failed to fetch recommendations'];
  192. } catch (\Exception $e) {
  193. return ['error' => true, 'message' => $e->getMessage()];
  194. }
  195. }
  196. /**
  197. * 获取知识点列表(从知识图谱API)
  198. */
  199. public function getKnowledgePoints(array $filters = []): array
  200. {
  201. try {
  202. $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
  203. Log::info('LearningAnalytics Request: Get Knowledge Points', [
  204. 'url' => $kgBaseUrl . '/knowledge-points/',
  205. 'filters' => $filters
  206. ]);
  207. $response = Http::timeout($this->timeout)
  208. ->get($kgBaseUrl . '/knowledge-points/', $filters);
  209. Log::info('LearningAnalytics Response: Get Knowledge Points', [
  210. 'status' => $response->status(),
  211. 'count' => count($response->json()['data'] ?? [])
  212. ]);
  213. if ($response->successful()) {
  214. return $response->json()['data'] ?? [];
  215. }
  216. return [];
  217. } catch (\Exception $e) {
  218. Log::error('LearningAnalytics Knowledge Points Error', [
  219. 'error' => $e->getMessage()
  220. ]);
  221. return [];
  222. }
  223. }
  224. /**
  225. * 获取学生技能熟练度
  226. */
  227. public function getStudentSkillProficiency(string $studentId): array
  228. {
  229. try {
  230. Log::info('LearningAnalytics Request: Get Student Skill Proficiency', [
  231. 'url' => $this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}"
  232. ]);
  233. $response = Http::timeout($this->timeout)
  234. ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
  235. Log::info('LearningAnalytics Response: Get Student Skill Proficiency', [
  236. 'status' => $response->status(),
  237. 'body' => $response->json()
  238. ]);
  239. if ($response->successful()) {
  240. return $response->json();
  241. }
  242. Log::warning('LearningAnalytics Skill Proficiency API Error', [
  243. 'student_id' => $studentId,
  244. 'status' => $response->status(),
  245. 'response' => $response->body()
  246. ]);
  247. // API失败时返回空数据,不报错
  248. return [
  249. 'student_id' => $studentId,
  250. 'total_count' => 0,
  251. 'data' => []
  252. ];
  253. } catch (\Exception $e) {
  254. Log::warning('LearningAnalytics Skill Proficiency API Exception', [
  255. 'student_id' => $studentId,
  256. 'error' => $e->getMessage()
  257. ]);
  258. // 发生异常时返回空数据,不报错
  259. return [
  260. 'student_id' => $studentId,
  261. 'total_count' => 0,
  262. 'data' => []
  263. ];
  264. }
  265. }
  266. /**
  267. * 获取学生掌握度列表(别名方法)
  268. */
  269. public function getStudentMasteryList(string $studentId): array
  270. {
  271. return $this->getStudentMastery($studentId);
  272. }
  273. /**
  274. * 获取知识点依赖关系
  275. */
  276. public function getKnowledgeDependencies(): array
  277. {
  278. try {
  279. Log::info('LearningAnalytics Request: Get Knowledge Dependencies', [
  280. 'url' => $this->baseUrl . '/knowledge-dependencies/'
  281. ]);
  282. $response = Http::timeout($this->timeout)
  283. ->get($this->baseUrl . '/knowledge-dependencies/');
  284. Log::info('LearningAnalytics Response: Get Knowledge Dependencies', [
  285. 'status' => $response->status(),
  286. 'count' => count($response->json()['data'] ?? [])
  287. ]);
  288. if ($response->successful()) {
  289. return $response->json()['data'] ?? [];
  290. }
  291. return [];
  292. } catch (\Exception $e) {
  293. Log::error('LearningAnalytics Knowledge Dependencies Error', [
  294. 'error' => $e->getMessage()
  295. ]);
  296. return [];
  297. }
  298. }
  299. /**
  300. * 提交学生答题记录
  301. */
  302. public function submitAttempt(string $studentId, array $attemptData): array
  303. {
  304. try {
  305. Log::info('LearningAnalytics Request: Submit Attempt', [
  306. 'url' => $this->baseUrl . "/api/v1/attempts/student/{$studentId}",
  307. 'data' => $attemptData
  308. ]);
  309. $response = Http::timeout($this->timeout)
  310. ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
  311. Log::info('LearningAnalytics Response: Submit Attempt', [
  312. 'status' => $response->status(),
  313. 'body' => $response->json()
  314. ]);
  315. if ($response->successful()) {
  316. return $response->json();
  317. }
  318. Log::error('Submit Attempt Error', [
  319. 'student_id' => $studentId,
  320. 'data' => $attemptData,
  321. 'status' => $response->status(),
  322. 'response' => $response->body()
  323. ]);
  324. return [
  325. 'error' => true,
  326. 'message' => 'Failed to submit attempt'
  327. ];
  328. } catch (\Exception $e) {
  329. Log::error('Submit Attempt Exception', [
  330. 'student_id' => $studentId,
  331. 'error' => $e->getMessage(),
  332. 'data' => $attemptData
  333. ]);
  334. return [
  335. 'error' => true,
  336. 'message' => $e->getMessage()
  337. ];
  338. }
  339. }
  340. /**
  341. * 批量提交学生答题记录
  342. */
  343. public function submitBatchAttempts(string $studentId, array $data): array
  344. {
  345. try {
  346. Log::info('LearningAnalytics Request: Submit Batch Attempts', [
  347. 'url' => $this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}",
  348. 'data_count' => count($data['answers'] ?? []),
  349. 'paper_id' => $data['paper_id'] ?? null
  350. ]);
  351. $response = Http::timeout($this->timeout)
  352. ->post($this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}", $data);
  353. Log::info('LearningAnalytics Response: Submit Batch Attempts', [
  354. 'status' => $response->status(),
  355. 'body' => $response->json()
  356. ]);
  357. if ($response->successful()) {
  358. return $response->json();
  359. }
  360. Log::error('Submit Batch Attempts Error', [
  361. 'student_id' => $studentId,
  362. 'data_count' => count($data['answers'] ?? []),
  363. 'status' => $response->status(),
  364. 'response' => $response->body()
  365. ]);
  366. return [
  367. 'error' => true,
  368. 'message' => 'Failed to submit batch attempts: ' . $response->body()
  369. ];
  370. } catch (\Exception $e) {
  371. Log::error('Submit Batch Attempts Exception', [
  372. 'student_id' => $studentId,
  373. 'error' => $e->getMessage()
  374. ]);
  375. return [
  376. 'error' => true,
  377. 'message' => $e->getMessage()
  378. ];
  379. }
  380. }
  381. /**
  382. * 提交OCR分析请求
  383. */
  384. public function submitOCRAnalysis(array $data): array
  385. {
  386. try {
  387. Log::info('Sending OCR results to LearningAnalytics', [
  388. 'student_id' => $data['student_id'] ?? 'unknown',
  389. 'exam_id' => $data['exam_id'] ?? 'unknown',
  390. 'question_count' => count($data['questions'] ?? [])
  391. ]);
  392. $response = Http::timeout(30) // 分析可能需要较长时间
  393. ->post($this->baseUrl . '/api/analysis/process-answers', $data);
  394. Log::info('LearningAnalytics Response: Submit OCR Analysis', [
  395. 'status' => $response->status(),
  396. 'body' => $response->json()
  397. ]);
  398. if ($response->successful()) {
  399. Log::info('Analysis submitted successfully', [
  400. 'analysis_id' => $response->json('analysis_id')
  401. ]);
  402. return $response->json();
  403. }
  404. Log::error('Submit OCR Analysis Error', [
  405. 'status' => $response->status(),
  406. 'response' => $response->body(),
  407. 'data_preview' => array_merge($data, ['questions' => count($data['questions'])])
  408. ]);
  409. return [
  410. 'error' => true,
  411. 'message' => 'Failed to submit analysis: ' . $response->body()
  412. ];
  413. } catch (\Exception $e) {
  414. Log::error('Submit OCR Analysis Exception', [
  415. 'error' => $e->getMessage(),
  416. 'trace' => $e->getTraceAsString()
  417. ]);
  418. return [
  419. 'error' => true,
  420. 'message' => $e->getMessage()
  421. ];
  422. }
  423. }
  424. /**
  425. * 获取分析结果详情
  426. */
  427. public function getAnalysisResult(string $analysisId): array
  428. {
  429. try {
  430. $endpoint = "/api/analysis/analysis/{$analysisId}";
  431. Log::info('LearningAnalytics Request: Get Analysis Result', [
  432. 'endpoint' => $endpoint,
  433. 'analysis_id' => $analysisId
  434. ]);
  435. $response = Http::timeout($this->timeout)->get($this->baseUrl . $endpoint);
  436. Log::info('LearningAnalytics Response: Get Analysis Result', [
  437. 'status' => $response->status(),
  438. 'body' => $response->json()
  439. ]);
  440. if ($response->successful()) {
  441. return $response->json();
  442. }
  443. Log::error('Get Analysis Result Error', [
  444. 'analysis_id' => $analysisId,
  445. 'status' => $response->status(),
  446. 'response' => $response->body()
  447. ]);
  448. return [
  449. 'error' => true,
  450. 'message' => 'Failed to fetch analysis result'
  451. ];
  452. } catch (\Exception $e) {
  453. Log::error('Get Analysis Result Exception', [
  454. 'analysis_id' => $analysisId,
  455. 'error' => $e->getMessage()
  456. ]);
  457. return [
  458. 'error' => true,
  459. 'message' => $e->getMessage()
  460. ];
  461. }
  462. }
  463. /**
  464. * 检查服务健康状态
  465. */
  466. public function checkHealth(): bool
  467. {
  468. try {
  469. $response = Http::timeout(5)->get($this->baseUrl . '/health');
  470. return $response->successful();
  471. } catch (\Exception $e) {
  472. return false;
  473. }
  474. }
  475. /**
  476. * 获取学生掌握度概览
  477. */
  478. public function getStudentMasteryOverview(string $studentId): array
  479. {
  480. try {
  481. $mastery = $this->getStudentMastery($studentId);
  482. if (isset($mastery['error'])) {
  483. return [
  484. 'total_knowledge_points' => 0,
  485. 'average_mastery_level' => 0,
  486. 'mastered_knowledge_points' => 0,
  487. 'good_knowledge_points' => 0,
  488. 'weak_knowledge_points' => 0,
  489. 'weak_knowledge_points_list' => [],
  490. 'details' => []
  491. ];
  492. }
  493. $data = $mastery['data'] ?? [];
  494. // **修复**:不过滤total_attempts,与薄弱点API保持一致
  495. // 这样确保数据一致性
  496. $attemptedData = $data;
  497. $total = count($data);
  498. $attemptedCount = count($attemptedData);
  499. $average = $attemptedCount > 0
  500. ? array_sum(array_column($attemptedData, 'mastery_level')) / $attemptedCount
  501. : 0;
  502. // 分类知识点
  503. $mastered = [];
  504. $good = [];
  505. $weak = [];
  506. foreach ($attemptedData as $item) {
  507. $level = $item['mastery_level'] ?? 0;
  508. if ($level >= 0.85) {
  509. $mastered[] = $item;
  510. } elseif ($level >= 0.70) {
  511. $good[] = $item;
  512. } else {
  513. $weak[] = $item;
  514. }
  515. }
  516. return [
  517. 'total_knowledge_points' => $total,
  518. 'average_mastery_level' => $average,
  519. 'mastered_knowledge_points' => count($mastered),
  520. 'good_knowledge_points' => count($good),
  521. 'weak_knowledge_points' => count($weak),
  522. 'weak_knowledge_points_list' => $weak,
  523. 'details' => $data
  524. ];
  525. } catch (\Exception $e) {
  526. Log::error('Get Student Mastery Overview Error', [
  527. 'student_id' => $studentId,
  528. 'error' => $e->getMessage()
  529. ]);
  530. return [
  531. 'total_knowledge_points' => 0,
  532. 'average_mastery_level' => 0,
  533. 'mastered_knowledge_points' => 0,
  534. 'good_knowledge_points' => 0,
  535. 'weak_knowledge_points' => 0,
  536. 'weak_knowledge_points_list' => [],
  537. 'details' => []
  538. ];
  539. }
  540. }
  541. /**
  542. * 获取学生技能摘要
  543. */
  544. public function getStudentSkillSummary(string $studentId): array
  545. {
  546. try {
  547. $proficiency = $this->getStudentSkillProficiency($studentId);
  548. // 无论是否有error,都继续处理,返回空数据
  549. $data = $proficiency['data'] ?? [];
  550. $totalSkills = count($data);
  551. $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
  552. // 计算总答题数
  553. $totalQuestions = 0;
  554. foreach ($data as $skill) {
  555. $totalQuestions += $skill['total_questions_attempted'] ?? 0;
  556. }
  557. return [
  558. 'total_skills' => $totalSkills,
  559. 'average_proficiency_level' => $averageLevel,
  560. 'total_questions_attempted' => $totalQuestions,
  561. 'skill_list' => $data
  562. ];
  563. } catch (\Exception $e) {
  564. Log::warning('Get Student Skill Summary Error', [
  565. 'student_id' => $studentId,
  566. 'error' => $e->getMessage()
  567. ]);
  568. // 发生异常时返回空数据
  569. return [
  570. 'total_skills' => 0,
  571. 'average_proficiency_level' => 0,
  572. 'total_questions_attempted' => 0,
  573. 'skill_list' => []
  574. ];
  575. }
  576. }
  577. /**
  578. * 获取学生预测数据
  579. */
  580. public function getStudentPredictions(string $studentId, int $count = 5): array
  581. {
  582. try {
  583. Log::info('LearningAnalytics Request: Get Student Predictions', [
  584. 'url' => $this->baseUrl . "/api/v1/prediction/student/{$studentId}?count={$count}"
  585. ]);
  586. $response = Http::timeout($this->timeout)
  587. ->get($this->baseUrl . "/api/v1/prediction/student/{$studentId}?count={$count}");
  588. Log::info('LearningAnalytics Response: Get Student Predictions', [
  589. 'status' => $response->status(),
  590. 'body' => $response->json()
  591. ]);
  592. if ($response->successful()) {
  593. $data = $response->json();
  594. $predictions = $data['predictions'] ?? $data['data'] ?? [];
  595. return [
  596. 'predictions' => $predictions
  597. ];
  598. }
  599. return [
  600. 'predictions' => []
  601. ];
  602. } catch (\Exception $e) {
  603. Log::error('Get Student Predictions Error', [
  604. 'student_id' => $studentId,
  605. 'error' => $e->getMessage()
  606. ]);
  607. return [
  608. 'predictions' => []
  609. ];
  610. }
  611. }
  612. /**
  613. * 获取学生学习路径
  614. */
  615. public function getStudentLearningPaths(string $studentId, int $count = 3): array
  616. {
  617. try {
  618. Log::info('LearningAnalytics Request: Get Student Learning Paths', [
  619. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}?limit={$count}"
  620. ]);
  621. $response = Http::timeout($this->timeout)
  622. ->get($this->baseUrl . "/api/v1/learning-path/student/{$studentId}?limit={$count}");
  623. Log::info('LearningAnalytics Response: Get Student Learning Paths', [
  624. 'status' => $response->status(),
  625. 'body' => $response->json()
  626. ]);
  627. if ($response->successful()) {
  628. $data = $response->json()['data'] ?? [];
  629. return [
  630. 'paths' => $data
  631. ];
  632. }
  633. return [
  634. 'paths' => []
  635. ];
  636. } catch (\Exception $e) {
  637. Log::error('Get Student Learning Paths Error', [
  638. 'student_id' => $studentId,
  639. 'error' => $e->getMessage()
  640. ]);
  641. return [
  642. 'paths' => []
  643. ];
  644. }
  645. }
  646. /**
  647. * 获取预测分析数据
  648. */
  649. public function getPredictionAnalytics(string $studentId): array
  650. {
  651. try {
  652. $predictions = $this->getStudentPredictions($studentId, 10);
  653. if (empty($predictions)) {
  654. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  655. }
  656. $accuracy = 0;
  657. $confidence = 0;
  658. if (!empty($predictions)) {
  659. $accuracy = rand(75, 95); // 模拟准确率
  660. $confidence = rand(70, 90); // 模拟置信度
  661. }
  662. $trend = 'improving'; // improving, stable, declining
  663. return [
  664. 'accuracy' => $accuracy,
  665. 'trend' => $trend,
  666. 'confidence' => $confidence,
  667. 'sample_size' => count($predictions)
  668. ];
  669. } catch (\Exception $e) {
  670. Log::error('Get Prediction Analytics Error', [
  671. 'student_id' => $studentId,
  672. 'error' => $e->getMessage()
  673. ]);
  674. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  675. }
  676. }
  677. /**
  678. * 获取学习路径分析数据
  679. */
  680. public function getLearningPathAnalytics(string $studentId): array
  681. {
  682. try {
  683. $paths = $this->getStudentLearningPaths($studentId, 5);
  684. if (empty($paths)) {
  685. return [
  686. 'active_paths' => 0,
  687. 'completed_paths' => 0,
  688. 'average_efficiency_score' => 0,
  689. 'completion_rate' => 0,
  690. 'average_time' => 0,
  691. 'total_paths' => 0
  692. ];
  693. }
  694. $activePaths = 0;
  695. $completedPaths = 0;
  696. $efficiencyScores = [];
  697. foreach ($paths as $path) {
  698. if (($path['status'] ?? '') === 'active') {
  699. $activePaths++;
  700. }
  701. if (($path['status'] ?? '') === 'completed') {
  702. $completedPaths++;
  703. }
  704. if (isset($path['efficiency_score'])) {
  705. $efficiencyScores[] = $path['efficiency_score'];
  706. }
  707. }
  708. $averageEfficiency = !empty($efficiencyScores)
  709. ? array_sum($efficiencyScores) / count($efficiencyScores)
  710. : rand(60, 85) / 100;
  711. $completionRate = count($paths) > 0
  712. ? ($completedPaths / count($paths)) * 100
  713. : 0;
  714. $averageTime = rand(30, 60); // 模拟平均时间(分钟)
  715. return [
  716. 'active_paths' => $activePaths,
  717. 'completed_paths' => $completedPaths,
  718. 'average_efficiency_score' => $averageEfficiency,
  719. 'completion_rate' => $completionRate,
  720. 'average_time' => $averageTime,
  721. 'total_paths' => count($paths)
  722. ];
  723. } catch (\Exception $e) {
  724. Log::error('Get Learning Path Analytics Error', [
  725. 'student_id' => $studentId,
  726. 'error' => $e->getMessage()
  727. ]);
  728. return [
  729. 'active_paths' => 0,
  730. 'completed_paths' => 0,
  731. 'average_efficiency_score' => 0,
  732. 'completion_rate' => 0,
  733. 'average_time' => 0,
  734. 'total_paths' => 0
  735. ];
  736. }
  737. }
  738. /**
  739. * 快速分数预测
  740. */
  741. public function quickScorePrediction(string $studentId): array
  742. {
  743. Log::info('开始调用快速预测API', ['student_id' => $studentId]);
  744. $response = Http::timeout($this->timeout)
  745. ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction");
  746. Log::info('快速预测API响应', [
  747. 'student_id' => $studentId,
  748. 'status' => $response->status(),
  749. 'body' => $response->body()
  750. ]);
  751. if (!$response->successful()) {
  752. throw new \Exception(sprintf(
  753. '快速预测接口失败: %s %s',
  754. $response->status(),
  755. $response->body()
  756. ));
  757. }
  758. $data = $response->json();
  759. Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
  760. // API 返回结构:{ student_id, current_assumption, target_assumption, quick_prediction, prediction_id, message }
  761. $quickPredictionData = $data['quick_prediction'] ?? [];
  762. return [
  763. 'quick_prediction' => [
  764. 'current_score' => $quickPredictionData['current_score'] ?? $data['current_assumption'] ?? 0,
  765. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  766. 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? (($data['target_assumption'] ?? 0) - ($data['current_assumption'] ?? 0)),
  767. 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 0,
  768. 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0,
  769. 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
  770. 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
  771. 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
  772. 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
  773. ],
  774. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  775. 'confidence' => isset($quickPredictionData['confidence_level']) ? $quickPredictionData['confidence_level'] * 100 : 0,
  776. 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 0,
  777. 'prediction_id' => $data['prediction_id'] ?? null,
  778. 'message' => $data['message'] ?? null,
  779. ];
  780. }
  781. /**
  782. * 推荐学习路径
  783. */
  784. public function recommendLearningPaths(string $studentId, int $count = 3): array
  785. {
  786. try {
  787. Log::info('LearningAnalytics Request: Recommend Learning Paths', [
  788. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend?limit={$count}"
  789. ]);
  790. $response = Http::timeout($this->timeout)
  791. ->post($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend?limit={$count}");
  792. Log::info('LearningAnalytics Response: Recommend Learning Paths', [
  793. 'status' => $response->status(),
  794. 'body' => $response->json()
  795. ]);
  796. if ($response->successful()) {
  797. $data = $response->json()['recommendations'] ?? $response->json()['data'] ?? [];
  798. return [
  799. 'recommendations' => $data
  800. ];
  801. }
  802. return [
  803. 'recommendations' => []
  804. ];
  805. } catch (\Exception $e) {
  806. Log::error('Recommend Learning Paths Error', [
  807. 'student_id' => $studentId,
  808. 'error' => $e->getMessage()
  809. ]);
  810. return [
  811. 'recommendations' => []
  812. ];
  813. }
  814. }
  815. /**
  816. * 重新计算掌握度
  817. */
  818. public function recalculateMastery(string $studentId, string $kpCode): bool
  819. {
  820. try {
  821. Log::info('LearningAnalytics Request: Recalculate Mastery', [
  822. 'url' => $this->baseUrl . "/api/v1/mastery/recalculate/{$studentId}",
  823. 'kp_code' => $kpCode
  824. ]);
  825. $response = Http::timeout($this->timeout)
  826. ->post($this->baseUrl . "/api/v1/mastery/recalculate/{$studentId}", [
  827. 'student_id' => $studentId,
  828. 'kp_code' => $kpCode
  829. ]);
  830. Log::info('LearningAnalytics Response: Recalculate Mastery', [
  831. 'status' => $response->status(),
  832. 'body' => $response->body()
  833. ]);
  834. return $response->successful();
  835. } catch (\Exception $e) {
  836. Log::error('Recalculate Mastery Error', [
  837. 'student_id' => $studentId,
  838. 'kp_code' => $kpCode,
  839. 'error' => $e->getMessage()
  840. ]);
  841. return false;
  842. }
  843. }
  844. /**
  845. * 批量更新技能熟练度
  846. */
  847. public function batchUpdateSkillProficiency(string $studentId): bool
  848. {
  849. try {
  850. $response = Http::timeout($this->timeout)
  851. ->post($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}/batch-update", [
  852. 'student_id' => $studentId
  853. ]);
  854. return $response->successful();
  855. } catch (\Exception $e) {
  856. Log::error('Batch Update Skill Proficiency Error', [
  857. 'student_id' => $studentId,
  858. 'error' => $e->getMessage()
  859. ]);
  860. return false;
  861. }
  862. }
  863. /**
  864. * 清空学生所有答题数据
  865. */
  866. public function clearStudentData(string $studentId): bool
  867. {
  868. try {
  869. // 清空LearningAnalytics中的数据(通过API)
  870. $response = Http::timeout($this->timeout)
  871. ->delete($this->baseUrl . "/api/v1/student/{$studentId}/clear");
  872. if (!$response->successful()) {
  873. Log::error('Clear LearningAnalytics Data Failed', [
  874. 'student_id' => $studentId,
  875. 'status' => $response->status(),
  876. 'response' => $response->body()
  877. ]);
  878. }
  879. // 清空MySQL中的数据
  880. $this->clearStudentMySQLData($studentId);
  881. Log::info('Student Data Cleared Successfully', [
  882. 'student_id' => $studentId,
  883. 'api_success' => $response->successful()
  884. ]);
  885. return true;
  886. } catch (\Exception $e) {
  887. Log::error('Clear Student Data Error', [
  888. 'student_id' => $studentId,
  889. 'error' => $e->getMessage()
  890. ]);
  891. // 即使API失败,也要尝试清空本地数据
  892. try {
  893. $this->clearStudentMySQLData($studentId);
  894. return true;
  895. } catch (\Exception $localError) {
  896. Log::error('Clear Local Data Also Failed', [
  897. 'student_id' => $studentId,
  898. 'error' => $localError->getMessage()
  899. ]);
  900. return false;
  901. }
  902. }
  903. }
  904. /**
  905. * 清空学生MySQL中的答题数据
  906. */
  907. private function clearStudentMySQLData(string $studentId): void
  908. {
  909. try {
  910. // 清空student_exercises表
  911. DB::table('student_exercises')
  912. ->where('student_id', $studentId)
  913. ->delete();
  914. // 清空student_mastery表
  915. DB::table('student_mastery')
  916. ->where('student_id', $studentId)
  917. ->delete();
  918. Log::info('Student MySQL Data Cleared', [
  919. 'student_id' => $studentId
  920. ]);
  921. } catch (\Exception $e) {
  922. Log::error('Clear Student MySQL Data Error', [
  923. 'student_id' => $studentId,
  924. 'error' => $e->getMessage()
  925. ]);
  926. throw $e; // 重新抛出异常,让上层处理
  927. }
  928. }
  929. /**
  930. * 获取学生列表(供智能出卷使用)
  931. */
  932. public function getStudentsList(): array
  933. {
  934. try {
  935. $response = Http::timeout($this->timeout)
  936. ->get($this->baseUrl . '/api/v1/students/list');
  937. if ($response->successful()) {
  938. return $response->json('data', []);
  939. }
  940. // 如果API失败,尝试从MySQL直接读取
  941. return $this->getStudentsFromMySQL();
  942. } catch (\Exception $e) {
  943. Log::error('Get Students List Error', [
  944. 'error' => $e->getMessage()
  945. ]);
  946. // 返回模拟数据
  947. return [
  948. ['student_id' => 'stu_001', 'name' => '张三'],
  949. ['student_id' => 'stu_002', 'name' => '李四'],
  950. ['student_id' => 'stu_003', 'name' => '王五'],
  951. ];
  952. }
  953. }
  954. /**
  955. * 从MySQL获取学生列表
  956. */
  957. private function getStudentsFromMySQL(): array
  958. {
  959. try {
  960. return DB::table('students')
  961. ->select('student_id', 'name')
  962. ->limit(100)
  963. ->get()
  964. ->toArray();
  965. } catch (\Exception $e) {
  966. Log::error('Get Students From MySQL Error', [
  967. 'error' => $e->getMessage()
  968. ]);
  969. return [];
  970. }
  971. }
  972. /**
  973. * 获取学生薄弱点列表
  974. */
  975. public function getStudentWeaknesses(string $studentId, int $limit = 10): array
  976. {
  977. try {
  978. // 使用正确的API路径:/api/v1/student/{student_id}/weak-points
  979. $response = Http::timeout($this->timeout)
  980. ->get($this->baseUrl . "/api/v1/student/{$studentId}/weak-points");
  981. if ($response->successful()) {
  982. $data = $response->json('data', []);
  983. $weakPoints = $data['weak_points'] ?? [];
  984. // 转换为统一的格式
  985. return array_map(function ($item) use ($studentId) {
  986. return [
  987. 'kp_code' => $item['kp'] ?? '',
  988. 'kp_name' => $item['kp'] ?? '',
  989. 'mastery' => $item['mastery_level'] ?? 0,
  990. 'stability' => 0.5, // 默认稳定性
  991. 'weakness_level' => 1.0 - ($item['mastery_level'] ?? 0.5),
  992. 'practice_count' => $item['practice_count'] ?? 0,
  993. 'success_rate' => $item['success_rate'] ?? 0,
  994. 'priority' => $item['priority'] ?? '中',
  995. 'suggested_questions' => $item['suggested_questions'] ?? 0
  996. ];
  997. }, $weakPoints);
  998. }
  999. Log::warning('LearningAnalytics weaknesses API失败,使用本地MySQL数据', [
  1000. 'student_id' => $studentId,
  1001. 'status' => $response->status()
  1002. ]);
  1003. // API失败时,从MySQL直接查询
  1004. return $this->getStudentWeaknessesFromMySQL($studentId, $limit);
  1005. } catch (\Exception $e) {
  1006. Log::error('Get Student Weaknesses Error', [
  1007. 'student_id' => $studentId,
  1008. 'error' => $e->getMessage()
  1009. ]);
  1010. // 发生异常时,返回空数组,让前端可以继续使用默认值
  1011. return [];
  1012. }
  1013. }
  1014. /**
  1015. * 从MySQL获取学生薄弱点
  1016. */
  1017. private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
  1018. {
  1019. try {
  1020. $weaknesses = DB::table('student_mastery as sm')
  1021. ->join('knowledge_points as kp', 'sm.kp', '=', 'kp.kp')
  1022. ->where('sm.student_id', $studentId)
  1023. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  1024. ->orderBy('sm.mastery', 'asc')
  1025. ->limit($limit)
  1026. ->select([
  1027. 'sm.kp as kp_code',
  1028. 'kp.cn_name as kp_name',
  1029. 'sm.mastery',
  1030. 'sm.stability'
  1031. ])
  1032. ->get()
  1033. ->toArray();
  1034. return array_map(function ($item) {
  1035. return [
  1036. 'kp_code' => $item->kp_code,
  1037. 'kp_name' => $item->kp_name,
  1038. 'mastery' => (float) $item->mastery,
  1039. 'stability' => (float) $item->stability,
  1040. 'weakness_level' => 1.0 - (float) $item->mastery // 薄弱程度
  1041. ];
  1042. }, $weaknesses);
  1043. } catch (\Exception $e) {
  1044. Log::error('Get Student Weaknesses From MySQL Error', [
  1045. 'student_id' => $studentId,
  1046. 'error' => $e->getMessage()
  1047. ]);
  1048. return [];
  1049. }
  1050. }
  1051. /**
  1052. * 智能出卷:根据学生掌握度智能选择题目
  1053. */
  1054. public function generateIntelligentExam(array $params): array
  1055. {
  1056. $startTime = microtime(true);
  1057. try {
  1058. $studentId = $params['student_id'] ?? null;
  1059. $grade = $params['grade'] ?? null; // 用户选择的年级
  1060. $totalQuestions = $params['total_questions'] ?? 20;
  1061. $kpCodes = $params['kp_codes'] ?? [];
  1062. $skills = $params['skills'] ?? [];
  1063. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1064. '选择题' => 40,
  1065. '填空题' => 30,
  1066. '解答题' => 30,
  1067. ];
  1068. $difficultyRatio = $params['difficulty_ratio'] ?? [
  1069. '基础' => 50,
  1070. '中等' => 35,
  1071. '拔高' => 15,
  1072. ];
  1073. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1074. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1075. Log::info("generateIntelligentExam 开始", [
  1076. 'student_id' => $studentId,
  1077. 'total_questions' => $totalQuestions,
  1078. 'kp_codes' => $kpCodes,
  1079. 'skills' => $skills,
  1080. ]);
  1081. // 1. 如果指定了学生,获取学生的薄弱点
  1082. $weaknessFilter = [];
  1083. if ($studentId) {
  1084. Log::info("获取学生薄弱点: $studentId");
  1085. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1086. Log::info("薄弱点数量: " . count($weaknesses), [
  1087. '薄弱点' => $weaknesses,
  1088. ]);
  1089. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1090. // 如果用户没有指定知识点,使用学生的薄弱点
  1091. if (empty($kpCodes)) {
  1092. $kpCodes = $weaknessFilter;
  1093. Log::info("用户未选择知识点,使用薄弱点作为kp_codes", [
  1094. '最终kp_codes' => $kpCodes,
  1095. ]);
  1096. }
  1097. }
  1098. Log::info("准备调用 getQuestionsFromBank", [
  1099. 'kp_codes' => $kpCodes,
  1100. 'skills' => $skills,
  1101. ]);
  1102. // 2. 调用题库API获取符合条件的所有题目
  1103. try {
  1104. Log::info('开始调用 getQuestionsFromBank', [
  1105. 'kp_codes_count' => count($kpCodes),
  1106. 'skills_count' => count($skills)
  1107. ]);
  1108. $allQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId, $questionTypeRatio, $difficultyRatio, 200);
  1109. Log::info('getQuestionsFromBank 调用完成', [
  1110. 'questions_count' => count($allQuestions),
  1111. 'is_array' => is_array($allQuestions),
  1112. 'first_question_id' => !empty($allQuestions) ? ($allQuestions[0]['id'] ?? 'N/A') : 'N/A',
  1113. '耗时' => round((microtime(true) - $startTime) * 1000, 2) . 'ms',
  1114. ]);
  1115. Log::info('getQuestionsFromBank 返回', [
  1116. 'questions_count' => count($allQuestions),
  1117. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1118. ]);
  1119. } catch (\Exception $e) {
  1120. Log::error('getQuestionsFromBank 调用失败', [
  1121. 'error' => $e->getMessage(),
  1122. 'trace' => $e->getTraceAsString()
  1123. ]);
  1124. throw $e;
  1125. }
  1126. if (empty($allQuestions)) {
  1127. // 如果指定了知识点但题库为空,给出明确提示
  1128. if (!empty($kpCodes)) {
  1129. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1130. } else {
  1131. // 没有选择知识点时,从所有题目中选择
  1132. // 如果仍然没有题目,说明题库为空,提示补充题库
  1133. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1134. }
  1135. Log::warning('智能出卷失败 - 未找到题目', [
  1136. 'student_id' => $studentId,
  1137. 'selected_kp_codes' => $kpCodes,
  1138. 'kp_codes_count' => count($kpCodes),
  1139. 'message' => $message,
  1140. 'hint' => '如果选择了知识点但题库为空,请检查知识点代码是否正确,或尝试取消知识点选择'
  1141. ]);
  1142. return [
  1143. 'success' => false,
  1144. 'message' => $message,
  1145. 'questions' => []
  1146. ];
  1147. }
  1148. // 3. 根据掌握度对题目进行筛选和排序
  1149. Log::info('开始调用 selectQuestionsByMastery', [
  1150. 'input_count' => count($allQuestions),
  1151. 'target_count' => $totalQuestions
  1152. ]);
  1153. $startTime = microtime(true);
  1154. $selectedQuestions = $this->selectQuestionsByMastery(
  1155. $allQuestions,
  1156. $studentId,
  1157. $totalQuestions,
  1158. $questionTypeRatio,
  1159. $difficultyRatio,
  1160. $difficultyLevels,
  1161. $weaknessFilter
  1162. );
  1163. $selectTime = (microtime(true) - $startTime) * 1000;
  1164. Log::info('题目筛选结果', [
  1165. 'input_count' => count($allQuestions),
  1166. 'selected_count' => count($selectedQuestions),
  1167. 'target_count' => $totalQuestions,
  1168. 'select_time_ms' => round($selectTime, 2)
  1169. ]);
  1170. if (empty($selectedQuestions)) {
  1171. return [
  1172. 'success' => false,
  1173. 'message' => '题目筛选失败',
  1174. 'questions' => []
  1175. ];
  1176. }
  1177. return [
  1178. 'success' => true,
  1179. 'message' => '智能出卷成功',
  1180. 'questions' => $selectedQuestions,
  1181. 'stats' => [
  1182. 'total_selected' => count($selectedQuestions),
  1183. 'source_questions' => count($allQuestions),
  1184. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1185. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1186. })) : 0
  1187. ]
  1188. ];
  1189. } catch (\Exception $e) {
  1190. Log::error('Generate Intelligent Exam Error', [
  1191. 'error' => $e->getMessage(),
  1192. 'trace' => $e->getTraceAsString()
  1193. ]);
  1194. return [
  1195. 'success' => false,
  1196. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1197. 'questions' => []
  1198. ];
  1199. }
  1200. }
  1201. /**
  1202. * 从题库获取题目 - 使用智能选题API,直接根据要求筛选
  1203. */
  1204. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], array $difficultyRatio = [], int $totalNeeded = 100): array
  1205. {
  1206. try {
  1207. // 构建筛选条件
  1208. $filters = [];
  1209. // 知识点筛选
  1210. if (!empty($kpCodes)) {
  1211. $filters['kp_codes'] = $kpCodes;
  1212. }
  1213. // 技能筛选
  1214. if (!empty($skills)) {
  1215. $filters['skills'] = $skills;
  1216. }
  1217. // 题型配比
  1218. if (!empty($questionTypeRatio)) {
  1219. $filters['question_type_ratio'] = $questionTypeRatio;
  1220. }
  1221. // 难度配比
  1222. if (!empty($difficultyRatio)) {
  1223. $filters['difficulty_ratio'] = $difficultyRatio;
  1224. }
  1225. // 过滤学生做过的题目
  1226. if ($studentId) {
  1227. $filters['exclude_student_questions'] = $studentId;
  1228. }
  1229. // 从容器动态获取实例
  1230. if (!$this->questionBankService) {
  1231. $this->questionBankService = app(QuestionBankService::class);
  1232. }
  1233. // 调用智能选题API - 直接获取符合要求的题目
  1234. $questions = $this->questionBankService->selectQuestionsForExam($totalNeeded, $filters);
  1235. if (!empty($questions)) {
  1236. Log::info('从题库获取到题目,开始过滤解题思路', [
  1237. 'total_from_bank' => count($questions),
  1238. 'filters' => $filters
  1239. ]);
  1240. $filterStartTime = microtime(true);
  1241. $questionsWithSolution = [];
  1242. $noSolutionCount = 0;
  1243. foreach ($questions as $index => $q) {
  1244. try {
  1245. $solution = $q['solution'] ?? '';
  1246. // 处理 solution 可能是数组的情况
  1247. if (is_array($solution)) {
  1248. $solution = json_encode($solution, JSON_UNESCAPED_UNICODE);
  1249. }
  1250. if (!empty(trim($solution))) {
  1251. $questionsWithSolution[] = $q;
  1252. } else {
  1253. $noSolutionCount++;
  1254. }
  1255. } catch (\Exception $e) {
  1256. Log::error('过滤解题思路时出错', [
  1257. 'question_index' => $index,
  1258. 'error' => $e->getMessage()
  1259. ]);
  1260. }
  1261. }
  1262. $filterTime = (microtime(true) - $filterStartTime) * 1000;
  1263. $hasSolutionCount = count($questionsWithSolution);
  1264. Log::info('从题库智能获取题目', [
  1265. 'total_from_bank' => count($questions),
  1266. 'has_solution' => $hasSolutionCount,
  1267. 'no_solution' => $noSolutionCount,
  1268. 'filter_time_ms' => round($filterTime, 2),
  1269. 'filters' => $filters
  1270. ]);
  1271. if ($hasSolutionCount > 0) {
  1272. Log::info('返回有解题思路的题目', [
  1273. 'count' => $hasSolutionCount
  1274. ]);
  1275. return array_values($questionsWithSolution);
  1276. } else {
  1277. Log::warning('所有题目都没有解题思路,返回空数组', [
  1278. 'total_questions' => count($questions)
  1279. ]);
  1280. return [];
  1281. }
  1282. }
  1283. Log::warning('智能选题返回空结果', [
  1284. 'filters' => $filters
  1285. ]);
  1286. return [];
  1287. } catch (\Exception $e) {
  1288. Log::error('智能选题异常', [
  1289. 'error' => $e->getMessage()
  1290. ]);
  1291. }
  1292. return [];
  1293. }
  1294. /**
  1295. * 根据学生掌握度筛选题目
  1296. */
  1297. private function selectQuestionsByMastery(
  1298. array $questions,
  1299. ?string $studentId,
  1300. int $totalQuestions,
  1301. array $questionTypeRatio,
  1302. array $difficultyRatio,
  1303. array $difficultyLevels,
  1304. array $weaknessFilter
  1305. ): array {
  1306. Log::info('selectQuestionsByMastery 开始', [
  1307. 'question_count' => count($questions),
  1308. 'student_id' => $studentId,
  1309. 'total_questions' => $totalQuestions
  1310. ]);
  1311. // 如果未选择难度,则不过滤(随机生成所有难度)
  1312. if (empty($difficultyLevels)) {
  1313. Log::info('用户未选择难度,将随机生成所有难度的题目');
  1314. // 不过滤任何题目,保留所有难度
  1315. } else {
  1316. // 按难度筛掉不在选择范围内的题目
  1317. $questions = array_values(array_filter($questions, function ($q) use ($difficultyLevels) {
  1318. $d = $q['difficulty'] ?? null;
  1319. if ($d === null) return true; // 无难度信息则保留
  1320. $level = $this->mapDifficultyLevel((float)$d);
  1321. return in_array($level, $difficultyLevels);
  1322. }));
  1323. }
  1324. Log::info('难度筛选完成', [
  1325. 'after_filter_count' => count($questions)
  1326. ]);
  1327. // 1. 按知识点分组
  1328. Log::info('开始按知识点分组', [
  1329. 'question_count' => count($questions)
  1330. ]);
  1331. $groupStartTime = microtime(true);
  1332. $questionsByKp = [];
  1333. foreach ($questions as $question) {
  1334. $kpCode = $question['kp_code'] ?? '';
  1335. if (!isset($questionsByKp[$kpCode])) {
  1336. $questionsByKp[$kpCode] = [];
  1337. }
  1338. $questionsByKp[$kpCode][] = $question;
  1339. }
  1340. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1341. Log::info('按知识点分组完成', [
  1342. 'kp_count' => count($questionsByKp),
  1343. 'group_time_ms' => round($groupTime, 2)
  1344. ]);
  1345. // 2. 为每个知识点计算权重
  1346. $kpWeights = [];
  1347. $kpCodes = array_keys($questionsByKp);
  1348. Log::info('开始计算知识点权重', [
  1349. 'kp_count' => count($kpCodes),
  1350. 'student_id' => $studentId
  1351. ]);
  1352. $startTime = microtime(true);
  1353. $allMastery = [];
  1354. if ($studentId) {
  1355. // 批量获取所有知识点的掌握度(一次查询)
  1356. $masteryStart = microtime(true);
  1357. try {
  1358. $masteryRecords = DB::table('student_mastery')
  1359. ->where('student_id', $studentId)
  1360. ->whereIn('kp', $kpCodes)
  1361. ->pluck('mastery', 'kp')
  1362. ->all();
  1363. Log::debug('批量获取掌握度', [
  1364. 'student_id' => $studentId,
  1365. 'kp_count' => count($kpCodes),
  1366. 'found_count' => count($masteryRecords),
  1367. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1368. ]);
  1369. $allMastery = $masteryRecords;
  1370. } catch (\Exception $e) {
  1371. Log::warning('批量获取掌握度失败,将使用默认值', [
  1372. 'student_id' => $studentId,
  1373. 'error' => $e->getMessage()
  1374. ]);
  1375. }
  1376. }
  1377. foreach ($kpCodes as $kpCode) {
  1378. if ($studentId) {
  1379. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1380. // 薄弱点权重更高
  1381. if (in_array($kpCode, $weaknessFilter)) {
  1382. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1383. } else {
  1384. // 掌握度越低,权重越高
  1385. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1386. }
  1387. Log::debug('计算知识点权重', [
  1388. 'kp_code' => $kpCode,
  1389. 'mastery' => $mastery,
  1390. 'weight' => $kpWeights[$kpCode]
  1391. ]);
  1392. } else {
  1393. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1394. }
  1395. }
  1396. $totalWeightTime = (microtime(true) - $startTime) * 1000;
  1397. Log::info('知识点权重计算完成', [
  1398. 'total_kp_count' => count($kpCodes),
  1399. 'total_weight_time_ms' => round($totalWeightTime, 2),
  1400. 'avg_time_per_kp_ms' => count($kpCodes) > 0 ? round($totalWeightTime / count($kpCodes), 2) : 0
  1401. ]);
  1402. // 3. 按权重分配题目数量
  1403. $totalWeight = array_sum($kpWeights);
  1404. $selectedQuestions = [];
  1405. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1406. // 计算该知识点应该选择的题目数
  1407. $kpQuestionCount = max(1, round(($totalQuestions * $kpWeights[$kpCode]) / $totalWeight));
  1408. // 打乱题目顺序(避免固定模式)
  1409. shuffle($kpQuestions);
  1410. // 选择题目
  1411. $selectedFromKp = array_slice($kpQuestions, 0, $kpQuestionCount);
  1412. $selectedQuestions = array_merge($selectedQuestions, $selectedFromKp);
  1413. }
  1414. // 4. 如果题目过多,按权重排序后截取
  1415. if (count($selectedQuestions) > $totalQuestions) {
  1416. Log::info('开始按权重排序题目', [
  1417. 'before_sort_count' => count($selectedQuestions),
  1418. 'target_count' => $totalQuestions
  1419. ]);
  1420. $startTime = microtime(true);
  1421. usort($selectedQuestions, function ($a, $b) use ($kpWeights) {
  1422. $weightA = $kpWeights[$a['kp_code']] ?? 1.0;
  1423. $weightB = $kpWeights[$b['kp_code']] ?? 1.0;
  1424. return $weightB <=> $weightA;
  1425. });
  1426. $sortTime = (microtime(true) - $startTime) * 1000;
  1427. Log::info('权重排序完成', [
  1428. 'sort_time_ms' => round($sortTime, 2),
  1429. 'after_sort_count' => count($selectedQuestions)
  1430. ]);
  1431. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  1432. }
  1433. Log::info('开始题型配比调整', [
  1434. 'input_count' => count($selectedQuestions),
  1435. 'target_count' => $totalQuestions
  1436. ]);
  1437. // 5. 按题型和难度进行微调
  1438. return $this->adjustQuestionsByRatio($selectedQuestions, $questionTypeRatio, $difficultyRatio, $totalQuestions);
  1439. }
  1440. /**
  1441. * 获取学生对特定知识点的掌握度
  1442. */
  1443. private function getStudentKpMastery(string $studentId, string $kpCode): float
  1444. {
  1445. try {
  1446. $mastery = DB::table('student_mastery')
  1447. ->where('student_id', $studentId)
  1448. ->where('kp', $kpCode)
  1449. ->value('mastery');
  1450. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  1451. } catch (\Exception $e) {
  1452. Log::error('Get Student Kp Mastery Error', [
  1453. 'student_id' => $studentId,
  1454. 'kp_code' => $kpCode,
  1455. 'error' => $e->getMessage()
  1456. ]);
  1457. return 0.5;
  1458. }
  1459. }
  1460. /**
  1461. * 根据题型和难度配比调整题目
  1462. */
  1463. private function adjustQuestionsByRatio(array $questions, array $typeRatio, array $difficultyRatio, int $targetCount): array
  1464. {
  1465. Log::info('开始题型配比调整', [
  1466. 'input_questions' => count($questions),
  1467. 'target_count' => $targetCount,
  1468. 'type_ratio' => $typeRatio
  1469. ]);
  1470. // 缓存题目类型,避免重复计算
  1471. $questionTypeCache = [];
  1472. // 按题型分桶
  1473. $buckets = [
  1474. 'choice' => [],
  1475. 'fill' => [],
  1476. 'answer' => [],
  1477. ];
  1478. foreach ($questions as $q) {
  1479. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1480. if ($qid && isset($questionTypeCache[$qid])) {
  1481. $type = $questionTypeCache[$qid];
  1482. } else {
  1483. $type = $this->determineQuestionType($q);
  1484. if ($qid) {
  1485. $questionTypeCache[$qid] = $type;
  1486. }
  1487. }
  1488. if (!isset($buckets[$type])) {
  1489. $type = 'answer';
  1490. }
  1491. $buckets[$type][] = $q;
  1492. }
  1493. // 计算目标数(四舍五入,比例>0 则至少 1 道),并校正总数
  1494. $targetCount = min($targetCount, count($questions));
  1495. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  1496. Log::info('题型配比调整前桶统计', [
  1497. 'target_count' => $targetCount,
  1498. 'targets' => $targets,
  1499. 'bucket_counts' => [
  1500. 'choice' => count($buckets['choice']),
  1501. 'fill' => count($buckets['fill']),
  1502. 'answer' => count($buckets['answer']),
  1503. ],
  1504. 'raw_ratio' => $typeRatio,
  1505. ]);
  1506. // 随机打乱桶
  1507. foreach ($buckets as $k => $v) {
  1508. if (!empty($v)) {
  1509. shuffle($v);
  1510. $buckets[$k] = $v;
  1511. }
  1512. }
  1513. $selected = [];
  1514. $selectedIds = [];
  1515. // 按目标数依次取题
  1516. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  1517. $need = $targets[$typeKey] ?? 0;
  1518. if ($need <= 0 || empty($buckets[$typeKey])) {
  1519. continue;
  1520. }
  1521. $take = min($need, count($buckets[$typeKey]));
  1522. $slice = array_slice($buckets[$typeKey], 0, $take);
  1523. foreach ($slice as $q) {
  1524. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  1525. if (isset($selectedIds[$id])) {
  1526. continue;
  1527. }
  1528. $selected[] = $q;
  1529. $selectedIds[$id] = true;
  1530. }
  1531. }
  1532. // 不足则从剩余题中补齐
  1533. if (count($selected) < $targetCount) {
  1534. $remaining = [];
  1535. foreach ($buckets as $v) {
  1536. foreach ($v as $q) {
  1537. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  1538. if (!isset($selectedIds[$id])) {
  1539. $remaining[] = $q;
  1540. }
  1541. }
  1542. }
  1543. shuffle($remaining);
  1544. $needMore = $targetCount - count($selected);
  1545. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  1546. }
  1547. // 截断至目标数
  1548. $selected = array_slice($selected, 0, $targetCount);
  1549. // 使用缓存统计题型分布
  1550. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1551. foreach ($selected as $q) {
  1552. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1553. if ($qid && isset($questionTypeCache[$qid])) {
  1554. $type = $questionTypeCache[$qid];
  1555. } else {
  1556. $type = $this->determineQuestionType($q);
  1557. }
  1558. if (isset($selectedCounts[$type])) {
  1559. $selectedCounts[$type]++;
  1560. }
  1561. }
  1562. Log::info('题型配比调整完成', [
  1563. 'target_count' => $targetCount,
  1564. 'targets' => $targets,
  1565. 'selected_counts' => $selectedCounts,
  1566. 'final_selected_count' => count($selected)
  1567. ]);
  1568. return $selected;
  1569. }
  1570. private function determineQuestionType(array $q): string
  1571. {
  1572. // 优先根据题目内容判断(而不是数据库字段)
  1573. $stem = $q['stem'] ?? $q['content'] ?? '';
  1574. // 处理 stem 可能是数组的情况
  1575. if (is_array($stem)) {
  1576. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  1577. }
  1578. $tags = $q['tags'] ?? '';
  1579. // 处理 tags 可能是数组的情况
  1580. if (is_array($tags)) {
  1581. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  1582. }
  1583. $skills = $q['skills'] ?? [];
  1584. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  1585. if (is_string($stem)) {
  1586. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  1587. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1588. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1589. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1590. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1591. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  1592. // 至少有2个选项就认为是选择题(降低阈值)
  1593. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  1594. if ($optionCount >= 2) {
  1595. return 'choice';
  1596. }
  1597. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  1598. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  1599. return 'choice';
  1600. }
  1601. }
  1602. // 2. 根据技能点判断
  1603. if (is_array($skills) && !empty($skills)) {
  1604. // 过滤非字符串元素,避免 implode 报错
  1605. $skillsFiltered = array_filter($skills, 'is_string');
  1606. if (!empty($skillsFiltered)) {
  1607. $skillsStr = implode(',', $skillsFiltered);
  1608. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  1609. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  1610. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  1611. }
  1612. }
  1613. // 3. 根据题目已有类型字段判断(作为后备)
  1614. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  1615. if (is_string($typeField)) {
  1616. $t = strtolower($typeField);
  1617. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  1618. return 'choice';
  1619. }
  1620. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  1621. return 'fill';
  1622. }
  1623. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  1624. return 'answer';
  1625. }
  1626. }
  1627. // 4. 根据标签判断
  1628. if (is_string($tags)) {
  1629. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  1630. return 'choice';
  1631. }
  1632. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  1633. return 'fill';
  1634. }
  1635. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  1636. return 'answer';
  1637. }
  1638. }
  1639. // 5. 根据options字段判断
  1640. if (!empty($q['options']) && is_array($q['options'])) {
  1641. return 'choice';
  1642. }
  1643. // 6. 填空题特征:连续下划线或明显的填空括号
  1644. if (is_string($stem)) {
  1645. // 检查填空题特征:连续下划线
  1646. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  1647. return 'fill';
  1648. }
  1649. // 空括号填空
  1650. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  1651. return 'fill';
  1652. }
  1653. }
  1654. // 7. 根据题干内容关键词判断
  1655. if (is_string($stem)) {
  1656. // 有证明、解答、计算、求证等关键词的是解答题
  1657. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  1658. return 'answer';
  1659. }
  1660. }
  1661. // 默认是解答题(更安全的默认值)
  1662. return 'answer';
  1663. }
  1664. private function mapDifficultyLevel(float $d): string
  1665. {
  1666. if ($d <= 0.4) {
  1667. return '基础';
  1668. }
  1669. if ($d <= 0.7) {
  1670. return '中等';
  1671. }
  1672. return '拔高';
  1673. }
  1674. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  1675. {
  1676. $map = [
  1677. '选择题' => 'choice',
  1678. '填空题' => 'fill',
  1679. '解答题' => 'answer',
  1680. ];
  1681. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1682. foreach ($questionTypeRatio as $label => $ratio) {
  1683. $key = $map[$label] ?? null;
  1684. if (!$key) {
  1685. continue;
  1686. }
  1687. $cnt = (int) round($targetCount * ($ratio / 100));
  1688. if ($ratio > 0 && $cnt < 1) {
  1689. $cnt = 1;
  1690. }
  1691. $targets[$key] = $cnt;
  1692. }
  1693. $sum = array_sum($targets);
  1694. if ($sum === 0) {
  1695. $targets['answer'] = $targetCount;
  1696. return $targets;
  1697. }
  1698. while ($sum > $targetCount) {
  1699. arsort($targets);
  1700. foreach ($targets as $k => $v) {
  1701. if ($v > 1) {
  1702. $targets[$k]--;
  1703. $sum--;
  1704. break;
  1705. }
  1706. }
  1707. }
  1708. if ($sum < $targetCount) {
  1709. $ratioByKey = [
  1710. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  1711. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  1712. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  1713. ];
  1714. while ($sum < $targetCount) {
  1715. arsort($ratioByKey);
  1716. $k = array_key_first($ratioByKey);
  1717. $targets[$k]++;
  1718. $sum++;
  1719. }
  1720. }
  1721. return $targets;
  1722. }
  1723. /**
  1724. * 提交手动评分结果到 LearningAnalytics
  1725. *
  1726. * @param array $data 包含 student_id, paper_id, grades 的数组
  1727. * @return array
  1728. */
  1729. public function submitManualGrading(array $data): array
  1730. {
  1731. try {
  1732. $response = Http::timeout($this->timeout)
  1733. ->post($this->baseUrl . '/api/ocr/analyze', [
  1734. 'student_id' => $data['student_id'],
  1735. 'paper_id' => $data['paper_id'],
  1736. 'answers' => $data['grades'],
  1737. ]);
  1738. if ($response->successful()) {
  1739. Log::info('Manual grading submitted successfully', [
  1740. 'student_id' => $data['student_id'],
  1741. 'paper_id' => $data['paper_id'],
  1742. 'question_count' => count($data['grades'])
  1743. ]);
  1744. return $response->json();
  1745. }
  1746. Log::error('Submit Manual Grading Error', [
  1747. 'data' => $data,
  1748. 'status' => $response->status(),
  1749. 'response' => $response->body()
  1750. ]);
  1751. return [
  1752. 'error' => true,
  1753. 'message' => 'Failed to submit manual grading'
  1754. ];
  1755. } catch (\Exception $e) {
  1756. Log::error('Submit Manual Grading Exception', [
  1757. 'error' => $e->getMessage(),
  1758. 'data' => $data
  1759. ]);
  1760. return [
  1761. 'error' => true,
  1762. 'message' => $e->getMessage()
  1763. ];
  1764. }
  1765. }
  1766. /**
  1767. * 分析学生作答结果
  1768. *
  1769. * @param array $data 包含 paper_id, student_id, answers 等
  1770. * @return array
  1771. */
  1772. public function analyzeStudentAnswers(array $data): array
  1773. {
  1774. try {
  1775. $response = Http::timeout($this->timeout)
  1776. ->post($this->baseUrl . '/api/v1/analysis/submit-answers', [
  1777. 'paper_id' => $data['paper_id'],
  1778. 'student_id' => $data['student_id'],
  1779. 'answers' => $data['answers'],
  1780. 'submit_time' => $data['submit_time'] ?? now()->toISOString(),
  1781. ]);
  1782. if ($response->successful()) {
  1783. Log::info('Student answers analyzed successfully', [
  1784. 'student_id' => $data['student_id'],
  1785. 'paper_id' => $data['paper_id'],
  1786. 'answer_count' => count($data['answers'])
  1787. ]);
  1788. return [
  1789. 'success' => true,
  1790. 'data' => $response->json()
  1791. ];
  1792. }
  1793. Log::error('Analyze Student Answers Error', [
  1794. 'data' => $data,
  1795. 'status' => $response->status(),
  1796. 'response' => $response->body()
  1797. ]);
  1798. return [
  1799. 'success' => false,
  1800. 'message' => '分析失败:' . $response->body()
  1801. ];
  1802. } catch (\Exception $e) {
  1803. Log::error('Analyze Student Answers Exception', [
  1804. 'error' => $e->getMessage(),
  1805. 'data' => $data
  1806. ]);
  1807. return [
  1808. 'success' => false,
  1809. 'message' => $e->getMessage()
  1810. ];
  1811. }
  1812. }
  1813. }