LearningAnalyticsService.php 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628
  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. // 新增:题目分类筛选
  1128. $questionCategory = $params['question_category'] ?? null;
  1129. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  1130. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1131. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1132. Log::info("generateIntelligentExam 开始", [
  1133. 'student_id' => $studentId,
  1134. 'total_questions' => $totalQuestions,
  1135. 'kp_codes' => $kpCodes,
  1136. 'skills' => $skills,
  1137. 'assemble_type' => $assembleType,
  1138. 'exam_type_legacy' => $examTypeLegacy,
  1139. 'question_category' => $questionCategory,
  1140. ]);
  1141. // 1. 如果指定了学生,获取学生的薄弱点
  1142. $weaknessFilter = [];
  1143. if ($studentId) {
  1144. Log::info("获取学生薄弱点: $studentId");
  1145. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1146. Log::info("薄弱点数量: " . count($weaknesses), [
  1147. '薄弱点' => $weaknesses,
  1148. ]);
  1149. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1150. // 如果用户没有指定知识点,使用学生的薄弱点
  1151. if (empty($kpCodes)) {
  1152. $kpCodes = $weaknessFilter;
  1153. Log::info("用户未选择知识点,使用薄弱点作为kp_codes", [
  1154. '最终kp_codes' => $kpCodes,
  1155. ]);
  1156. }
  1157. }
  1158. Log::info("准备调用 getQuestionsFromBank", [
  1159. 'kp_codes' => $kpCodes,
  1160. 'skills' => $skills,
  1161. ]);
  1162. // 2. 优先使用学生错题(如果存在)
  1163. $mistakeQuestionIds = $params['mistake_question_ids'] ?? [];
  1164. $priorityQuestions = [];
  1165. $maxQuestions = 50; // 全局最大题目数限制
  1166. if (!empty($mistakeQuestionIds)) {
  1167. Log::info('LearningAnalyticsService: 优先获取学生错题', [
  1168. 'mistake_question_ids' => $mistakeQuestionIds,
  1169. 'count' => count($mistakeQuestionIds),
  1170. 'max_limit' => $maxQuestions
  1171. ]);
  1172. // 如果错题超过最大值,截取到最大值
  1173. $truncatedMistakeIds = $mistakeQuestionIds;
  1174. if (count($mistakeQuestionIds) > $maxQuestions) {
  1175. Log::warning('LearningAnalyticsService: 错题数量超过最大值限制,已截取', [
  1176. 'mistake_count' => count($mistakeQuestionIds),
  1177. 'max_limit' => $maxQuestions,
  1178. 'truncated_count' => $maxQuestions
  1179. ]);
  1180. $truncatedMistakeIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  1181. }
  1182. // 获取学生错题的详细信息
  1183. $priorityQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $truncatedMistakeIds, [], null);
  1184. Log::info('LearningAnalyticsService: 错题获取完成', [
  1185. 'priority_questions_count' => count($priorityQuestions),
  1186. 'expected_count' => count($truncatedMistakeIds)
  1187. ]);
  1188. // 如果获取的错题数量少于预期,记录警告
  1189. if (count($priorityQuestions) < count($truncatedMistakeIds)) {
  1190. Log::warning('LearningAnalyticsService: 错题获取不完整', [
  1191. 'expected' => count($truncatedMistakeIds),
  1192. 'actual' => count($priorityQuestions),
  1193. 'missing_ids' => array_diff($truncatedMistakeIds, array_column($priorityQuestions, 'id'))
  1194. ]);
  1195. }
  1196. }
  1197. // 3. 处理错题本逻辑
  1198. $allQuestions = $priorityQuestions;
  1199. $isMistakeBook = ($assembleType === 5); // 错题本类型
  1200. // 如果是错题本类型,且有错题但数量不足,获取原卷子的所有题目
  1201. if ($isMistakeBook && !empty($priorityQuestions) && count($priorityQuestions) < 5 && !empty($params['paper_ids'])) {
  1202. Log::info('LearningAnalyticsService: 错题本错题不足,获取原卷子题目补充', [
  1203. 'mistake_count' => count($priorityQuestions),
  1204. 'paper_ids' => $params['paper_ids']
  1205. ]);
  1206. // 获取原卷子的所有题目
  1207. $paperQuestionIds = $this->getPaperAllQuestions($params['paper_ids']);
  1208. if (!empty($paperQuestionIds)) {
  1209. Log::info('LearningAnalyticsService: 获取原卷子题目', [
  1210. 'paper_question_count' => count($paperQuestionIds)
  1211. ]);
  1212. // 使用原卷子题目补充到目标数量
  1213. $additionalNeeded = max(5, count($priorityQuestions)) - count($priorityQuestions);
  1214. $paperQuestionIds = array_diff($paperQuestionIds, array_column($priorityQuestions, 'id'));
  1215. $additionalPaperQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $additionalNeeded, $paperQuestionIds, [], null);
  1216. $allQuestions = array_merge($priorityQuestions, $additionalPaperQuestions);
  1217. Log::info('LearningAnalyticsService: 错题本题目补充完成', [
  1218. 'final_count' => count($allQuestions)
  1219. ]);
  1220. }
  1221. }
  1222. // 如果是错题本类型,但完全没有错题,使用原卷子的所有题目
  1223. if ($isMistakeBook && empty($priorityQuestions) && !empty($params['paper_ids'])) {
  1224. Log::info('LearningAnalyticsService: 错题本无错题,使用原卷子题目', [
  1225. 'paper_ids' => $params['paper_ids']
  1226. ]);
  1227. // 获取原卷子的所有题目
  1228. $paperQuestionIds = $this->getPaperAllQuestions($params['paper_ids']);
  1229. if (!empty($paperQuestionIds)) {
  1230. $allQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $paperQuestionIds, [], null);
  1231. // 检查是否获取到题目
  1232. if (empty($allQuestions)) {
  1233. Log::warning('LearningAnalyticsService: 错题本无法获取任何题目', [
  1234. 'paper_ids' => $params['paper_ids'],
  1235. 'paper_question_ids' => $paperQuestionIds,
  1236. 'reason' => '原卷子题目在题库中不存在或已删除'
  1237. ]);
  1238. throw new \Exception('抱歉,您选择的卷子中的题目在题库中不存在或已被删除,无法生成错题本。请选择其他卷子或联系管理员更新题库。');
  1239. }
  1240. Log::info('LearningAnalyticsService: 错题本使用原卷子题目', [
  1241. 'question_count' => count($allQuestions)
  1242. ]);
  1243. } else {
  1244. throw new \Exception('抱歉,指定的卷子中没有找到题目,无法生成错题本。');
  1245. }
  1246. }
  1247. // 错题本类型但既无错题又无卷子题目
  1248. if ($isMistakeBook && empty($priorityQuestions) && empty($allQuestions)) {
  1249. Log::warning('LearningAnalyticsService: 错题本既无错题又无卷子题目', [
  1250. 'student_id' => $studentId,
  1251. 'paper_ids' => $params['paper_ids'] ?? []
  1252. ]);
  1253. throw new \Exception('抱歉,您在这个卷子中没有错题记录,且卷子题目无法获取,无法生成错题本。请确认卷子ID是否正确或联系管理员。');
  1254. }
  1255. if (!$isMistakeBook && count($priorityQuestions) < $totalQuestions) {
  1256. try {
  1257. Log::info('开始调用 getQuestionsFromBank 补充题目', [
  1258. 'kp_codes_count' => count($kpCodes),
  1259. 'skills_count' => count($skills),
  1260. 'has_mistake_priority' => !empty($mistakeQuestionIds),
  1261. 'need_more' => $totalQuestions - count($priorityQuestions),
  1262. 'assemble_type' => $assembleType
  1263. ]);
  1264. $additionalQuestions = $this->getQuestionsFromBank($kpCodes, $skills, $studentId, $questionTypeRatio, $maxQuestions, [], [], $questionCategory);
  1265. $allQuestions = array_merge($priorityQuestions, $additionalQuestions);
  1266. Log::info('getQuestionsFromBank 调用完成', [
  1267. 'questions_count' => count($allQuestions),
  1268. 'is_array' => is_array($allQuestions),
  1269. 'first_question_id' => !empty($allQuestions) ? ($allQuestions[0]['id'] ?? 'N/A') : 'N/A',
  1270. '耗时' => round((microtime(true) - $startTime) * 1000, 2) . 'ms',
  1271. ]);
  1272. Log::info('getQuestionsFromBank 返回', [
  1273. 'questions_count' => count($allQuestions),
  1274. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1275. ]);
  1276. } catch (\Exception $e) {
  1277. Log::error('getQuestionsFromBank 调用失败', [
  1278. 'error' => $e->getMessage(),
  1279. 'trace' => $e->getTraceAsString()
  1280. ]);
  1281. throw $e;
  1282. }
  1283. } elseif ($isMistakeBook) {
  1284. // 错题本类型:不补充题目,只使用错题
  1285. Log::info('错题本类型:不补充题目,只使用错题', [
  1286. 'assemble_type' => $assembleType,
  1287. 'mistake_questions_count' => count($priorityQuestions),
  1288. 'total_questions_requested' => $totalQuestions
  1289. ]);
  1290. }
  1291. if (empty($allQuestions)) {
  1292. // 如果指定了知识点但题库为空,给出明确提示
  1293. if (!empty($kpCodes)) {
  1294. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1295. } else {
  1296. // 没有选择知识点时,从所有题目中选择
  1297. // 如果仍然没有题目,说明题库为空,提示补充题库
  1298. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1299. }
  1300. Log::warning('智能出卷失败 - 未找到题目', [
  1301. 'student_id' => $studentId,
  1302. 'selected_kp_codes' => $kpCodes,
  1303. 'kp_codes_count' => count($kpCodes),
  1304. 'message' => $message,
  1305. 'hint' => '如果选择了知识点但题库为空,请检查知识点代码是否正确,或尝试取消知识点选择'
  1306. ]);
  1307. return [
  1308. 'success' => false,
  1309. 'message' => $message,
  1310. 'questions' => []
  1311. ];
  1312. }
  1313. // 3. 根据掌握度对题目进行筛选和排序
  1314. // 错题本类型:使用所有错题,但不超过最大值限制
  1315. $targetQuestionCount = $isMistakeBook ? min(count($allQuestions), $maxQuestions) : $totalQuestions;
  1316. Log::info('开始调用 selectQuestionsByMastery', [
  1317. 'input_count' => count($allQuestions),
  1318. 'target_count' => $targetQuestionCount,
  1319. 'is_mistake_book' => $isMistakeBook,
  1320. 'assemble_type' => $assembleType,
  1321. 'total_questions_param' => $totalQuestions
  1322. ]);
  1323. $startTime = microtime(true);
  1324. $selectedQuestions = $this->selectQuestionsByMastery(
  1325. $allQuestions,
  1326. $studentId,
  1327. $targetQuestionCount,
  1328. $questionTypeRatio,
  1329. $difficultyLevels,
  1330. $weaknessFilter
  1331. );
  1332. $selectTime = (microtime(true) - $startTime) * 1000;
  1333. Log::info('题目筛选结果', [
  1334. 'input_count' => count($allQuestions),
  1335. 'selected_count' => count($selectedQuestions),
  1336. 'target_count' => $targetQuestionCount,
  1337. 'is_mistake_book' => $isMistakeBook,
  1338. 'select_time_ms' => round($selectTime, 2)
  1339. ]);
  1340. if (empty($selectedQuestions)) {
  1341. return [
  1342. 'success' => false,
  1343. 'message' => '题目筛选失败',
  1344. 'questions' => []
  1345. ];
  1346. }
  1347. // 如果启用了难度分布且不是排除类型,则应用难度分布
  1348. $difficultyCategory = $params['difficulty_category'] ?? 1;
  1349. $enableDistribution = $params['enable_difficulty_distribution'] ?? false;
  1350. $isExcludedType = ($assembleType === 5); // 只有错题本类型(assembleType=5)不应用难度分布
  1351. if ($enableDistribution && !$isExcludedType) {
  1352. Log::info('LearningAnalyticsService: 应用难度系数分布', [
  1353. 'difficulty_category' => $difficultyCategory,
  1354. 'assemble_type' => $assembleType,
  1355. 'before_count' => count($selectedQuestions)
  1356. ]);
  1357. try {
  1358. // 使用 ExamTypeStrategy 的独立方法应用难度分布
  1359. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1360. $examStrategy = new ExamTypeStrategy($questionExpansionService);
  1361. $selectedQuestions = $examStrategy->applyDifficultyDistributionToQuestions(
  1362. $selectedQuestions,
  1363. $totalQuestions,
  1364. $difficultyCategory,
  1365. $params
  1366. );
  1367. Log::info('LearningAnalyticsService: 难度分布应用完成', [
  1368. 'after_count' => count($selectedQuestions)
  1369. ]);
  1370. } catch (\Exception $e) {
  1371. Log::warning('LearningAnalyticsService: 难度分布应用失败,继续使用原结果', [
  1372. 'error' => $e->getMessage()
  1373. ]);
  1374. }
  1375. }
  1376. return [
  1377. 'success' => true,
  1378. 'message' => '智能出卷成功',
  1379. 'questions' => $selectedQuestions,
  1380. 'stats' => [
  1381. 'total_selected' => count($selectedQuestions),
  1382. 'source_questions' => count($allQuestions),
  1383. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1384. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1385. })) : 0,
  1386. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1387. 'difficulty_category' => $difficultyCategory
  1388. ]
  1389. ];
  1390. } catch (\Exception $e) {
  1391. Log::error('Generate Intelligent Exam Error', [
  1392. 'error' => $e->getMessage(),
  1393. 'trace' => $e->getTraceAsString()
  1394. ]);
  1395. return [
  1396. 'success' => false,
  1397. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1398. 'questions' => []
  1399. ];
  1400. }
  1401. }
  1402. /**
  1403. * 从本地题库获取题目(错题回顾优先)
  1404. * 支持优先获取指定题目ID的题目
  1405. */
  1406. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], int $totalNeeded = 100, array $priorityQuestionIds = [], array $excludeQuestionIds = [], ?int $questionCategory = null): array
  1407. {
  1408. $startTime = microtime(true);
  1409. try {
  1410. // 错题回顾:优先获取指定的学生错题
  1411. if (!empty($priorityQuestionIds)) {
  1412. Log::info('getQuestionsFromBank: 优先获取学生错题', [
  1413. 'priority_count' => count($priorityQuestionIds),
  1414. 'priority_ids' => $priorityQuestionIds
  1415. ]);
  1416. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1417. if (!empty($priorityQuestions)) {
  1418. Log::info('getQuestionsFromBank: 优先错题获取成功', [
  1419. 'count' => count($priorityQuestions)
  1420. ]);
  1421. return $priorityQuestions;
  1422. } else {
  1423. Log::warning('getQuestionsFromBank: 优先错题获取失败,返回空数组让上层处理');
  1424. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1425. return [];
  1426. }
  1427. }
  1428. // 从本地数据库查询题目
  1429. Log::info('getQuestionsFromBank: 从本地数据库查询题目', [
  1430. 'kp_codes' => $kpCodes,
  1431. 'skills' => $skills,
  1432. 'total_needed' => $totalNeeded,
  1433. 'question_type_ratio' => $questionTypeRatio,
  1434. 'note' => '难度筛选由 QuestionLocalService 处理'
  1435. ]);
  1436. $query = \App\Models\Question::query();
  1437. // 按知识点筛选
  1438. if (!empty($kpCodes)) {
  1439. $query->whereIn('kp_code', $kpCodes);
  1440. Log::info('应用知识点筛选', ['kp_codes' => $kpCodes]);
  1441. }
  1442. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1443. if (!empty($skills)) {
  1444. $query->where(function ($q) use ($skills) {
  1445. foreach ($skills as $skill) {
  1446. $q->orWhere('tags', 'like', "%{$skill}%");
  1447. }
  1448. });
  1449. Log::info('应用技能筛选', ['skills' => $skills]);
  1450. }
  1451. // 排除学生已做过的题目
  1452. if (!empty($excludeQuestionIds)) {
  1453. $query->whereNotIn('id', $excludeQuestionIds);
  1454. Log::info('应用排除筛选', ['exclude_count' => count($excludeQuestionIds)]);
  1455. }
  1456. // 按题目分类筛选(如果指定了 question_category)
  1457. if ($questionCategory !== null) {
  1458. $query->where('question_category', $questionCategory);
  1459. Log::info('应用题目分类筛选', ['question_category' => $questionCategory]);
  1460. }
  1461. // 筛选有解题思路的题目
  1462. $query->whereNotNull('solution')
  1463. ->where('solution', '!=', '')
  1464. ->where('solution', '!=', '[]');
  1465. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1466. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1467. // 限制数量并随机排序
  1468. $query->limit($totalNeeded * 2) // 多取一些用于后续筛选
  1469. ->inRandomOrder();
  1470. $questions = $query->get();
  1471. Log::info('getQuestionsFromBank: 查询完成', [
  1472. 'raw_count' => $questions->count(),
  1473. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1474. ]);
  1475. // 转换为标准格式
  1476. $formattedQuestions = $questions->map(function ($q) {
  1477. return [
  1478. 'id' => $q->id,
  1479. 'question_code' => $q->question_code,
  1480. 'kp_code' => $q->kp_code,
  1481. 'question_type' => $q->question_type,
  1482. 'difficulty' => (float) $q->difficulty,
  1483. 'stem' => $q->stem,
  1484. 'solution' => $q->solution,
  1485. 'metadata' => [
  1486. 'has_solution' => true,
  1487. 'is_choice' => $q->question_type === 'choice',
  1488. 'is_fill' => $q->question_type === 'fill',
  1489. 'is_answer' => $q->question_type === 'answer',
  1490. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty),
  1491. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1492. ]
  1493. ];
  1494. })->toArray();
  1495. // 注意: 题型和难度配比调整由 QuestionLocalService 处理
  1496. // 这里只做初步筛选,让 QuestionLocalService 做精确的配比调整
  1497. $selectedQuestions = array_slice($formattedQuestions, 0, $totalNeeded);
  1498. Log::info('getQuestionsFromBank 完成', [
  1499. 'selected_count' => count($selectedQuestions),
  1500. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1501. ]);
  1502. return $selectedQuestions;
  1503. } catch (\Exception $e) {
  1504. Log::error('getQuestionsFromBank 查询失败', [
  1505. 'error' => $e->getMessage(),
  1506. 'trace' => $e->getTraceAsString()
  1507. ]);
  1508. throw $e;
  1509. }
  1510. }
  1511. /**
  1512. * 获取指定ID的题目详情
  1513. */
  1514. private function getLocalQuestionsByIds(array $questionIds): array
  1515. {
  1516. try {
  1517. // 通过QuestionBankService获取题目详情
  1518. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1519. // 批量获取题目详情
  1520. $response = $questionBankService->getQuestionsByIds($questionIds);
  1521. if (empty($response['data'])) {
  1522. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1523. 'requested_ids' => $questionIds
  1524. ]);
  1525. return [];
  1526. }
  1527. $questions = $response['data'];
  1528. // 转换为标准格式
  1529. $result = array_map(function ($q) {
  1530. $difficulty = $q['difficulty'] ?? 0.5;
  1531. return [
  1532. 'id' => $q['id'],
  1533. 'question_code' => $q['question_code'] ?? '',
  1534. 'kp_code' => $q['kp_code'] ?? '',
  1535. 'question_type' => $q['question_type'] ?? 'choice',
  1536. 'difficulty' => (float) $difficulty,
  1537. 'stem' => $q['stem'] ?? '',
  1538. 'solution' => $q['solution'] ?? '',
  1539. 'answer' => $q['answer'] ?? '',
  1540. 'metadata' => [
  1541. 'has_solution' => !empty($q['solution']),
  1542. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1543. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1544. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1545. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1546. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1547. ]
  1548. ];
  1549. }, $questions);
  1550. Log::info('getLocalQuestionsByIds 获取成功', [
  1551. 'requested_count' => count($questionIds),
  1552. 'found_count' => count($result),
  1553. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1554. 'question_ids' => array_slice($questionIds, 0, 20),
  1555. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1556. ]);
  1557. return $result;
  1558. } catch (\Exception $e) {
  1559. Log::error('getLocalQuestionsByIds 获取失败', [
  1560. 'question_ids' => $questionIds,
  1561. 'error' => $e->getMessage(),
  1562. 'trace' => $e->getTraceAsString()
  1563. ]);
  1564. return [];
  1565. }
  1566. }
  1567. /**
  1568. * 获取卷子的所有题目ID(不区分对错)
  1569. */
  1570. private function getPaperAllQuestions(array $paperIds): array
  1571. {
  1572. try {
  1573. // 查询 paper_questions 表获取所有题目ID
  1574. $questionIds = DB::table('paper_questions')
  1575. ->whereIn('paper_id', $paperIds)
  1576. ->pluck('question_bank_id')
  1577. ->unique()
  1578. ->filter()
  1579. ->values()
  1580. ->toArray();
  1581. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1582. 'paper_ids' => $paperIds,
  1583. 'question_count' => count($questionIds)
  1584. ]);
  1585. return $questionIds;
  1586. } catch (\Exception $e) {
  1587. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1588. 'paper_ids' => $paperIds,
  1589. 'error' => $e->getMessage()
  1590. ]);
  1591. return [];
  1592. }
  1593. }
  1594. /**
  1595. * 获取难度标签
  1596. */
  1597. private function getDifficultyLabel(float $difficulty): string
  1598. {
  1599. return match (true) {
  1600. $difficulty < 0.4 => '基础',
  1601. $difficulty < 0.7 => '中等',
  1602. default => '拔高'
  1603. };
  1604. }
  1605. /**
  1606. * 获取题型标签
  1607. */
  1608. private function getQuestionTypeLabel(string $questionType): string
  1609. {
  1610. return match ($questionType) {
  1611. 'choice' => '选择题',
  1612. 'fill' => '填空题',
  1613. 'answer' => '解答题',
  1614. default => '未知题型'
  1615. };
  1616. }
  1617. /**
  1618. * 根据题型配比选择题目
  1619. * 注意: 难度配比调整由 QuestionLocalService 处理
  1620. */
  1621. private function selectQuestionsByRatio(
  1622. array $questions,
  1623. int $totalNeeded,
  1624. array $questionTypeRatio = []
  1625. ): array {
  1626. if (empty($questions)) {
  1627. return [];
  1628. }
  1629. // 如果没有配比要求,直接返回
  1630. if (empty($questionTypeRatio)) {
  1631. return array_slice($questions, 0, $totalNeeded);
  1632. }
  1633. $selected = [];
  1634. $usedIndices = [];
  1635. // 按题型配比选择
  1636. if (!empty($questionTypeRatio)) {
  1637. foreach ($questionTypeRatio as $type => $ratio) {
  1638. $count = (int) round(($ratio / 100) * $totalNeeded);
  1639. if ($count <= 0) continue;
  1640. $typeQuestions = [];
  1641. foreach ($questions as $idx => $q) {
  1642. if (in_array($idx, $usedIndices)) continue;
  1643. $qType = $q['question_type'] ?? '';
  1644. $label = $this->getQuestionTypeLabel($qType);
  1645. if ($label === $type) {
  1646. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1647. }
  1648. }
  1649. // 随机选择
  1650. shuffle($typeQuestions);
  1651. $selectedCount = min($count, count($typeQuestions));
  1652. for ($i = 0; $i < $selectedCount; $i++) {
  1653. $selected[] = $typeQuestions[$i]['question'];
  1654. $usedIndices[] = $typeQuestions[$i]['idx'];
  1655. }
  1656. }
  1657. }
  1658. // 如果还有空缺,补充剩余题目
  1659. // 注意: 难度配比调整由 QuestionLocalService 处理
  1660. if (count($selected) < $totalNeeded) {
  1661. foreach ($questions as $idx => $q) {
  1662. if (count($selected) >= $totalNeeded) break;
  1663. if (!in_array($idx, $usedIndices)) {
  1664. $selected[] = $q;
  1665. $usedIndices[] = $idx;
  1666. }
  1667. }
  1668. }
  1669. return array_slice($selected, 0, $totalNeeded);
  1670. }
  1671. /**
  1672. * 根据学生掌握度筛选题目
  1673. */
  1674. private function selectQuestionsByMastery(
  1675. array $questions,
  1676. ?string $studentId,
  1677. int $totalQuestions,
  1678. array $questionTypeRatio,
  1679. array $difficultyLevels,
  1680. array $weaknessFilter
  1681. ): array {
  1682. Log::info('selectQuestionsByMastery 开始', [
  1683. 'question_count' => count($questions),
  1684. 'student_id' => $studentId,
  1685. 'total_questions' => $totalQuestions
  1686. ]);
  1687. // 错题本类型:使用所有题目,不进行权重分配和筛选
  1688. if ($totalQuestions >= count($questions)) {
  1689. Log::info('错题本类型:使用所有题目,跳过权重分配', [
  1690. 'question_count' => count($questions),
  1691. 'total_questions' => $totalQuestions,
  1692. 'input_question_count' => func_num_args() > 0 ? count($questions) : 'N/A'
  1693. ]);
  1694. return $questions;
  1695. }
  1696. // 如果未选择难度,则不过滤(随机生成所有难度)
  1697. if (empty($difficultyLevels)) {
  1698. Log::info('用户未选择难度,将随机生成所有难度的题目');
  1699. // 不过滤任何题目,保留所有难度
  1700. } else {
  1701. // 按难度筛掉不在选择范围内的题目
  1702. $questions = array_values(array_filter($questions, function ($q) use ($difficultyLevels) {
  1703. $d = $q['difficulty'] ?? null;
  1704. if ($d === null) return true; // 无难度信息则保留
  1705. $level = $this->mapDifficultyLevel((float)$d);
  1706. return in_array($level, $difficultyLevels);
  1707. }));
  1708. }
  1709. Log::info('难度筛选完成', [
  1710. 'after_filter_count' => count($questions)
  1711. ]);
  1712. // 1. 按知识点分组
  1713. Log::info('开始按知识点分组', [
  1714. 'question_count' => count($questions)
  1715. ]);
  1716. $groupStartTime = microtime(true);
  1717. $questionsByKp = [];
  1718. foreach ($questions as $question) {
  1719. $kpCode = $question['kp_code'] ?? '';
  1720. if (!isset($questionsByKp[$kpCode])) {
  1721. $questionsByKp[$kpCode] = [];
  1722. }
  1723. $questionsByKp[$kpCode][] = $question;
  1724. }
  1725. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1726. Log::info('按知识点分组完成', [
  1727. 'kp_count' => count($questionsByKp),
  1728. 'group_time_ms' => round($groupTime, 2)
  1729. ]);
  1730. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1731. $kpWeights = [];
  1732. $kpCodes = array_keys($questionsByKp);
  1733. Log::info('开始计算知识点权重(用于题型内排序)', [
  1734. 'kp_count' => count($kpCodes),
  1735. 'student_id' => $studentId
  1736. ]);
  1737. $startTime = microtime(true);
  1738. $allMastery = [];
  1739. if ($studentId) {
  1740. // 批量获取所有知识点的掌握度(一次查询)
  1741. $masteryStart = microtime(true);
  1742. try {
  1743. $masteryRecords = DB::table('student_mastery')
  1744. ->where('student_id', $studentId)
  1745. ->whereIn('kp', $kpCodes)
  1746. ->pluck('mastery', 'kp')
  1747. ->all();
  1748. Log::debug('批量获取掌握度', [
  1749. 'student_id' => $studentId,
  1750. 'kp_count' => count($kpCodes),
  1751. 'found_count' => count($masteryRecords),
  1752. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1753. ]);
  1754. $allMastery = $masteryRecords;
  1755. } catch (\Exception $e) {
  1756. Log::warning('批量获取掌握度失败,将使用默认值', [
  1757. 'student_id' => $studentId,
  1758. 'error' => $e->getMessage()
  1759. ]);
  1760. }
  1761. }
  1762. foreach ($kpCodes as $kpCode) {
  1763. if ($studentId) {
  1764. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1765. // 薄弱点权重更高
  1766. if (in_array($kpCode, $weaknessFilter)) {
  1767. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1768. } else {
  1769. // 掌握度越低,权重越高
  1770. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1771. }
  1772. Log::debug('计算知识点权重', [
  1773. 'kp_code' => $kpCode,
  1774. 'mastery' => $mastery,
  1775. 'weight' => $kpWeights[$kpCode]
  1776. ]);
  1777. } else {
  1778. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1779. }
  1780. }
  1781. $totalWeightTime = (microtime(true) - $startTime) * 1000;
  1782. Log::info('知识点权重计算完成', [
  1783. 'total_kp_count' => count($kpCodes),
  1784. 'total_weight_time_ms' => round($totalWeightTime, 2),
  1785. 'avg_time_per_kp_ms' => count($kpCodes) > 0 ? round($totalWeightTime / count($kpCodes), 2) : 0
  1786. ]);
  1787. // 3. 按题型分配题目数量(权重用于题型内排序)
  1788. $selectedQuestions = [];
  1789. // 将所有题目合并
  1790. $weightedQuestions = [];
  1791. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1792. foreach ($kpQuestions as $q) {
  1793. $q['kp_code'] = $kpCode;
  1794. $weightedQuestions[] = $q;
  1795. }
  1796. }
  1797. // ========== 知识点优先选择机制 ==========
  1798. // 摸底测试的核心目标是最大化知识点覆盖
  1799. // 题型只是约束条件(每种至少1题)
  1800. // 首先按题型分组
  1801. $questionsByType = [
  1802. 'choice' => [],
  1803. 'fill' => [],
  1804. 'answer' => [],
  1805. ];
  1806. foreach ($weightedQuestions as $q) {
  1807. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1808. if ($qid && isset($questionTypeCache[$qid])) {
  1809. $type = $questionTypeCache[$qid];
  1810. } else {
  1811. $type = $this->determineQuestionType($q);
  1812. if ($qid) {
  1813. $questionTypeCache[$qid] = $type;
  1814. }
  1815. }
  1816. if (!isset($questionsByType[$type])) {
  1817. $type = 'answer'; // 默认归类为answer
  1818. }
  1819. $questionsByType[$type][] = $q;
  1820. }
  1821. // ========== 步骤1:按知识点分组,优先选不同知识点 ==========
  1822. $selectedQuestions = [];
  1823. $kpSelected = []; // 已选知识点记录
  1824. // 先确保每种题型至少选1题(来自不同知识点)
  1825. foreach (['choice', 'fill', 'answer'] as $type) {
  1826. if (empty($questionsByType[$type])) {
  1827. Log::warning('题型分配:题型无题目', ['type' => $type]);
  1828. continue;
  1829. }
  1830. // 按权重排序该题型的题目
  1831. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  1832. $kpA = $a['kp_code'] ?? '';
  1833. $kpB = $b['kp_code'] ?? '';
  1834. $weightA = $kpWeights[$kpA] ?? 1.0;
  1835. $weightB = $kpWeights[$kpB] ?? 1.0;
  1836. return $weightB <=> $weightA;
  1837. });
  1838. // 选择第一个未选过知识点的题目
  1839. foreach ($questionsByType[$type] as $q) {
  1840. $kpCode = $q['kp_code'] ?? '';
  1841. if (!isset($kpSelected[$kpCode])) {
  1842. $selectedQuestions[] = $q;
  1843. $kpSelected[$kpCode] = true;
  1844. Log::debug('题型基础分配', ['type' => $type, 'kp' => $kpCode]);
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. // ========== 步骤2:继续选不同知识点,直到达到目标数量 ==========
  1850. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  1851. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  1852. $kpA = $a['kp_code'] ?? '';
  1853. $kpB = $b['kp_code'] ?? '';
  1854. $weightA = $kpWeights[$kpA] ?? 1.0;
  1855. $weightB = $kpWeights[$kpB] ?? 1.0;
  1856. if ($weightA == $weightB) {
  1857. $idA = $a['id'] ?? $a['question_id'] ?? 0;
  1858. $idB = $b['id'] ?? $b['question_id'] ?? 0;
  1859. return $idA <=> $idB;
  1860. }
  1861. return $weightB <=> $weightA;
  1862. });
  1863. // 选择未选过知识点的题目(优先)
  1864. foreach ($allQuestions as $q) {
  1865. if (count($selectedQuestions) >= $totalQuestions) break;
  1866. $kpCode = $q['kp_code'] ?? '';
  1867. if (!isset($kpSelected[$kpCode])) {
  1868. $selectedQuestions[] = $q;
  1869. $kpSelected[$kpCode] = true;
  1870. }
  1871. }
  1872. // ========== 步骤3:如果还有空缺,从已选知识点中补充 ==========
  1873. if (count($selectedQuestions) < $totalQuestions) {
  1874. Log::info('知识点分配后题目不足,开始补充', [
  1875. 'selected_count' => count($selectedQuestions),
  1876. 'need_more' => $totalQuestions - count($selectedQuestions),
  1877. 'kp_covered' => count($kpSelected)
  1878. ]);
  1879. // 统计每个知识点的题目数量
  1880. $kpCount = [];
  1881. foreach ($selectedQuestions as $q) {
  1882. $kpCode = $q['kp_code'] ?? '';
  1883. $kpCount[$kpCode] = ($kpCount[$kpCode] ?? 0) + 1;
  1884. }
  1885. // 优先补充知识点数量少的题目
  1886. foreach ($allQuestions as $q) {
  1887. if (count($selectedQuestions) >= $totalQuestions) break;
  1888. $kpCode = $q['kp_code'] ?? '';
  1889. $count = $kpCount[$kpCode] ?? 0;
  1890. // 如果该知识点题目数量少于2题,且题目不在已选列表中
  1891. if ($count < 2 && !in_array($q, $selectedQuestions)) {
  1892. $selectedQuestions[] = $q;
  1893. $kpCount[$kpCode] = $count + 1;
  1894. }
  1895. }
  1896. }
  1897. Log::info('知识点优先选择完成', [
  1898. 'total_questions' => $totalQuestions,
  1899. 'selected_count' => count($selectedQuestions),
  1900. 'kp_covered' => count($kpSelected),
  1901. 'type_distribution' => array_count_values(array_map(function($q) {
  1902. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1903. if ($qid && isset($questionTypeCache[$qid])) {
  1904. return $questionTypeCache[$qid];
  1905. }
  1906. return $this->determineQuestionType($q);
  1907. }, $selectedQuestions)),
  1908. 'top_kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  1909. ]);
  1910. // 最终截取到目标数量(如果超过)
  1911. if (count($selectedQuestions) > $totalQuestions) {
  1912. Log::info('题目数量超过目标,进行最终截取', [
  1913. 'before' => count($selectedQuestions),
  1914. 'after' => $totalQuestions
  1915. ]);
  1916. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  1917. }
  1918. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  1919. $finalQuestions = [];
  1920. $seenQuestionIds = [];
  1921. $duplicateCount = 0;
  1922. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1923. foreach ($selectedQuestions as $question) {
  1924. $qbId = $question['question_bank_id'] ?? $question['id'];
  1925. if (!in_array($qbId, $seenQuestionIds)) {
  1926. $seenQuestionIds[] = $qbId;
  1927. $finalQuestions[] = $question;
  1928. // 统计题型分布
  1929. $qid = $question['id'] ?? $question['question_id'] ?? null;
  1930. $type = null;
  1931. if ($qid && isset($questionTypeCache[$qid])) {
  1932. $type = $questionTypeCache[$qid];
  1933. } else {
  1934. $type = $this->determineQuestionType($question);
  1935. if ($qid) {
  1936. $questionTypeCache[$qid] = $type;
  1937. }
  1938. }
  1939. if (isset($typeDistribution[$type])) {
  1940. $typeDistribution[$type]++;
  1941. }
  1942. } else {
  1943. $duplicateCount++;
  1944. Log::warning('发现重复题目(已自动移除)', [
  1945. 'question_id' => $qbId,
  1946. 'duplicate_count' => $duplicateCount
  1947. ]);
  1948. }
  1949. }
  1950. Log::info('最终排查完成', [
  1951. 'original_count' => count($selectedQuestions),
  1952. 'final_count' => count($finalQuestions),
  1953. 'duplicate_removed' => $duplicateCount,
  1954. 'final_type_distribution' => $typeDistribution
  1955. ]);
  1956. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  1957. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  1958. return $finalQuestions;
  1959. }
  1960. /**
  1961. * 获取学生对特定知识点的掌握度
  1962. */
  1963. private function getStudentKpMastery(string $studentId, string $kpCode): float
  1964. {
  1965. try {
  1966. $mastery = DB::table('student_mastery')
  1967. ->where('student_id', $studentId)
  1968. ->where('kp', $kpCode)
  1969. ->value('mastery');
  1970. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  1971. } catch (\Exception $e) {
  1972. Log::error('Get Student Kp Mastery Error', [
  1973. 'student_id' => $studentId,
  1974. 'kp_code' => $kpCode,
  1975. 'error' => $e->getMessage()
  1976. ]);
  1977. return 0.5;
  1978. }
  1979. }
  1980. /**
  1981. * 根据题型和难度配比调整题目
  1982. */
  1983. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  1984. {
  1985. Log::info('开始题型配比调整', [
  1986. 'input_questions' => count($questions),
  1987. 'target_count' => $targetCount,
  1988. 'type_ratio' => $typeRatio
  1989. ]);
  1990. // 缓存题目类型,避免重复计算
  1991. $questionTypeCache = [];
  1992. // 按题型分桶
  1993. $buckets = [
  1994. 'choice' => [],
  1995. 'fill' => [],
  1996. 'answer' => [],
  1997. ];
  1998. foreach ($questions as $q) {
  1999. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2000. if ($qid && isset($questionTypeCache[$qid])) {
  2001. $type = $questionTypeCache[$qid];
  2002. } else {
  2003. $type = $this->determineQuestionType($q);
  2004. if ($qid) {
  2005. $questionTypeCache[$qid] = $type;
  2006. }
  2007. }
  2008. if (!isset($buckets[$type])) {
  2009. $type = 'answer';
  2010. }
  2011. $buckets[$type][] = $q;
  2012. }
  2013. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2014. // 修复:不自动减少目标数量,确保达到用户要求
  2015. $availableCount = count($questions);
  2016. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2017. Log::info('题型配比调整前桶统计', [
  2018. 'target_count' => $targetCount,
  2019. 'available_count' => $availableCount,
  2020. 'targets' => $targets,
  2021. 'bucket_counts' => [
  2022. 'choice' => count($buckets['choice']),
  2023. 'fill' => count($buckets['fill']),
  2024. 'answer' => count($buckets['answer']),
  2025. ],
  2026. 'raw_ratio' => $typeRatio,
  2027. ]);
  2028. // 随机打乱桶
  2029. foreach ($buckets as $k => $v) {
  2030. if (!empty($v)) {
  2031. shuffle($v);
  2032. $buckets[$k] = $v;
  2033. }
  2034. }
  2035. $selected = [];
  2036. $selectedIds = [];
  2037. // 按目标数依次取题
  2038. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2039. $need = $targets[$typeKey] ?? 0;
  2040. if ($need <= 0 || empty($buckets[$typeKey])) {
  2041. continue;
  2042. }
  2043. $take = min($need, count($buckets[$typeKey]));
  2044. $slice = array_slice($buckets[$typeKey], 0, $take);
  2045. foreach ($slice as $q) {
  2046. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2047. if (isset($selectedIds[$id])) {
  2048. continue;
  2049. }
  2050. $selected[] = $q;
  2051. $selectedIds[$id] = true;
  2052. }
  2053. }
  2054. // 不足则从剩余题中补齐
  2055. if (count($selected) < $targetCount) {
  2056. $remaining = [];
  2057. foreach ($buckets as $v) {
  2058. foreach ($v as $q) {
  2059. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2060. if (!isset($selectedIds[$id])) {
  2061. $remaining[] = $q;
  2062. }
  2063. }
  2064. }
  2065. shuffle($remaining);
  2066. $needMore = $targetCount - count($selected);
  2067. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2068. }
  2069. // 截断至目标数
  2070. $selected = array_slice($selected, 0, $targetCount);
  2071. // 使用缓存统计题型分布
  2072. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2073. foreach ($selected as $q) {
  2074. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2075. if ($qid && isset($questionTypeCache[$qid])) {
  2076. $type = $questionTypeCache[$qid];
  2077. } else {
  2078. $type = $this->determineQuestionType($q);
  2079. }
  2080. if (isset($selectedCounts[$type])) {
  2081. $selectedCounts[$type]++;
  2082. }
  2083. }
  2084. Log::info('题型配比调整完成', [
  2085. 'target_count' => $targetCount,
  2086. 'targets' => $targets,
  2087. 'selected_counts' => $selectedCounts,
  2088. 'final_selected_count' => count($selected)
  2089. ]);
  2090. return $selected;
  2091. }
  2092. private function determineQuestionType(array $q): string
  2093. {
  2094. // 优先根据题目内容判断(而不是数据库字段)
  2095. $stem = $q['stem'] ?? $q['content'] ?? '';
  2096. // 处理 stem 可能是数组的情况
  2097. if (is_array($stem)) {
  2098. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2099. }
  2100. $tags = $q['tags'] ?? '';
  2101. // 处理 tags 可能是数组的情况
  2102. if (is_array($tags)) {
  2103. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2104. }
  2105. $skills = $q['skills'] ?? [];
  2106. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2107. if (is_string($stem)) {
  2108. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2109. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2110. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2111. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2112. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2113. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2114. // 至少有2个选项就认为是选择题(降低阈值)
  2115. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2116. if ($optionCount >= 2) {
  2117. return 'choice';
  2118. }
  2119. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2120. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2121. return 'choice';
  2122. }
  2123. }
  2124. // 2. 根据技能点判断
  2125. if (is_array($skills) && !empty($skills)) {
  2126. // 过滤非字符串元素,避免 implode 报错
  2127. $skillsFiltered = array_filter($skills, 'is_string');
  2128. if (!empty($skillsFiltered)) {
  2129. $skillsStr = implode(',', $skillsFiltered);
  2130. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2131. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2132. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2133. }
  2134. }
  2135. // 3. 根据题目已有类型字段判断(作为后备)
  2136. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2137. if (is_string($typeField)) {
  2138. $t = strtolower($typeField);
  2139. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2140. return 'choice';
  2141. }
  2142. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2143. return 'fill';
  2144. }
  2145. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2146. return 'answer';
  2147. }
  2148. }
  2149. // 4. 根据标签判断
  2150. if (is_string($tags)) {
  2151. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2152. return 'choice';
  2153. }
  2154. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2155. return 'fill';
  2156. }
  2157. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2158. return 'answer';
  2159. }
  2160. }
  2161. // 5. 根据options字段判断
  2162. if (!empty($q['options']) && is_array($q['options'])) {
  2163. return 'choice';
  2164. }
  2165. // 6. 填空题特征:连续下划线或明显的填空括号
  2166. if (is_string($stem)) {
  2167. // 检查填空题特征:连续下划线
  2168. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2169. return 'fill';
  2170. }
  2171. // 空括号填空
  2172. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2173. return 'fill';
  2174. }
  2175. }
  2176. // 7. 根据题干内容关键词判断
  2177. if (is_string($stem)) {
  2178. // 有证明、解答、计算、求证等关键词的是解答题
  2179. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2180. return 'answer';
  2181. }
  2182. }
  2183. // 默认是解答题(更安全的默认值)
  2184. return 'answer';
  2185. }
  2186. private function mapDifficultyLevel(float $d): string
  2187. {
  2188. if ($d <= 0.4) {
  2189. return '基础';
  2190. }
  2191. if ($d <= 0.7) {
  2192. return '中等';
  2193. }
  2194. return '拔高';
  2195. }
  2196. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2197. {
  2198. $map = [
  2199. '选择题' => 'choice',
  2200. '填空题' => 'fill',
  2201. '解答题' => 'answer',
  2202. ];
  2203. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2204. foreach ($questionTypeRatio as $label => $ratio) {
  2205. $key = $map[$label] ?? null;
  2206. if (!$key) {
  2207. continue;
  2208. }
  2209. $cnt = (int) round($targetCount * ($ratio / 100));
  2210. if ($ratio > 0 && $cnt < 1) {
  2211. $cnt = 1;
  2212. }
  2213. $targets[$key] = $cnt;
  2214. }
  2215. $sum = array_sum($targets);
  2216. if ($sum === 0) {
  2217. $targets['answer'] = $targetCount;
  2218. return $targets;
  2219. }
  2220. while ($sum > $targetCount) {
  2221. arsort($targets);
  2222. foreach ($targets as $k => $v) {
  2223. if ($v > 1) {
  2224. $targets[$k]--;
  2225. $sum--;
  2226. break;
  2227. }
  2228. }
  2229. }
  2230. if ($sum < $targetCount) {
  2231. $ratioByKey = [
  2232. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2233. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2234. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  2235. ];
  2236. while ($sum < $targetCount) {
  2237. arsort($ratioByKey);
  2238. $k = array_key_first($ratioByKey);
  2239. $targets[$k]++;
  2240. $sum++;
  2241. }
  2242. }
  2243. return $targets;
  2244. }
  2245. /**
  2246. * 提交手动评分结果到 LearningAnalytics
  2247. *
  2248. * @param array $data 包含 student_id, paper_id, grades 的数组
  2249. * @return array
  2250. */
  2251. public function submitManualGrading(array $data): array
  2252. {
  2253. try {
  2254. $response = Http::timeout($this->timeout)
  2255. ->post($this->baseUrl . '/api/ocr/analyze', [
  2256. 'student_id' => $data['student_id'],
  2257. 'paper_id' => $data['paper_id'],
  2258. 'answers' => $data['grades'],
  2259. ]);
  2260. if ($response->successful()) {
  2261. Log::info('Manual grading submitted successfully', [
  2262. 'student_id' => $data['student_id'],
  2263. 'paper_id' => $data['paper_id'],
  2264. 'question_count' => count($data['grades'])
  2265. ]);
  2266. return $response->json();
  2267. }
  2268. Log::error('Submit Manual Grading Error', [
  2269. 'data' => $data,
  2270. 'status' => $response->status(),
  2271. 'response' => $response->body()
  2272. ]);
  2273. return [
  2274. 'error' => true,
  2275. 'message' => 'Failed to submit manual grading'
  2276. ];
  2277. } catch (\Exception $e) {
  2278. Log::error('Submit Manual Grading Exception', [
  2279. 'error' => $e->getMessage(),
  2280. 'data' => $data
  2281. ]);
  2282. return [
  2283. 'error' => true,
  2284. 'message' => $e->getMessage()
  2285. ];
  2286. }
  2287. }
  2288. /**
  2289. * 分析学生作答结果
  2290. *
  2291. * @param array $data 包含 paper_id, student_id, answers 等
  2292. * @return array
  2293. */
  2294. public function analyzeStudentAnswers(array $data): array
  2295. {
  2296. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  2297. 'student_id' => $data['student_id'] ?? null,
  2298. 'paper_id' => $data['paper_id'] ?? null,
  2299. ]);
  2300. return [
  2301. 'success' => false,
  2302. 'message' => 'analysis_api_disabled',
  2303. ];
  2304. }
  2305. }