LearningAnalyticsService.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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)
  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. $response = Http::timeout($this->timeout)->get($this->baseUrl . $endpoint);
  26. if ($response->successful()) {
  27. return $response->json();
  28. }
  29. Log::error('LearningAnalytics API Error', [
  30. 'endpoint' => $endpoint,
  31. 'status' => $response->status(),
  32. 'response' => $response->body()
  33. ]);
  34. return [
  35. 'error' => true,
  36. 'message' => 'Failed to fetch mastery data'
  37. ];
  38. } catch (\Exception $e) {
  39. Log::error('LearningAnalytics Service Exception', [
  40. 'error' => $e->getMessage(),
  41. 'trace' => $e->getTraceAsString()
  42. ]);
  43. return [
  44. 'error' => true,
  45. 'message' => $e->getMessage()
  46. ];
  47. }
  48. }
  49. /**
  50. * 更新学生掌握度
  51. */
  52. public function updateMastery(array $data): array
  53. {
  54. try {
  55. $response = Http::timeout($this->timeout)
  56. ->post($this->baseUrl . '/api/v1/mastery/student/' . $data['student_id'] . '/update', $data);
  57. if ($response->successful()) {
  58. return $response->json();
  59. }
  60. Log::error('LearningAnalytics Update Error', [
  61. 'data' => $data,
  62. 'status' => $response->status(),
  63. 'response' => $response->body()
  64. ]);
  65. return [
  66. 'error' => true,
  67. 'message' => 'Failed to update mastery'
  68. ];
  69. } catch (\Exception $e) {
  70. Log::error('LearningAnalytics Update Exception', [
  71. 'error' => $e->getMessage(),
  72. 'data' => $data
  73. ]);
  74. return [
  75. 'error' => true,
  76. 'message' => $e->getMessage()
  77. ];
  78. }
  79. }
  80. /**
  81. * 获取老师名下的所有学生
  82. */
  83. public function getTeacherStudents(string $teacherId): array
  84. {
  85. try {
  86. // 从本地MySQL获取学生
  87. $students = DB::table('students as s')
  88. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  89. ->where('s.teacher_id', $teacherId)
  90. ->select(
  91. 's.student_id',
  92. 's.name',
  93. 's.grade',
  94. 's.class_name',
  95. 'u.username',
  96. 'u.email'
  97. )
  98. ->get()
  99. ->toArray();
  100. return $students;
  101. } catch (\Exception $e) {
  102. Log::error('Get Teacher Students Error', [
  103. 'teacher_id' => $teacherId,
  104. 'error' => $e->getMessage()
  105. ]);
  106. return [];
  107. }
  108. }
  109. /**
  110. * 获取学生学习分析
  111. */
  112. public function getStudentAnalysis(string $studentId): array
  113. {
  114. // 从LearningAnalytics获取掌握度
  115. $masteryData = $this->getStudentMastery($studentId);
  116. // 从MySQL获取练习历史
  117. $exercises = DB::table('student_exercises')
  118. ->where('student_id', $studentId)
  119. ->orderBy('created_at', 'desc')
  120. ->limit(50)
  121. ->get()
  122. ->toArray();
  123. // 从MySQL获取掌握度记录
  124. $masteryRecords = DB::table('student_mastery')
  125. ->where('student_id', $studentId)
  126. ->get()
  127. ->toArray();
  128. return [
  129. 'student_id' => $studentId,
  130. 'mastery_from_la' => $masteryData,
  131. 'exercises' => $exercises,
  132. 'mastery_records' => $masteryRecords,
  133. 'total_exercises' => count($exercises),
  134. 'total_mastery_records' => count($masteryRecords),
  135. ];
  136. }
  137. /**
  138. * 生成学习测试数据
  139. */
  140. public function generateLearningData(string $studentId, array $params): array
  141. {
  142. $results = [];
  143. foreach ($params as $param) {
  144. $data = [
  145. 'student_id' => $studentId,
  146. 'kp_code' => $param['kp_code'],
  147. 'is_correct' => $param['is_correct'],
  148. 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
  149. 'difficulty_level' => $param['difficulty_level'] ?? 3,
  150. ];
  151. $result = $this->updateMastery($data);
  152. $results[] = $result;
  153. }
  154. return $results;
  155. }
  156. /**
  157. * 获取学习推荐
  158. */
  159. public function getLearningRecommendations(string $studentId): array
  160. {
  161. try {
  162. $response = Http::timeout($this->timeout)
  163. ->get($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
  164. if ($response->successful()) {
  165. return $response->json();
  166. }
  167. return ['error' => true, 'message' => 'Failed to fetch recommendations'];
  168. } catch (\Exception $e) {
  169. return ['error' => true, 'message' => $e->getMessage()];
  170. }
  171. }
  172. /**
  173. * 获取知识点列表(从知识图谱API)
  174. */
  175. public function getKnowledgePoints(array $filters = []): array
  176. {
  177. try {
  178. $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
  179. $response = Http::timeout($this->timeout)
  180. ->get($kgBaseUrl . '/knowledge-points/', $filters);
  181. if ($response->successful()) {
  182. return $response->json()['data'] ?? [];
  183. }
  184. return [];
  185. } catch (\Exception $e) {
  186. Log::error('LearningAnalytics Knowledge Points Error', [
  187. 'error' => $e->getMessage()
  188. ]);
  189. return [];
  190. }
  191. }
  192. /**
  193. * 获取学生技能熟练度
  194. */
  195. public function getStudentSkillProficiency(string $studentId): array
  196. {
  197. try {
  198. $response = Http::timeout($this->timeout)
  199. ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
  200. if ($response->successful()) {
  201. return $response->json();
  202. }
  203. Log::error('LearningAnalytics Skill Proficiency Error', [
  204. 'student_id' => $studentId,
  205. 'status' => $response->status(),
  206. 'response' => $response->body()
  207. ]);
  208. return [
  209. 'error' => true,
  210. 'message' => 'Failed to fetch skill proficiency'
  211. ];
  212. } catch (\Exception $e) {
  213. Log::error('LearningAnalytics Skill Proficiency Exception', [
  214. 'student_id' => $studentId,
  215. 'error' => $e->getMessage()
  216. ]);
  217. return [
  218. 'error' => true,
  219. 'message' => $e->getMessage()
  220. ];
  221. }
  222. }
  223. /**
  224. * 获取学生掌握度列表(别名方法)
  225. */
  226. public function getStudentMasteryList(string $studentId): array
  227. {
  228. return $this->getStudentMastery($studentId);
  229. }
  230. /**
  231. * 获取知识点依赖关系
  232. */
  233. public function getKnowledgeDependencies(): array
  234. {
  235. try {
  236. $response = Http::timeout($this->timeout)
  237. ->get($this->baseUrl . '/knowledge-dependencies/');
  238. if ($response->successful()) {
  239. return $response->json()['data'] ?? [];
  240. }
  241. return [];
  242. } catch (\Exception $e) {
  243. Log::error('LearningAnalytics Knowledge Dependencies Error', [
  244. 'error' => $e->getMessage()
  245. ]);
  246. return [];
  247. }
  248. }
  249. /**
  250. * 提交学生答题记录
  251. */
  252. public function submitAttempt(string $studentId, array $attemptData): array
  253. {
  254. try {
  255. $response = Http::timeout($this->timeout)
  256. ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
  257. if ($response->successful()) {
  258. return $response->json();
  259. }
  260. Log::error('Submit Attempt Error', [
  261. 'student_id' => $studentId,
  262. 'data' => $attemptData,
  263. 'status' => $response->status(),
  264. 'response' => $response->body()
  265. ]);
  266. return [
  267. 'error' => true,
  268. 'message' => 'Failed to submit attempt'
  269. ];
  270. } catch (\Exception $e) {
  271. Log::error('Submit Attempt Exception', [
  272. 'student_id' => $studentId,
  273. 'error' => $e->getMessage(),
  274. 'data' => $attemptData
  275. ]);
  276. return [
  277. 'error' => true,
  278. 'message' => $e->getMessage()
  279. ];
  280. }
  281. }
  282. /**
  283. * 检查服务健康状态
  284. */
  285. public function checkHealth(): bool
  286. {
  287. try {
  288. $response = Http::timeout(5)->get($this->baseUrl . '/health');
  289. return $response->successful();
  290. } catch (\Exception $e) {
  291. return false;
  292. }
  293. }
  294. /**
  295. * 获取学生掌握度概览
  296. */
  297. public function getStudentMasteryOverview(string $studentId): array
  298. {
  299. try {
  300. $mastery = $this->getStudentMastery($studentId);
  301. if (isset($mastery['error'])) {
  302. return [
  303. 'total_knowledge_points' => 0,
  304. 'average_mastery_level' => 0,
  305. 'mastered_knowledge_points' => 0,
  306. 'good_knowledge_points' => 0,
  307. 'weak_knowledge_points' => 0,
  308. 'weak_knowledge_points_list' => [],
  309. 'details' => []
  310. ];
  311. }
  312. $data = $mastery['data'] ?? [];
  313. // 过滤出有实际答题记录的知识点
  314. $attemptedData = array_filter($data, function($item) {
  315. return ($item['total_attempts'] ?? 0) > 0;
  316. });
  317. $total = count($data); // 总知识点数(包括未学习的)
  318. $attemptedCount = count($attemptedData); // 已学习的知识点数
  319. $average = $attemptedCount > 0
  320. ? array_sum(array_column($attemptedData, 'mastery_level')) / $attemptedCount
  321. : 0;
  322. // 分类知识点(只对有记录的知识点进行分类)
  323. $mastered = []; // ≥ 85%
  324. $good = []; // 70-84%
  325. $weak = []; // < 70%
  326. foreach ($attemptedData as $item) {
  327. $level = $item['mastery_level'] ?? 0;
  328. if ($level >= 0.85) {
  329. $mastered[] = $item;
  330. } elseif ($level >= 0.70) {
  331. $good[] = $item;
  332. } else {
  333. $weak[] = $item;
  334. }
  335. }
  336. return [
  337. 'total_knowledge_points' => $total,
  338. 'average_mastery_level' => $average,
  339. 'mastered_knowledge_points' => count($mastered),
  340. 'good_knowledge_points' => count($good),
  341. 'weak_knowledge_points' => count($weak),
  342. 'weak_knowledge_points_list' => $weak,
  343. 'details' => $data
  344. ];
  345. } catch (\Exception $e) {
  346. Log::error('Get Student Mastery Overview Error', [
  347. 'student_id' => $studentId,
  348. 'error' => $e->getMessage()
  349. ]);
  350. return [
  351. 'total_knowledge_points' => 0,
  352. 'average_mastery_level' => 0,
  353. 'mastered_knowledge_points' => 0,
  354. 'good_knowledge_points' => 0,
  355. 'weak_knowledge_points' => 0,
  356. 'weak_knowledge_points_list' => [],
  357. 'details' => []
  358. ];
  359. }
  360. }
  361. /**
  362. * 获取学生技能摘要
  363. */
  364. public function getStudentSkillSummary(string $studentId): array
  365. {
  366. try {
  367. $proficiency = $this->getStudentSkillProficiency($studentId);
  368. if (isset($proficiency['error'])) {
  369. return [
  370. 'total_skills' => 0,
  371. 'average_proficiency_level' => 0,
  372. 'total_questions_attempted' => 0,
  373. 'skill_list' => []
  374. ];
  375. }
  376. $data = $proficiency['data'] ?? [];
  377. $totalSkills = count($data);
  378. $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
  379. // 计算总答题数
  380. $totalQuestions = 0;
  381. foreach ($data as $skill) {
  382. $totalQuestions += $skill['total_questions_attempted'] ?? 0;
  383. }
  384. return [
  385. 'total_skills' => $totalSkills,
  386. 'average_proficiency_level' => $averageLevel,
  387. 'total_questions_attempted' => $totalQuestions,
  388. 'skill_list' => $data
  389. ];
  390. } catch (\Exception $e) {
  391. Log::error('Get Student Skill Summary Error', [
  392. 'student_id' => $studentId,
  393. 'error' => $e->getMessage()
  394. ]);
  395. return [
  396. 'total_skills' => 0,
  397. 'average_proficiency_level' => 0,
  398. 'total_questions_attempted' => 0,
  399. 'skill_list' => []
  400. ];
  401. }
  402. }
  403. /**
  404. * 获取学生预测数据
  405. */
  406. public function getStudentPredictions(string $studentId, int $count = 5): array
  407. {
  408. try {
  409. $response = Http::timeout($this->timeout)
  410. ->get($this->baseUrl . "/api/v1/prediction/student/{$studentId}?count={$count}");
  411. if ($response->successful()) {
  412. $data = $response->json();
  413. $predictions = $data['predictions'] ?? $data['data'] ?? [];
  414. return [
  415. 'predictions' => $predictions
  416. ];
  417. }
  418. return [
  419. 'predictions' => []
  420. ];
  421. } catch (\Exception $e) {
  422. Log::error('Get Student Predictions Error', [
  423. 'student_id' => $studentId,
  424. 'error' => $e->getMessage()
  425. ]);
  426. return [
  427. 'predictions' => []
  428. ];
  429. }
  430. }
  431. /**
  432. * 获取学生学习路径
  433. */
  434. public function getStudentLearningPaths(string $studentId, int $count = 3): array
  435. {
  436. try {
  437. $response = Http::timeout($this->timeout)
  438. ->get($this->baseUrl . "/api/v1/learning-path/student/{$studentId}?count={$count}");
  439. if ($response->successful()) {
  440. $data = $response->json()['data'] ?? [];
  441. return [
  442. 'paths' => $data
  443. ];
  444. }
  445. return [
  446. 'paths' => []
  447. ];
  448. } catch (\Exception $e) {
  449. Log::error('Get Student Learning Paths Error', [
  450. 'student_id' => $studentId,
  451. 'error' => $e->getMessage()
  452. ]);
  453. return [
  454. 'paths' => []
  455. ];
  456. }
  457. }
  458. /**
  459. * 获取预测分析数据
  460. */
  461. public function getPredictionAnalytics(string $studentId): array
  462. {
  463. try {
  464. $predictions = $this->getStudentPredictions($studentId, 10);
  465. if (empty($predictions)) {
  466. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  467. }
  468. $accuracy = 0;
  469. $confidence = 0;
  470. if (!empty($predictions)) {
  471. $accuracy = rand(75, 95); // 模拟准确率
  472. $confidence = rand(70, 90); // 模拟置信度
  473. }
  474. $trend = 'improving'; // improving, stable, declining
  475. return [
  476. 'accuracy' => $accuracy,
  477. 'trend' => $trend,
  478. 'confidence' => $confidence,
  479. 'sample_size' => count($predictions)
  480. ];
  481. } catch (\Exception $e) {
  482. Log::error('Get Prediction Analytics Error', [
  483. 'student_id' => $studentId,
  484. 'error' => $e->getMessage()
  485. ]);
  486. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  487. }
  488. }
  489. /**
  490. * 获取学习路径分析数据
  491. */
  492. public function getLearningPathAnalytics(string $studentId): array
  493. {
  494. try {
  495. $paths = $this->getStudentLearningPaths($studentId, 5);
  496. if (empty($paths)) {
  497. return [
  498. 'active_paths' => 0,
  499. 'completed_paths' => 0,
  500. 'average_efficiency_score' => 0,
  501. 'completion_rate' => 0,
  502. 'average_time' => 0,
  503. 'total_paths' => 0
  504. ];
  505. }
  506. $activePaths = 0;
  507. $completedPaths = 0;
  508. $efficiencyScores = [];
  509. foreach ($paths as $path) {
  510. if (($path['status'] ?? '') === 'active') {
  511. $activePaths++;
  512. }
  513. if (($path['status'] ?? '') === 'completed') {
  514. $completedPaths++;
  515. }
  516. if (isset($path['efficiency_score'])) {
  517. $efficiencyScores[] = $path['efficiency_score'];
  518. }
  519. }
  520. $averageEfficiency = !empty($efficiencyScores)
  521. ? array_sum($efficiencyScores) / count($efficiencyScores)
  522. : rand(60, 85) / 100;
  523. $completionRate = count($paths) > 0
  524. ? ($completedPaths / count($paths)) * 100
  525. : 0;
  526. $averageTime = rand(30, 60); // 模拟平均时间(分钟)
  527. return [
  528. 'active_paths' => $activePaths,
  529. 'completed_paths' => $completedPaths,
  530. 'average_efficiency_score' => $averageEfficiency,
  531. 'completion_rate' => $completionRate,
  532. 'average_time' => $averageTime,
  533. 'total_paths' => count($paths)
  534. ];
  535. } catch (\Exception $e) {
  536. Log::error('Get Learning Path Analytics Error', [
  537. 'student_id' => $studentId,
  538. 'error' => $e->getMessage()
  539. ]);
  540. return [
  541. 'active_paths' => 0,
  542. 'completed_paths' => 0,
  543. 'average_efficiency_score' => 0,
  544. 'completion_rate' => 0,
  545. 'average_time' => 0,
  546. 'total_paths' => 0
  547. ];
  548. }
  549. }
  550. /**
  551. * 快速分数预测
  552. */
  553. public function quickScorePrediction(string $studentId): array
  554. {
  555. Log::info('开始调用快速预测API', ['student_id' => $studentId]);
  556. try {
  557. $response = Http::timeout($this->timeout)
  558. ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction", [
  559. 'student_id' => $studentId
  560. ]);
  561. Log::info('快速预测API响应', [
  562. 'student_id' => $studentId,
  563. 'status' => $response->status(),
  564. 'body' => $response->body()
  565. ]);
  566. if ($response->successful()) {
  567. $data = $response->json();
  568. Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
  569. // API直接返回数据,没有嵌套在'data'键中
  570. $quickPredictionData = $data['quick_prediction'] ?? [];
  571. return [
  572. 'quick_prediction' => [
  573. 'current_score' => $quickPredictionData['current_score'] ?? 70,
  574. 'predicted_score' => $quickPredictionData['predicted_score'] ?? 75,
  575. 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? 5,
  576. 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 15,
  577. 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0.75,
  578. 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
  579. 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
  580. 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
  581. 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
  582. ],
  583. 'predicted_score' => $quickPredictionData['predicted_score'] ?? 75,
  584. 'confidence' => $quickPredictionData['confidence_level'] ? $quickPredictionData['confidence_level'] * 100 : 75,
  585. 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 15
  586. ];
  587. }
  588. Log::warning('快速预测API调用失败', [
  589. 'student_id' => $studentId,
  590. 'status' => $response->status(),
  591. 'response' => $response->body()
  592. ]);
  593. return [
  594. 'quick_prediction' => [
  595. 'improvement_potential' => 0,
  596. 'estimated_study_hours' => 0,
  597. 'confidence_level' => 0
  598. ],
  599. 'predicted_score' => 0,
  600. 'confidence' => 0,
  601. 'time_estimate' => 0
  602. ];
  603. } catch (\Exception $e) {
  604. Log::error('Quick Score Prediction Error', [
  605. 'student_id' => $studentId,
  606. 'error' => $e->getMessage()
  607. ]);
  608. return [
  609. 'quick_prediction' => [
  610. 'improvement_potential' => 0,
  611. 'estimated_study_hours' => 0,
  612. 'confidence_level' => 0
  613. ],
  614. 'predicted_score' => 0,
  615. 'confidence' => 0,
  616. 'time_estimate' => 0
  617. ];
  618. }
  619. }
  620. /**
  621. * 推荐学习路径
  622. */
  623. public function recommendLearningPaths(string $studentId, int $count = 3): array
  624. {
  625. try {
  626. $response = Http::timeout($this->timeout)
  627. ->get($this->baseUrl . "/api/v1/learning-path/recommend/{$studentId}?count={$count}");
  628. if ($response->successful()) {
  629. $data = $response->json()['data'] ?? [];
  630. return [
  631. 'recommendations' => $data
  632. ];
  633. }
  634. return [
  635. 'recommendations' => []
  636. ];
  637. } catch (\Exception $e) {
  638. Log::error('Recommend Learning Paths Error', [
  639. 'student_id' => $studentId,
  640. 'error' => $e->getMessage()
  641. ]);
  642. return [
  643. 'recommendations' => []
  644. ];
  645. }
  646. }
  647. /**
  648. * 重新计算掌握度
  649. */
  650. public function recalculateMastery(string $studentId, string $kpCode): bool
  651. {
  652. try {
  653. $response = Http::timeout($this->timeout)
  654. ->post($this->baseUrl . "/api/v1/mastery/recalculate/{$studentId}", [
  655. 'student_id' => $studentId,
  656. 'kp_code' => $kpCode
  657. ]);
  658. return $response->successful();
  659. } catch (\Exception $e) {
  660. Log::error('Recalculate Mastery Error', [
  661. 'student_id' => $studentId,
  662. 'kp_code' => $kpCode,
  663. 'error' => $e->getMessage()
  664. ]);
  665. return false;
  666. }
  667. }
  668. /**
  669. * 批量更新技能熟练度
  670. */
  671. public function batchUpdateSkillProficiency(string $studentId): bool
  672. {
  673. try {
  674. $response = Http::timeout($this->timeout)
  675. ->post($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}/batch-update", [
  676. 'student_id' => $studentId
  677. ]);
  678. return $response->successful();
  679. } catch (\Exception $e) {
  680. Log::error('Batch Update Skill Proficiency Error', [
  681. 'student_id' => $studentId,
  682. 'error' => $e->getMessage()
  683. ]);
  684. return false;
  685. }
  686. }
  687. /**
  688. * 清空学生所有答题数据
  689. */
  690. public function clearStudentData(string $studentId): bool
  691. {
  692. try {
  693. // 清空LearningAnalytics中的数据(通过API)
  694. $response = Http::timeout($this->timeout)
  695. ->delete($this->baseUrl . "/api/v1/student/{$studentId}/clear");
  696. if (!$response->successful()) {
  697. Log::error('Clear LearningAnalytics Data Failed', [
  698. 'student_id' => $studentId,
  699. 'status' => $response->status(),
  700. 'response' => $response->body()
  701. ]);
  702. }
  703. // 清空MySQL中的数据
  704. $this->clearStudentMySQLData($studentId);
  705. Log::info('Student Data Cleared Successfully', [
  706. 'student_id' => $studentId,
  707. 'api_success' => $response->successful()
  708. ]);
  709. return true;
  710. } catch (\Exception $e) {
  711. Log::error('Clear Student Data Error', [
  712. 'student_id' => $studentId,
  713. 'error' => $e->getMessage()
  714. ]);
  715. // 即使API失败,也要尝试清空本地数据
  716. try {
  717. $this->clearStudentMySQLData($studentId);
  718. return true;
  719. } catch (\Exception $localError) {
  720. Log::error('Clear Local Data Also Failed', [
  721. 'student_id' => $studentId,
  722. 'error' => $localError->getMessage()
  723. ]);
  724. return false;
  725. }
  726. }
  727. }
  728. /**
  729. * 清空学生MySQL中的答题数据
  730. */
  731. private function clearStudentMySQLData(string $studentId): void
  732. {
  733. try {
  734. // 清空student_exercises表
  735. DB::table('student_exercises')
  736. ->where('student_id', $studentId)
  737. ->delete();
  738. // 清空student_mastery表
  739. DB::table('student_mastery')
  740. ->where('student_id', $studentId)
  741. ->delete();
  742. Log::info('Student MySQL Data Cleared', [
  743. 'student_id' => $studentId
  744. ]);
  745. } catch (\Exception $e) {
  746. Log::error('Clear Student MySQL Data Error', [
  747. 'student_id' => $studentId,
  748. 'error' => $e->getMessage()
  749. ]);
  750. throw $e; // 重新抛出异常,让上层处理
  751. }
  752. }
  753. /**
  754. * 获取学生列表(供智能出卷使用)
  755. */
  756. public function getStudentsList(): array
  757. {
  758. try {
  759. $response = Http::timeout($this->timeout)
  760. ->get($this->baseUrl . '/api/v1/students/list');
  761. if ($response->successful()) {
  762. return $response->json('data', []);
  763. }
  764. // 如果API失败,尝试从MySQL直接读取
  765. return $this->getStudentsFromMySQL();
  766. } catch (\Exception $e) {
  767. Log::error('Get Students List Error', [
  768. 'error' => $e->getMessage()
  769. ]);
  770. // 返回模拟数据
  771. return [
  772. ['student_id' => 'stu_001', 'name' => '张三'],
  773. ['student_id' => 'stu_002', 'name' => '李四'],
  774. ['student_id' => 'stu_003', 'name' => '王五'],
  775. ];
  776. }
  777. }
  778. /**
  779. * 从MySQL获取学生列表
  780. */
  781. private function getStudentsFromMySQL(): array
  782. {
  783. try {
  784. return DB::table('students')
  785. ->select('student_id', 'name')
  786. ->limit(100)
  787. ->get()
  788. ->toArray();
  789. } catch (\Exception $e) {
  790. Log::error('Get Students From MySQL Error', [
  791. 'error' => $e->getMessage()
  792. ]);
  793. return [];
  794. }
  795. }
  796. /**
  797. * 获取学生薄弱点列表
  798. */
  799. public function getStudentWeaknesses(string $studentId, int $limit = 10): array
  800. {
  801. try {
  802. $response = Http::timeout($this->timeout)
  803. ->get($this->baseUrl . "/api/v1/analysis/weaknesses/{$studentId}?limit={$limit}");
  804. if ($response->successful()) {
  805. return $response->json('data', []);
  806. }
  807. // API失败时,从MySQL直接查询
  808. return $this->getStudentWeaknessesFromMySQL($studentId, $limit);
  809. } catch (\Exception $e) {
  810. Log::error('Get Student Weaknesses Error', [
  811. 'student_id' => $studentId,
  812. 'error' => $e->getMessage()
  813. ]);
  814. return [];
  815. }
  816. }
  817. /**
  818. * 从MySQL获取学生薄弱点
  819. */
  820. private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
  821. {
  822. try {
  823. $weaknesses = DB::table('student_mastery as sm')
  824. ->join('knowledge_points as kp', 'sm.kp', '=', 'kp.kp')
  825. ->where('sm.student_id', $studentId)
  826. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  827. ->orderBy('sm.mastery', 'asc')
  828. ->limit($limit)
  829. ->select([
  830. 'sm.kp as kp_code',
  831. 'kp.cn_name as kp_name',
  832. 'sm.mastery',
  833. 'sm.stability'
  834. ])
  835. ->get()
  836. ->toArray();
  837. return array_map(function ($item) {
  838. return [
  839. 'kp_code' => $item->kp_code,
  840. 'kp_name' => $item->kp_name,
  841. 'mastery' => (float) $item->mastery,
  842. 'stability' => (float) $item->stability,
  843. 'weakness_level' => 1.0 - (float) $item->mastery // 薄弱程度
  844. ];
  845. }, $weaknesses);
  846. } catch (\Exception $e) {
  847. Log::error('Get Student Weaknesses From MySQL Error', [
  848. 'student_id' => $studentId,
  849. 'error' => $e->getMessage()
  850. ]);
  851. return [];
  852. }
  853. }
  854. /**
  855. * 智能出卷:根据学生掌握度智能选择题目
  856. */
  857. public function generateIntelligentExam(array $params): array
  858. {
  859. try {
  860. $studentId = $params['student_id'] ?? null;
  861. $totalQuestions = $params['total_questions'] ?? 20;
  862. $kpCodes = $params['kp_codes'] ?? [];
  863. $skills = $params['skills'] ?? [];
  864. $questionTypeRatio = $params['question_type_ratio'] ?? [
  865. '选择题' => 40,
  866. '填空题' => 30,
  867. '解答题' => 30,
  868. ];
  869. $difficultyRatio = $params['difficulty_ratio'] ?? [
  870. '基础' => 50,
  871. '中等' => 35,
  872. '拔高' => 15,
  873. ];
  874. // 1. 如果指定了学生,获取学生的薄弱点
  875. $weaknessFilter = [];
  876. if ($studentId) {
  877. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  878. $weaknessFilter = array_column($weaknesses, 'kp_code');
  879. // 如果用户没有指定知识点,使用学生的薄弱点
  880. if (empty($kpCodes)) {
  881. $kpCodes = $weaknessFilter;
  882. }
  883. }
  884. // 如果仍然没有知识点(例如新学生无薄弱点),根据年级从知识图谱获取知识点
  885. if (empty($kpCodes)) {
  886. $filters = [];
  887. if ($studentId) {
  888. $student = \App\Models\Student::find($studentId);
  889. if ($student && $student->grade) {
  890. $grade = $student->grade;
  891. $standardizedGrade = $grade;
  892. // 标准化年级名称并更新数据库
  893. if ($grade === '初一') {
  894. $standardizedGrade = '七年级';
  895. } elseif ($grade === '初二') {
  896. $standardizedGrade = '八年级';
  897. } elseif ($grade === '初三') {
  898. $standardizedGrade = '九年级';
  899. }
  900. if ($standardizedGrade !== $grade) {
  901. $student->grade = $standardizedGrade;
  902. $student->save();
  903. Log::info('Standardized student grade', ['student_id' => $studentId, 'old' => $grade, 'new' => $standardizedGrade]);
  904. $grade = $standardizedGrade;
  905. }
  906. // 映射年级到学段 (phase)
  907. if (str_contains($grade, '初') || str_contains($grade, '七年级') || str_contains($grade, '八年级') || str_contains($grade, '九年级')) {
  908. $filters['phase'] = '初中';
  909. } elseif (str_contains($grade, '高')) {
  910. $filters['phase'] = '高中';
  911. }
  912. }
  913. }
  914. // 调用API获取过滤后的知识点
  915. $filteredKps = $this->getKnowledgePoints($filters);
  916. if (!empty($filteredKps)) {
  917. // 随机选择 5 个知识点
  918. $kpKeys = array_column($filteredKps, 'kp_code');
  919. if (empty($kpKeys)) {
  920. $kpKeys = array_column($filteredKps, 'code');
  921. }
  922. if (!empty($kpKeys)) {
  923. $randomKeys = array_rand(array_flip($kpKeys), min(5, count($kpKeys)));
  924. $kpCodes = is_array($randomKeys) ? $randomKeys : [$randomKeys];
  925. Log::info('Randomly selected KPs for student based on grade (API)', [
  926. 'student_id' => $studentId,
  927. 'grade' => $student->grade ?? 'unknown',
  928. 'filters' => $filters,
  929. 'kps' => $kpCodes
  930. ]);
  931. }
  932. }
  933. }
  934. // 2. 调用题库API获取符合条件的所有题目
  935. $allQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId);
  936. if (empty($allQuestions)) {
  937. return [
  938. 'success' => false,
  939. 'message' => '未找到符合条件的题目',
  940. 'questions' => []
  941. ];
  942. }
  943. // 3. 根据掌握度对题目进行筛选和排序
  944. $selectedQuestions = $this->selectQuestionsByMastery(
  945. $allQuestions,
  946. $studentId,
  947. $totalQuestions,
  948. $questionTypeRatio,
  949. $difficultyRatio,
  950. $weaknessFilter
  951. );
  952. if (empty($selectedQuestions)) {
  953. return [
  954. 'success' => false,
  955. 'message' => '题目筛选失败',
  956. 'questions' => []
  957. ];
  958. }
  959. return [
  960. 'success' => true,
  961. 'message' => '智能出卷成功',
  962. 'questions' => $selectedQuestions,
  963. 'stats' => [
  964. 'total_selected' => count($selectedQuestions),
  965. 'source_questions' => count($allQuestions),
  966. 'weakness_targeted' => $studentId ? count(array_intersect(array_column($selectedQuestions, 'kp_code'), $weaknessFilter)) : 0
  967. ]
  968. ];
  969. } catch (\Exception $e) {
  970. Log::error('Generate Intelligent Exam Error', [
  971. 'error' => $e->getMessage(),
  972. 'trace' => $e->getTraceAsString()
  973. ]);
  974. return [
  975. 'success' => false,
  976. 'message' => '智能出卷异常: ' . $e->getMessage(),
  977. 'questions' => []
  978. ];
  979. }
  980. }
  981. /**
  982. * 从题库获取题目
  983. */
  984. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId): array
  985. {
  986. try {
  987. // 构建查询参数
  988. $params = [
  989. 'kp_codes' => implode(',', $kpCodes),
  990. 'limit' => 1000 // 获取足够多的题目用于筛选
  991. ];
  992. if (!empty($skills)) {
  993. $params['skills'] = implode(',', $skills);
  994. }
  995. if ($studentId) {
  996. $params['exclude_student_questions'] = $studentId; // 过滤学生做过的题目
  997. }
  998. // 调用QuestionBank API
  999. // 使用 QuestionBankService 获取题目 (使用 filterQuestions 方法以支持 kp_codes)
  1000. $response = $this->questionBankService->filterQuestions($params);
  1001. if (!empty($response['data'])) {
  1002. return $response['data'];
  1003. }
  1004. Log::warning('Get Questions From Bank Failed or Empty', [
  1005. 'params' => $params,
  1006. 'response' => $response
  1007. ]);
  1008. return [];
  1009. } catch (\Exception $e) {
  1010. Log::error('Get Questions From Bank Error', [
  1011. 'error' => $e->getMessage()
  1012. ]);
  1013. }
  1014. return [];
  1015. }
  1016. /**
  1017. * 根据学生掌握度筛选题目
  1018. */
  1019. private function selectQuestionsByMastery(
  1020. array $questions,
  1021. ?string $studentId,
  1022. int $totalQuestions,
  1023. array $questionTypeRatio,
  1024. array $difficultyRatio,
  1025. array $weaknessFilter
  1026. ): array {
  1027. // 1. 按知识点分组
  1028. $questionsByKp = [];
  1029. foreach ($questions as $question) {
  1030. $kpCode = $question['kp_code'] ?? '';
  1031. if (!isset($questionsByKp[$kpCode])) {
  1032. $questionsByKp[$kpCode] = [];
  1033. }
  1034. $questionsByKp[$kpCode][] = $question;
  1035. }
  1036. // 2. 为每个知识点计算权重
  1037. $kpWeights = [];
  1038. foreach (array_keys($questionsByKp) as $kpCode) {
  1039. if ($studentId) {
  1040. // 获取学生对该知识点的掌握度
  1041. $mastery = $this->getStudentKpMastery($studentId, $kpCode);
  1042. // 薄弱点权重更高
  1043. if (in_array($kpCode, $weaknessFilter)) {
  1044. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1045. } else {
  1046. // 掌握度越低,权重越高
  1047. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1048. }
  1049. } else {
  1050. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1051. }
  1052. }
  1053. // 3. 按权重分配题目数量
  1054. $totalWeight = array_sum($kpWeights);
  1055. $selectedQuestions = [];
  1056. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1057. // 计算该知识点应该选择的题目数
  1058. $kpQuestionCount = max(1, round(($totalQuestions * $kpWeights[$kpCode]) / $totalWeight));
  1059. // 打乱题目顺序(避免固定模式)
  1060. shuffle($kpQuestions);
  1061. // 选择题目
  1062. $selectedFromKp = array_slice($kpQuestions, 0, $kpQuestionCount);
  1063. $selectedQuestions = array_merge($selectedQuestions, $selectedFromKp);
  1064. }
  1065. // 4. 如果题目过多,按权重排序后截取
  1066. if (count($selectedQuestions) > $totalQuestions) {
  1067. usort($selectedQuestions, function ($a, $b) use ($kpWeights) {
  1068. $weightA = $kpWeights[$a['kp_code']] ?? 1.0;
  1069. $weightB = $kpWeights[$b['kp_code']] ?? 1.0;
  1070. return $weightB <=> $weightA;
  1071. });
  1072. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  1073. }
  1074. // 5. 按题型和难度进行微调
  1075. return $this->adjustQuestionsByRatio($selectedQuestions, $questionTypeRatio, $difficultyRatio);
  1076. }
  1077. /**
  1078. * 获取学生对特定知识点的掌握度
  1079. */
  1080. private function getStudentKpMastery(string $studentId, string $kpCode): float
  1081. {
  1082. try {
  1083. $mastery = DB::table('student_mastery')
  1084. ->where('student_id', $studentId)
  1085. ->where('kp', $kpCode)
  1086. ->value('mastery');
  1087. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  1088. } catch (\Exception $e) {
  1089. Log::error('Get Student Kp Mastery Error', [
  1090. 'student_id' => $studentId,
  1091. 'kp_code' => $kpCode,
  1092. 'error' => $e->getMessage()
  1093. ]);
  1094. return 0.5;
  1095. }
  1096. }
  1097. /**
  1098. * 根据题型和难度配比调整题目
  1099. */
  1100. private function adjustQuestionsByRatio(array $questions, array $typeRatio, array $difficultyRatio): array
  1101. {
  1102. // 这里可以实现更精细的调整逻辑
  1103. // 目前先返回原始题目,后续可以基于question_type和difficulty字段进行调整
  1104. return $questions;
  1105. }
  1106. }