LearningAnalyticsService.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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. try {
  1057. $studentId = $params['student_id'] ?? null;
  1058. $grade = $params['grade'] ?? null; // 用户选择的年级
  1059. $totalQuestions = $params['total_questions'] ?? 20;
  1060. $kpCodes = $params['kp_codes'] ?? [];
  1061. $skills = $params['skills'] ?? [];
  1062. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1063. '选择题' => 40,
  1064. '填空题' => 30,
  1065. '解答题' => 30,
  1066. ];
  1067. $difficultyRatio = $params['difficulty_ratio'] ?? [
  1068. '基础' => 50,
  1069. '中等' => 35,
  1070. '拔高' => 15,
  1071. ];
  1072. // 1. 如果指定了学生,获取学生的薄弱点
  1073. $weaknessFilter = [];
  1074. if ($studentId) {
  1075. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1076. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1077. // 如果用户没有指定知识点,使用学生的薄弱点
  1078. if (empty($kpCodes)) {
  1079. $kpCodes = $weaknessFilter;
  1080. }
  1081. }
  1082. // 如果仍然没有知识点(例如新学生无薄弱点),根据年级从知识图谱获取知识点
  1083. if (empty($kpCodes)) {
  1084. $filters = [];
  1085. // 优先使用用户选择的年级,其次使用学生的年级
  1086. $effectiveGrade = $grade;
  1087. if (!$effectiveGrade && $studentId) {
  1088. $student = \App\Models\Student::find($studentId);
  1089. if ($student && $student->grade) {
  1090. $effectiveGrade = $student->grade;
  1091. }
  1092. }
  1093. if ($effectiveGrade) {
  1094. $standardizedGrade = $effectiveGrade;
  1095. // 标准化年级名称(不更新数据库)
  1096. if ($standardizedGrade === '初一') {
  1097. $standardizedGrade = '七年级';
  1098. } elseif ($standardizedGrade === '初二') {
  1099. $standardizedGrade = '八年级';
  1100. } elseif ($standardizedGrade === '初三') {
  1101. $standardizedGrade = '九年级';
  1102. }
  1103. // 映射年级到学段 (phase)
  1104. if ($standardizedGrade === '初中' || str_contains($standardizedGrade, '七年级') || str_contains($standardizedGrade, '八年级') || str_contains($standardizedGrade, '九年级')) {
  1105. $filters['phase'] = '初中';
  1106. } elseif (str_contains($standardizedGrade, '高')) {
  1107. $filters['phase'] = '高中';
  1108. }
  1109. Log::info('Using grade for knowledge points filter', [
  1110. 'original_grade' => $effectiveGrade,
  1111. 'standardized_grade' => $standardizedGrade,
  1112. 'filters' => $filters
  1113. ]);
  1114. }
  1115. // 调用API获取过滤后的知识点
  1116. $filteredKps = $this->getKnowledgePoints($filters);
  1117. if (!empty($filteredKps)) {
  1118. // 随机选择 5 个知识点
  1119. $kpKeys = array_column($filteredKps, 'kp_code');
  1120. if (empty($kpKeys)) {
  1121. $kpKeys = array_column($filteredKps, 'code');
  1122. }
  1123. if (!empty($kpKeys)) {
  1124. $randomKeys = array_rand(array_flip($kpKeys), min(5, count($kpKeys)));
  1125. $kpCodes = is_array($randomKeys) ? $randomKeys : [$randomKeys];
  1126. Log::info('Randomly selected KPs for student based on grade (API)', [
  1127. 'student_id' => $studentId,
  1128. 'grade' => $student->grade ?? 'unknown',
  1129. 'filters' => $filters,
  1130. 'kps' => $kpCodes
  1131. ]);
  1132. }
  1133. }
  1134. }
  1135. // 2. 调用题库API获取符合条件的所有题目
  1136. $allQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId);
  1137. if (empty($allQuestions)) {
  1138. // 根据是否有选择的知识点给出不同的错误信息
  1139. if (empty($kpCodes)) {
  1140. $message = '未选择知识点,无法生成试卷。请先选择知识点或选择学生以获取薄弱点推荐。';
  1141. } else {
  1142. $message = '题库中暂无可用题目。您可以选择其他知识点,或点击"生成练习题"按钮先补充题库。';
  1143. }
  1144. Log::warning('智能出卷失败 - 未找到题目', [
  1145. 'student_id' => $studentId,
  1146. 'selected_kp_codes' => $kpCodes,
  1147. 'message' => $message
  1148. ]);
  1149. return [
  1150. 'success' => false,
  1151. 'message' => $message,
  1152. 'questions' => []
  1153. ];
  1154. }
  1155. // 3. 根据掌握度对题目进行筛选和排序
  1156. $selectedQuestions = $this->selectQuestionsByMastery(
  1157. $allQuestions,
  1158. $studentId,
  1159. $totalQuestions,
  1160. $questionTypeRatio,
  1161. $difficultyRatio,
  1162. $weaknessFilter
  1163. );
  1164. if (empty($selectedQuestions)) {
  1165. return [
  1166. 'success' => false,
  1167. 'message' => '题目筛选失败',
  1168. 'questions' => []
  1169. ];
  1170. }
  1171. return [
  1172. 'success' => true,
  1173. 'message' => '智能出卷成功',
  1174. 'questions' => $selectedQuestions,
  1175. 'stats' => [
  1176. 'total_selected' => count($selectedQuestions),
  1177. 'source_questions' => count($allQuestions),
  1178. 'weakness_targeted' => $studentId ? count(array_intersect(array_column($selectedQuestions, 'kp_code'), $weaknessFilter)) : 0
  1179. ]
  1180. ];
  1181. } catch (\Exception $e) {
  1182. Log::error('Generate Intelligent Exam Error', [
  1183. 'error' => $e->getMessage(),
  1184. 'trace' => $e->getTraceAsString()
  1185. ]);
  1186. return [
  1187. 'success' => false,
  1188. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1189. 'questions' => []
  1190. ];
  1191. }
  1192. }
  1193. /**
  1194. * 从题库获取题目
  1195. */
  1196. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId): array
  1197. {
  1198. try {
  1199. // 构建查询参数
  1200. $params = [
  1201. 'kp_codes' => implode(',', $kpCodes),
  1202. 'limit' => 1000 // 获取足够多的题目用于筛选
  1203. ];
  1204. if (!empty($skills)) {
  1205. $params['skills'] = implode(',', $skills);
  1206. }
  1207. if ($studentId) {
  1208. $params['exclude_student_questions'] = $studentId; // 过滤学生做过的题目
  1209. }
  1210. // 调用QuestionBank API
  1211. // 使用 QuestionBankService 获取题目 (使用 filterQuestions 方法以支持 kp_codes)
  1212. // 从容器动态获取实例
  1213. if (!$this->questionBankService) {
  1214. $this->questionBankService = app(QuestionBankService::class);
  1215. }
  1216. $response = $this->questionBankService->filterQuestions($params);
  1217. if (!empty($response['data'])) {
  1218. return $response['data'];
  1219. }
  1220. Log::warning('Get Questions From Bank Failed or Empty', [
  1221. 'params' => $params,
  1222. 'response' => $response
  1223. ]);
  1224. return [];
  1225. } catch (\Exception $e) {
  1226. Log::error('Get Questions From Bank Error', [
  1227. 'error' => $e->getMessage()
  1228. ]);
  1229. }
  1230. return [];
  1231. }
  1232. /**
  1233. * 根据学生掌握度筛选题目
  1234. */
  1235. private function selectQuestionsByMastery(
  1236. array $questions,
  1237. ?string $studentId,
  1238. int $totalQuestions,
  1239. array $questionTypeRatio,
  1240. array $difficultyRatio,
  1241. array $weaknessFilter
  1242. ): array {
  1243. // 1. 按知识点分组
  1244. $questionsByKp = [];
  1245. foreach ($questions as $question) {
  1246. $kpCode = $question['kp_code'] ?? '';
  1247. if (!isset($questionsByKp[$kpCode])) {
  1248. $questionsByKp[$kpCode] = [];
  1249. }
  1250. $questionsByKp[$kpCode][] = $question;
  1251. }
  1252. // 2. 为每个知识点计算权重
  1253. $kpWeights = [];
  1254. foreach (array_keys($questionsByKp) as $kpCode) {
  1255. if ($studentId) {
  1256. // 获取学生对该知识点的掌握度
  1257. $mastery = $this->getStudentKpMastery($studentId, $kpCode);
  1258. // 薄弱点权重更高
  1259. if (in_array($kpCode, $weaknessFilter)) {
  1260. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1261. } else {
  1262. // 掌握度越低,权重越高
  1263. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1264. }
  1265. } else {
  1266. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1267. }
  1268. }
  1269. // 3. 按权重分配题目数量
  1270. $totalWeight = array_sum($kpWeights);
  1271. $selectedQuestions = [];
  1272. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1273. // 计算该知识点应该选择的题目数
  1274. $kpQuestionCount = max(1, round(($totalQuestions * $kpWeights[$kpCode]) / $totalWeight));
  1275. // 打乱题目顺序(避免固定模式)
  1276. shuffle($kpQuestions);
  1277. // 选择题目
  1278. $selectedFromKp = array_slice($kpQuestions, 0, $kpQuestionCount);
  1279. $selectedQuestions = array_merge($selectedQuestions, $selectedFromKp);
  1280. }
  1281. // 4. 如果题目过多,按权重排序后截取
  1282. if (count($selectedQuestions) > $totalQuestions) {
  1283. usort($selectedQuestions, function ($a, $b) use ($kpWeights) {
  1284. $weightA = $kpWeights[$a['kp_code']] ?? 1.0;
  1285. $weightB = $kpWeights[$b['kp_code']] ?? 1.0;
  1286. return $weightB <=> $weightA;
  1287. });
  1288. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  1289. }
  1290. // 5. 按题型和难度进行微调
  1291. return $this->adjustQuestionsByRatio($selectedQuestions, $questionTypeRatio, $difficultyRatio);
  1292. }
  1293. /**
  1294. * 获取学生对特定知识点的掌握度
  1295. */
  1296. private function getStudentKpMastery(string $studentId, string $kpCode): float
  1297. {
  1298. try {
  1299. $mastery = DB::table('student_mastery')
  1300. ->where('student_id', $studentId)
  1301. ->where('kp', $kpCode)
  1302. ->value('mastery');
  1303. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  1304. } catch (\Exception $e) {
  1305. Log::error('Get Student Kp Mastery Error', [
  1306. 'student_id' => $studentId,
  1307. 'kp_code' => $kpCode,
  1308. 'error' => $e->getMessage()
  1309. ]);
  1310. return 0.5;
  1311. }
  1312. }
  1313. /**
  1314. * 根据题型和难度配比调整题目
  1315. */
  1316. private function adjustQuestionsByRatio(array $questions, array $typeRatio, array $difficultyRatio): array
  1317. {
  1318. // 这里可以实现更精细的调整逻辑
  1319. // 目前先返回原始题目,后续可以基于question_type和difficulty字段进行调整
  1320. return $questions;
  1321. }
  1322. /**
  1323. * 提交手动评分结果到 LearningAnalytics
  1324. *
  1325. * @param array $data 包含 student_id, paper_id, grades 的数组
  1326. * @return array
  1327. */
  1328. public function submitManualGrading(array $data): array
  1329. {
  1330. try {
  1331. $response = Http::timeout($this->timeout)
  1332. ->post($this->baseUrl . '/api/ocr/analyze', [
  1333. 'student_id' => $data['student_id'],
  1334. 'paper_id' => $data['paper_id'],
  1335. 'answers' => $data['grades'],
  1336. ]);
  1337. if ($response->successful()) {
  1338. Log::info('Manual grading submitted successfully', [
  1339. 'student_id' => $data['student_id'],
  1340. 'paper_id' => $data['paper_id'],
  1341. 'question_count' => count($data['grades'])
  1342. ]);
  1343. return $response->json();
  1344. }
  1345. Log::error('Submit Manual Grading Error', [
  1346. 'data' => $data,
  1347. 'status' => $response->status(),
  1348. 'response' => $response->body()
  1349. ]);
  1350. return [
  1351. 'error' => true,
  1352. 'message' => 'Failed to submit manual grading'
  1353. ];
  1354. } catch (\Exception $e) {
  1355. Log::error('Submit Manual Grading Exception', [
  1356. 'error' => $e->getMessage(),
  1357. 'data' => $data
  1358. ]);
  1359. return [
  1360. 'error' => true,
  1361. 'message' => $e->getMessage()
  1362. ];
  1363. }
  1364. }
  1365. }