LearningAnalyticsService.php 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1073. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1074. // 1. 如果指定了学生,获取学生的薄弱点
  1075. $weaknessFilter = [];
  1076. if ($studentId) {
  1077. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1078. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1079. // 如果用户没有指定知识点,使用学生的薄弱点
  1080. if (empty($kpCodes)) {
  1081. $kpCodes = $weaknessFilter;
  1082. }
  1083. }
  1084. // 如果没有指定知识点,直接从题库随机选择题目(不限制知识点)
  1085. // 这样可以确保总能找到题目,而不是依赖知识图谱中的知识点
  1086. // 2. 调用题库API获取符合条件的所有题目
  1087. $allQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId, $questionTypeRatio, $difficultyRatio, 200);
  1088. if (empty($allQuestions)) {
  1089. // 如果指定了知识点但题库为空,给出明确提示
  1090. if (!empty($kpCodes)) {
  1091. $message = '题库中暂无可用题目。您可以选择其他知识点,或点击"生成练习题"按钮先补充题库。';
  1092. } else {
  1093. // 没有选择知识点时,从所有题目中选择
  1094. // 如果仍然没有题目,说明题库为空,提示补充题库
  1095. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1096. }
  1097. Log::warning('智能出卷失败 - 未找到题目', [
  1098. 'student_id' => $studentId,
  1099. 'selected_kp_codes' => $kpCodes,
  1100. 'message' => $message
  1101. ]);
  1102. return [
  1103. 'success' => false,
  1104. 'message' => $message,
  1105. 'questions' => []
  1106. ];
  1107. }
  1108. // 3. 根据掌握度对题目进行筛选和排序
  1109. $selectedQuestions = $this->selectQuestionsByMastery(
  1110. $allQuestions,
  1111. $studentId,
  1112. $totalQuestions,
  1113. $questionTypeRatio,
  1114. $difficultyRatio,
  1115. $difficultyLevels,
  1116. $weaknessFilter
  1117. );
  1118. if (empty($selectedQuestions)) {
  1119. return [
  1120. 'success' => false,
  1121. 'message' => '题目筛选失败',
  1122. 'questions' => []
  1123. ];
  1124. }
  1125. return [
  1126. 'success' => true,
  1127. 'message' => '智能出卷成功',
  1128. 'questions' => $selectedQuestions,
  1129. 'stats' => [
  1130. 'total_selected' => count($selectedQuestions),
  1131. 'source_questions' => count($allQuestions),
  1132. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1133. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1134. })) : 0
  1135. ]
  1136. ];
  1137. } catch (\Exception $e) {
  1138. Log::error('Generate Intelligent Exam Error', [
  1139. 'error' => $e->getMessage(),
  1140. 'trace' => $e->getTraceAsString()
  1141. ]);
  1142. return [
  1143. 'success' => false,
  1144. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1145. 'questions' => []
  1146. ];
  1147. }
  1148. }
  1149. /**
  1150. * 从题库获取题目 - 使用智能选题API,直接根据要求筛选
  1151. */
  1152. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], array $difficultyRatio = [], int $totalNeeded = 100): array
  1153. {
  1154. try {
  1155. // 构建筛选条件
  1156. $filters = [];
  1157. // 知识点筛选
  1158. if (!empty($kpCodes)) {
  1159. $filters['kp_codes'] = $kpCodes;
  1160. }
  1161. // 技能筛选
  1162. if (!empty($skills)) {
  1163. $filters['skills'] = $skills;
  1164. }
  1165. // 题型配比
  1166. if (!empty($questionTypeRatio)) {
  1167. $filters['question_type_ratio'] = $questionTypeRatio;
  1168. }
  1169. // 难度配比
  1170. if (!empty($difficultyRatio)) {
  1171. $filters['difficulty_ratio'] = $difficultyRatio;
  1172. }
  1173. // 过滤学生做过的题目
  1174. if ($studentId) {
  1175. $filters['exclude_student_questions'] = $studentId;
  1176. }
  1177. // 从容器动态获取实例
  1178. if (!$this->questionBankService) {
  1179. $this->questionBankService = app(QuestionBankService::class);
  1180. }
  1181. // 调用智能选题API - 直接获取符合要求的题目
  1182. $questions = $this->questionBankService->selectQuestionsForExam($totalNeeded, $filters);
  1183. if (!empty($questions)) {
  1184. // 过滤掉没有解题思路的题目
  1185. $questionsWithSolution = array_filter($questions, function($q) {
  1186. return !empty(trim($q['solution'] ?? ''));
  1187. });
  1188. Log::info('从题库智能获取题目', [
  1189. 'total_from_bank' => count($questions),
  1190. 'has_solution' => count($questionsWithSolution),
  1191. 'filtered_out' => count($questions) - count($questionsWithSolution),
  1192. 'filters' => $filters
  1193. ]);
  1194. return array_values($questionsWithSolution);
  1195. }
  1196. Log::warning('智能选题返回空结果', [
  1197. 'filters' => $filters
  1198. ]);
  1199. return [];
  1200. } catch (\Exception $e) {
  1201. Log::error('智能选题异常', [
  1202. 'error' => $e->getMessage()
  1203. ]);
  1204. }
  1205. return [];
  1206. }
  1207. /**
  1208. * 根据学生掌握度筛选题目
  1209. */
  1210. private function selectQuestionsByMastery(
  1211. array $questions,
  1212. ?string $studentId,
  1213. int $totalQuestions,
  1214. array $questionTypeRatio,
  1215. array $difficultyRatio,
  1216. array $difficultyLevels,
  1217. array $weaknessFilter
  1218. ): array {
  1219. // 如果未选择难度,则不过滤(随机生成所有难度)
  1220. if (empty($difficultyLevels)) {
  1221. Log::info('用户未选择难度,将随机生成所有难度的题目');
  1222. // 不过滤任何题目,保留所有难度
  1223. } else {
  1224. // 按难度筛掉不在选择范围内的题目
  1225. $questions = array_values(array_filter($questions, function ($q) use ($difficultyLevels) {
  1226. $d = $q['difficulty'] ?? null;
  1227. if ($d === null) return true; // 无难度信息则保留
  1228. $level = $this->mapDifficultyLevel((float)$d);
  1229. return in_array($level, $difficultyLevels);
  1230. }));
  1231. }
  1232. // 1. 按知识点分组
  1233. $questionsByKp = [];
  1234. foreach ($questions as $question) {
  1235. $kpCode = $question['kp_code'] ?? '';
  1236. if (!isset($questionsByKp[$kpCode])) {
  1237. $questionsByKp[$kpCode] = [];
  1238. }
  1239. $questionsByKp[$kpCode][] = $question;
  1240. }
  1241. // 2. 为每个知识点计算权重
  1242. $kpWeights = [];
  1243. foreach (array_keys($questionsByKp) as $kpCode) {
  1244. if ($studentId) {
  1245. // 获取学生对该知识点的掌握度
  1246. $mastery = $this->getStudentKpMastery($studentId, $kpCode);
  1247. // 薄弱点权重更高
  1248. if (in_array($kpCode, $weaknessFilter)) {
  1249. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1250. } else {
  1251. // 掌握度越低,权重越高
  1252. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1253. }
  1254. } else {
  1255. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1256. }
  1257. }
  1258. // 3. 按权重分配题目数量
  1259. $totalWeight = array_sum($kpWeights);
  1260. $selectedQuestions = [];
  1261. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1262. // 计算该知识点应该选择的题目数
  1263. $kpQuestionCount = max(1, round(($totalQuestions * $kpWeights[$kpCode]) / $totalWeight));
  1264. // 打乱题目顺序(避免固定模式)
  1265. shuffle($kpQuestions);
  1266. // 选择题目
  1267. $selectedFromKp = array_slice($kpQuestions, 0, $kpQuestionCount);
  1268. $selectedQuestions = array_merge($selectedQuestions, $selectedFromKp);
  1269. }
  1270. // 4. 如果题目过多,按权重排序后截取
  1271. if (count($selectedQuestions) > $totalQuestions) {
  1272. usort($selectedQuestions, function ($a, $b) use ($kpWeights) {
  1273. $weightA = $kpWeights[$a['kp_code']] ?? 1.0;
  1274. $weightB = $kpWeights[$b['kp_code']] ?? 1.0;
  1275. return $weightB <=> $weightA;
  1276. });
  1277. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  1278. }
  1279. // 5. 按题型和难度进行微调
  1280. return $this->adjustQuestionsByRatio($selectedQuestions, $questionTypeRatio, $difficultyRatio, $totalQuestions);
  1281. }
  1282. /**
  1283. * 获取学生对特定知识点的掌握度
  1284. */
  1285. private function getStudentKpMastery(string $studentId, string $kpCode): float
  1286. {
  1287. try {
  1288. $mastery = DB::table('student_mastery')
  1289. ->where('student_id', $studentId)
  1290. ->where('kp', $kpCode)
  1291. ->value('mastery');
  1292. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  1293. } catch (\Exception $e) {
  1294. Log::error('Get Student Kp Mastery Error', [
  1295. 'student_id' => $studentId,
  1296. 'kp_code' => $kpCode,
  1297. 'error' => $e->getMessage()
  1298. ]);
  1299. return 0.5;
  1300. }
  1301. }
  1302. /**
  1303. * 根据题型和难度配比调整题目
  1304. */
  1305. private function adjustQuestionsByRatio(array $questions, array $typeRatio, array $difficultyRatio, int $targetCount): array
  1306. {
  1307. // 按题型分桶
  1308. $buckets = [
  1309. 'choice' => [],
  1310. 'fill' => [],
  1311. 'answer' => [],
  1312. ];
  1313. foreach ($questions as $q) {
  1314. $type = $this->determineQuestionType($q);
  1315. if (!isset($buckets[$type])) {
  1316. $type = 'answer';
  1317. }
  1318. $buckets[$type][] = $q;
  1319. }
  1320. // 计算目标数(四舍五入,比例>0 则至少 1 道),并校正总数
  1321. $targetCount = min($targetCount, count($questions));
  1322. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  1323. Log::info('题型配比调整前桶统计', [
  1324. 'target_count' => $targetCount,
  1325. 'targets' => $targets,
  1326. 'bucket_counts' => [
  1327. 'choice' => count($buckets['choice']),
  1328. 'fill' => count($buckets['fill']),
  1329. 'answer' => count($buckets['answer']),
  1330. ],
  1331. 'raw_ratio' => $typeRatio,
  1332. ]);
  1333. // 随机打乱桶
  1334. foreach ($buckets as $k => $v) {
  1335. if (!empty($v)) {
  1336. shuffle($v);
  1337. $buckets[$k] = $v;
  1338. }
  1339. }
  1340. $selected = [];
  1341. $selectedIds = [];
  1342. // 按目标数依次取题
  1343. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  1344. $need = $targets[$typeKey] ?? 0;
  1345. if ($need <= 0 || empty($buckets[$typeKey])) {
  1346. continue;
  1347. }
  1348. $take = min($need, count($buckets[$typeKey]));
  1349. $slice = array_slice($buckets[$typeKey], 0, $take);
  1350. foreach ($slice as $q) {
  1351. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  1352. if (isset($selectedIds[$id])) {
  1353. continue;
  1354. }
  1355. $selected[] = $q;
  1356. $selectedIds[$id] = true;
  1357. }
  1358. }
  1359. // 不足则从剩余题中补齐
  1360. if (count($selected) < $targetCount) {
  1361. $remaining = [];
  1362. foreach ($buckets as $v) {
  1363. foreach ($v as $q) {
  1364. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  1365. if (!isset($selectedIds[$id])) {
  1366. $remaining[] = $q;
  1367. }
  1368. }
  1369. }
  1370. shuffle($remaining);
  1371. $needMore = $targetCount - count($selected);
  1372. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  1373. }
  1374. // 截断至目标数
  1375. $selected = array_slice($selected, 0, $targetCount);
  1376. Log::info('题型配比调整完成', [
  1377. 'target_count' => $targetCount,
  1378. 'targets' => $targets,
  1379. 'selected_counts' => [
  1380. 'choice' => count(array_filter($selected, fn($q) => $this->determineQuestionType($q) === 'choice')),
  1381. 'fill' => count(array_filter($selected, fn($q) => $this->determineQuestionType($q) === 'fill')),
  1382. 'answer' => count(array_filter($selected, fn($q) => $this->determineQuestionType($q) === 'answer')),
  1383. ],
  1384. ]);
  1385. return $selected;
  1386. }
  1387. private function determineQuestionType(array $q): string
  1388. {
  1389. // 优先根据题目内容判断(而不是数据库字段)
  1390. $stem = $q['stem'] ?? $q['content'] ?? '';
  1391. $tags = $q['tags'] ?? '';
  1392. $skills = $q['skills'] ?? [];
  1393. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  1394. if (is_string($stem)) {
  1395. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  1396. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  1397. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  1398. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  1399. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  1400. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  1401. // 至少有2个选项就认为是选择题(降低阈值)
  1402. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  1403. if ($optionCount >= 2) {
  1404. return 'choice';
  1405. }
  1406. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  1407. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  1408. return 'choice';
  1409. }
  1410. }
  1411. // 2. 根据技能点判断
  1412. if (is_array($skills)) {
  1413. $skillsStr = implode(',', $skills);
  1414. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  1415. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  1416. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  1417. }
  1418. // 3. 根据题目已有类型字段判断(作为后备)
  1419. $t = strtolower($q['question_type'] ?? $q['type'] ?? '');
  1420. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题'])) {
  1421. return 'choice';
  1422. }
  1423. if (in_array($t, ['fill', 'blank', 'fill_blank', '填空题'])) {
  1424. return 'fill';
  1425. }
  1426. if (in_array($t, ['answer', 'calculation', '解答题'])) {
  1427. return 'answer';
  1428. }
  1429. // 4. 根据标签判断
  1430. if (is_string($tags)) {
  1431. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  1432. return 'choice';
  1433. }
  1434. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  1435. return 'fill';
  1436. }
  1437. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  1438. return 'answer';
  1439. }
  1440. }
  1441. // 5. 根据options字段判断
  1442. if (!empty($q['options']) && is_array($q['options'])) {
  1443. return 'choice';
  1444. }
  1445. // 6. 填空题特征:连续下划线或明显的填空括号
  1446. if (is_string($stem)) {
  1447. // 检查填空题特征:连续下划线
  1448. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  1449. return 'fill';
  1450. }
  1451. // 空括号填空
  1452. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  1453. return 'fill';
  1454. }
  1455. }
  1456. // 7. 根据题干内容关键词判断
  1457. if (is_string($stem)) {
  1458. // 有证明、解答、计算、求证等关键词的是解答题
  1459. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  1460. return 'answer';
  1461. }
  1462. }
  1463. // 默认是解答题(更安全的默认值)
  1464. return 'answer';
  1465. }
  1466. private function mapDifficultyLevel(float $d): string
  1467. {
  1468. if ($d <= 0.4) {
  1469. return '基础';
  1470. }
  1471. if ($d <= 0.7) {
  1472. return '中等';
  1473. }
  1474. return '拔高';
  1475. }
  1476. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  1477. {
  1478. $map = [
  1479. '选择题' => 'choice',
  1480. '填空题' => 'fill',
  1481. '解答题' => 'answer',
  1482. ];
  1483. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1484. foreach ($questionTypeRatio as $label => $ratio) {
  1485. $key = $map[$label] ?? null;
  1486. if (!$key) {
  1487. continue;
  1488. }
  1489. $cnt = (int) round($targetCount * ($ratio / 100));
  1490. if ($ratio > 0 && $cnt < 1) {
  1491. $cnt = 1;
  1492. }
  1493. $targets[$key] = $cnt;
  1494. }
  1495. $sum = array_sum($targets);
  1496. if ($sum === 0) {
  1497. $targets['answer'] = $targetCount;
  1498. return $targets;
  1499. }
  1500. while ($sum > $targetCount) {
  1501. arsort($targets);
  1502. foreach ($targets as $k => $v) {
  1503. if ($v > 1) {
  1504. $targets[$k]--;
  1505. $sum--;
  1506. break;
  1507. }
  1508. }
  1509. }
  1510. if ($sum < $targetCount) {
  1511. $ratioByKey = [
  1512. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  1513. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  1514. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  1515. ];
  1516. while ($sum < $targetCount) {
  1517. arsort($ratioByKey);
  1518. $k = array_key_first($ratioByKey);
  1519. $targets[$k]++;
  1520. $sum++;
  1521. }
  1522. }
  1523. return $targets;
  1524. }
  1525. /**
  1526. * 提交手动评分结果到 LearningAnalytics
  1527. *
  1528. * @param array $data 包含 student_id, paper_id, grades 的数组
  1529. * @return array
  1530. */
  1531. public function submitManualGrading(array $data): array
  1532. {
  1533. try {
  1534. $response = Http::timeout($this->timeout)
  1535. ->post($this->baseUrl . '/api/ocr/analyze', [
  1536. 'student_id' => $data['student_id'],
  1537. 'paper_id' => $data['paper_id'],
  1538. 'answers' => $data['grades'],
  1539. ]);
  1540. if ($response->successful()) {
  1541. Log::info('Manual grading submitted successfully', [
  1542. 'student_id' => $data['student_id'],
  1543. 'paper_id' => $data['paper_id'],
  1544. 'question_count' => count($data['grades'])
  1545. ]);
  1546. return $response->json();
  1547. }
  1548. Log::error('Submit Manual Grading Error', [
  1549. 'data' => $data,
  1550. 'status' => $response->status(),
  1551. 'response' => $response->body()
  1552. ]);
  1553. return [
  1554. 'error' => true,
  1555. 'message' => 'Failed to submit manual grading'
  1556. ];
  1557. } catch (\Exception $e) {
  1558. Log::error('Submit Manual Grading Exception', [
  1559. 'error' => $e->getMessage(),
  1560. 'data' => $data
  1561. ]);
  1562. return [
  1563. 'error' => true,
  1564. 'message' => $e->getMessage()
  1565. ];
  1566. }
  1567. }
  1568. }