LearningAnalyticsService.php 82 KB

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