LearningAnalyticsService.php 86 KB

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