LearningAnalyticsService.php 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247
  1. <?php
  2. namespace App\Services;
  3. use Exception;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Facades\DB;
  7. use App\Services\ExamTypeStrategy;
  8. use App\Services\QuestionExpansionService;
  9. /**
  10. * 学习分析服务(本地化重构版)
  11. *
  12. * 原先调用外部 LearningAnalytics API (localhost:5016)
  13. * 现已重构为使用本地服务:MasteryCalculator、KnowledgeMasteryService 等
  14. */
  15. class LearningAnalyticsService
  16. {
  17. protected string $baseUrl;
  18. protected int $timeout = 10;
  19. protected ?QuestionExpansionService $questionExpansionService;
  20. protected ?MasteryCalculator $masteryCalculator;
  21. protected ?LocalAIAnalysisService $aiAnalysisService;
  22. public function __construct(
  23. ?QuestionExpansionService $questionExpansionService = null,
  24. ?MasteryCalculator $masteryCalculator = null,
  25. ?LocalAIAnalysisService $aiAnalysisService = null
  26. ) {
  27. // 保留baseUrl用于兼容,但不再实际调用
  28. $this->baseUrl = config('services.learning_analytics.url', env('LEARNING_ANALYTICS_API_BASE', 'http://localhost:5016'));
  29. $this->questionExpansionService = $questionExpansionService;
  30. $this->masteryCalculator = $masteryCalculator ?? app(MasteryCalculator::class);
  31. $this->aiAnalysisService = $aiAnalysisService ?? app(LocalAIAnalysisService::class);
  32. }
  33. /**
  34. * 获取学生掌握度(本地化)
  35. */
  36. public function getStudentMastery(string $studentId, string $kpCode = null): array
  37. {
  38. try {
  39. Log::info('LearningAnalyticsService: 获取学生掌握度 (本地)', [
  40. 'student_id' => $studentId,
  41. 'kp_code' => $kpCode
  42. ]);
  43. if ($kpCode) {
  44. // 获取特定知识点掌握度
  45. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  46. return [
  47. 'student_id' => $studentId,
  48. 'kp_code' => $kpCode,
  49. 'mastery_level' => $result['mastery'],
  50. 'confidence' => $result['confidence'],
  51. 'trend' => $result['trend'],
  52. 'total_attempts' => $result['total_attempts'],
  53. 'correct_attempts' => $result['correct_attempts'],
  54. ];
  55. }
  56. // 获取全部知识点掌握度概览
  57. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  58. return [
  59. 'student_id' => $studentId,
  60. 'total_knowledge_points' => $overview['total_knowledge_points'],
  61. 'average_mastery' => $overview['average_mastery_level'],
  62. 'mastered_count' => $overview['mastered_knowledge_points'],
  63. 'good_count' => $overview['good_knowledge_points'],
  64. 'weak_count' => $overview['weak_knowledge_points'],
  65. 'weak_list' => $overview['weak_knowledge_points_list'],
  66. 'details' => $overview['details'],
  67. ];
  68. } catch (\Exception $e) {
  69. Log::error('LearningAnalyticsService: 获取掌握度失败', [
  70. 'student_id' => $studentId,
  71. 'error' => $e->getMessage(),
  72. ]);
  73. return [
  74. 'error' => true,
  75. 'message' => $e->getMessage()
  76. ];
  77. }
  78. }
  79. /**
  80. * 更新学生掌握度(本地化)
  81. */
  82. public function updateMastery(array $data): array
  83. {
  84. try {
  85. $studentId = $data['student_id'];
  86. $kpCode = $data['kp_code'];
  87. $isCorrect = $data['is_correct'] ?? false;
  88. $difficulty = $data['difficulty_level'] ?? 0.5;
  89. Log::info('LearningAnalyticsService: 更新掌握度 (本地)', [
  90. 'student_id' => $studentId,
  91. 'kp_code' => $kpCode,
  92. ]);
  93. // 获取当前掌握度
  94. $currentMastery = DB::table('student_knowledge_mastery')
  95. ->where('student_id', $studentId)
  96. ->where('kp_code', $kpCode)
  97. ->value('mastery_level') ?? 0.5;
  98. // 使用LocalAIAnalysisService更新掌握度
  99. $result = $this->aiAnalysisService->updateMastery(
  100. $studentId,
  101. $kpCode,
  102. $currentMastery,
  103. $isCorrect,
  104. $difficulty
  105. );
  106. return [
  107. 'success' => true,
  108. 'data' => $result
  109. ];
  110. } catch (\Exception $e) {
  111. Log::error('LearningAnalyticsService: 更新掌握度失败', [
  112. 'data' => $data,
  113. 'error' => $e->getMessage(),
  114. ]);
  115. return [
  116. 'error' => true,
  117. 'message' => $e->getMessage()
  118. ];
  119. }
  120. }
  121. /**
  122. * 获取老师名下的所有学生
  123. */
  124. public function getTeacherStudents(string $teacherId): array
  125. {
  126. try {
  127. // 从本地MySQL获取学生
  128. $students = DB::table('students as s')
  129. ->leftJoin('users as u', 's.student_id', '=', 'u.user_id')
  130. ->where('s.teacher_id', $teacherId)
  131. ->select(
  132. 's.student_id',
  133. 's.name',
  134. 's.grade',
  135. 's.class_name',
  136. 'u.username',
  137. 'u.email'
  138. )
  139. ->get()
  140. ->toArray();
  141. return $students;
  142. } catch (\Exception $e) {
  143. Log::error('Get Teacher Students Error', [
  144. 'teacher_id' => $teacherId,
  145. 'error' => $e->getMessage()
  146. ]);
  147. return [];
  148. }
  149. }
  150. /**
  151. * 获取学生学习分析
  152. */
  153. public function getStudentAnalysis(string $studentId): array
  154. {
  155. // 从LearningAnalytics获取掌握度
  156. $masteryData = $this->getStudentMastery($studentId);
  157. // 从MySQL获取练习历史
  158. $exercises = DB::table('student_exercises')
  159. ->where('student_id', $studentId)
  160. ->orderBy('created_at', 'desc')
  161. ->limit(50)
  162. ->get()
  163. ->toArray();
  164. // 从MySQL获取掌握度记录
  165. $masteryRecords = DB::table('student_mastery')
  166. ->where('student_id', $studentId)
  167. ->get()
  168. ->toArray();
  169. return [
  170. 'student_id' => $studentId,
  171. 'mastery_from_la' => $masteryData,
  172. 'exercises' => $exercises,
  173. 'mastery_records' => $masteryRecords,
  174. 'total_exercises' => count($exercises),
  175. 'total_mastery_records' => count($masteryRecords),
  176. ];
  177. }
  178. /**
  179. * 生成学习测试数据
  180. */
  181. public function generateLearningData(string $studentId, array $params): array
  182. {
  183. $results = [];
  184. foreach ($params as $param) {
  185. $data = [
  186. 'student_id' => $studentId,
  187. 'kp_code' => $param['kp_code'],
  188. 'is_correct' => $param['is_correct'],
  189. 'time_spent_seconds' => $param['time_spent_seconds'] ?? 120,
  190. 'difficulty_level' => $param['difficulty_level'] ?? 3,
  191. ];
  192. $result = $this->updateMastery($data);
  193. $results[] = $result;
  194. }
  195. return $results;
  196. }
  197. /**
  198. * 获取学习推荐
  199. */
  200. public function getLearningRecommendations(string $studentId): array
  201. {
  202. try {
  203. Log::info('LearningAnalytics Request: Get Learning Recommendations', [
  204. 'url' => $this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend"
  205. ]);
  206. $response = Http::timeout($this->timeout)
  207. ->post($this->baseUrl . "/api/v1/learning-path/student/{$studentId}/recommend");
  208. Log::info('LearningAnalytics Response: Get Learning Recommendations', [
  209. 'status' => $response->status(),
  210. 'body' => $response->json()
  211. ]);
  212. if ($response->successful()) {
  213. return $response->json();
  214. }
  215. return ['error' => true, 'message' => 'Failed to fetch recommendations'];
  216. } catch (\Exception $e) {
  217. return ['error' => true, 'message' => $e->getMessage()];
  218. }
  219. }
  220. /**
  221. * 获取知识点列表(从知识图谱API)
  222. */
  223. public function getKnowledgePoints(array $filters = []): array
  224. {
  225. try {
  226. $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
  227. Log::info('LearningAnalytics Request: Get Knowledge Points', [
  228. 'url' => $kgBaseUrl . '/knowledge-points/',
  229. 'filters' => $filters
  230. ]);
  231. $response = Http::timeout($this->timeout)
  232. ->get($kgBaseUrl . '/knowledge-points/', $filters);
  233. Log::info('LearningAnalytics Response: Get Knowledge Points', [
  234. 'status' => $response->status(),
  235. 'count' => count($response->json()['data'] ?? [])
  236. ]);
  237. if ($response->successful()) {
  238. return $response->json()['data'] ?? [];
  239. }
  240. return [];
  241. } catch (\Exception $e) {
  242. Log::error('LearningAnalytics Knowledge Points Error', [
  243. 'error' => $e->getMessage()
  244. ]);
  245. return [];
  246. }
  247. }
  248. /**
  249. * 获取学生技能熟练度
  250. */
  251. public function getStudentSkillProficiency(string $studentId): array
  252. {
  253. try {
  254. Log::info('LearningAnalytics Request: Get Student Skill Proficiency', [
  255. 'url' => $this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}"
  256. ]);
  257. $response = Http::timeout($this->timeout)
  258. ->get($this->baseUrl . "/api/v1/skill/proficiency/student/{$studentId}");
  259. Log::info('LearningAnalytics Response: Get Student Skill Proficiency', [
  260. 'status' => $response->status(),
  261. 'body' => $response->json()
  262. ]);
  263. if ($response->successful()) {
  264. return $response->json();
  265. }
  266. Log::warning('LearningAnalytics Skill Proficiency API Error', [
  267. 'student_id' => $studentId,
  268. 'status' => $response->status(),
  269. 'response' => $response->body()
  270. ]);
  271. // API失败时返回空数据,不报错
  272. return [
  273. 'student_id' => $studentId,
  274. 'total_count' => 0,
  275. 'data' => []
  276. ];
  277. } catch (\Exception $e) {
  278. Log::warning('LearningAnalytics Skill Proficiency API Exception', [
  279. 'student_id' => $studentId,
  280. 'error' => $e->getMessage()
  281. ]);
  282. // 发生异常时返回空数据,不报错
  283. return [
  284. 'student_id' => $studentId,
  285. 'total_count' => 0,
  286. 'data' => []
  287. ];
  288. }
  289. }
  290. /**
  291. * 获取学生掌握度列表(别名方法)
  292. */
  293. public function getStudentMasteryList(string $studentId): array
  294. {
  295. return $this->getStudentMastery($studentId);
  296. }
  297. /**
  298. * 获取知识点依赖关系
  299. */
  300. public function getKnowledgeDependencies(): array
  301. {
  302. try {
  303. Log::info('LearningAnalytics Request: Get Knowledge Dependencies', [
  304. 'url' => $this->baseUrl . '/knowledge-dependencies/'
  305. ]);
  306. $response = Http::timeout($this->timeout)
  307. ->get($this->baseUrl . '/knowledge-dependencies/');
  308. Log::info('LearningAnalytics Response: Get Knowledge Dependencies', [
  309. 'status' => $response->status(),
  310. 'count' => count($response->json()['data'] ?? [])
  311. ]);
  312. if ($response->successful()) {
  313. return $response->json()['data'] ?? [];
  314. }
  315. return [];
  316. } catch (\Exception $e) {
  317. Log::error('LearningAnalytics Knowledge Dependencies Error', [
  318. 'error' => $e->getMessage()
  319. ]);
  320. return [];
  321. }
  322. }
  323. /**
  324. * 提交学生答题记录
  325. */
  326. public function submitAttempt(string $studentId, array $attemptData): array
  327. {
  328. try {
  329. Log::info('LearningAnalytics Request: Submit Attempt', [
  330. 'url' => $this->baseUrl . "/api/v1/attempts/student/{$studentId}",
  331. 'data' => $attemptData
  332. ]);
  333. $response = Http::timeout($this->timeout)
  334. ->post($this->baseUrl . "/api/v1/attempts/student/{$studentId}", $attemptData);
  335. Log::info('LearningAnalytics Response: Submit Attempt', [
  336. 'status' => $response->status(),
  337. 'body' => $response->json()
  338. ]);
  339. if ($response->successful()) {
  340. return $response->json();
  341. }
  342. Log::error('Submit Attempt Error', [
  343. 'student_id' => $studentId,
  344. 'data' => $attemptData,
  345. 'status' => $response->status(),
  346. 'response' => $response->body()
  347. ]);
  348. return [
  349. 'error' => true,
  350. 'message' => 'Failed to submit attempt'
  351. ];
  352. } catch (\Exception $e) {
  353. Log::error('Submit Attempt Exception', [
  354. 'student_id' => $studentId,
  355. 'error' => $e->getMessage(),
  356. 'data' => $attemptData
  357. ]);
  358. return [
  359. 'error' => true,
  360. 'message' => $e->getMessage()
  361. ];
  362. }
  363. }
  364. /**
  365. * 批量提交学生答题记录
  366. */
  367. public function submitBatchAttempts(string $studentId, array $data): array
  368. {
  369. try {
  370. Log::info('LearningAnalytics Request: Submit Batch Attempts', [
  371. 'url' => $this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}",
  372. 'data_count' => count($data['answers'] ?? []),
  373. 'paper_id' => $data['paper_id'] ?? null
  374. ]);
  375. $response = Http::timeout($this->timeout)
  376. ->post($this->baseUrl . "/api/v1/attempts/batch/student/{$studentId}", $data);
  377. Log::info('LearningAnalytics Response: Submit Batch Attempts', [
  378. 'status' => $response->status(),
  379. 'body' => $response->json()
  380. ]);
  381. if ($response->successful()) {
  382. return $response->json();
  383. }
  384. Log::error('Submit Batch Attempts Error', [
  385. 'student_id' => $studentId,
  386. 'data_count' => count($data['answers'] ?? []),
  387. 'status' => $response->status(),
  388. 'response' => $response->body()
  389. ]);
  390. return [
  391. 'error' => true,
  392. 'message' => 'Failed to submit batch attempts: ' . $response->body()
  393. ];
  394. } catch (\Exception $e) {
  395. Log::error('Submit Batch Attempts Exception', [
  396. 'student_id' => $studentId,
  397. 'error' => $e->getMessage()
  398. ]);
  399. return [
  400. 'error' => true,
  401. 'message' => $e->getMessage()
  402. ];
  403. }
  404. }
  405. /**
  406. * 提交OCR分析请求
  407. */
  408. public function submitOCRAnalysis(array $data): array
  409. {
  410. Log::warning('submitOCRAnalysis 已停用:分析项目已下线', [
  411. 'student_id' => $data['student_id'] ?? 'unknown',
  412. 'exam_id' => $data['exam_id'] ?? 'unknown',
  413. ]);
  414. return [
  415. 'success' => false,
  416. 'message' => 'analysis_api_disabled',
  417. ];
  418. }
  419. /**
  420. * 获取分析结果详情
  421. */
  422. public function getAnalysisResult(string $analysisId): array
  423. {
  424. Log::warning('getAnalysisResult 已停用:分析项目已下线', [
  425. 'analysis_id' => $analysisId,
  426. ]);
  427. return [
  428. 'success' => false,
  429. 'message' => 'analysis_api_disabled',
  430. ];
  431. }
  432. /**
  433. * 检查服务健康状态(本地化)
  434. */
  435. public function checkHealth(): bool
  436. {
  437. // 检查本地服务是否可用
  438. try {
  439. $this->masteryCalculator->getStudentMasteryOverview('test');
  440. return true;
  441. } catch (\Exception $e) {
  442. return false;
  443. }
  444. }
  445. /**
  446. * 获取学生掌握度概览(本地化)
  447. */
  448. public function getStudentMasteryOverview(string $studentId): array
  449. {
  450. try {
  451. // 直接使用MasteryCalculator
  452. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  453. return [
  454. 'total_knowledge_points' => $overview['total_knowledge_points'],
  455. 'average_mastery_level' => $overview['average_mastery_level'],
  456. 'mastered_knowledge_points' => $overview['mastered_knowledge_points'],
  457. 'good_knowledge_points' => $overview['good_knowledge_points'],
  458. 'weak_knowledge_points' => $overview['weak_knowledge_points'],
  459. 'weak_knowledge_points_list' => $overview['weak_knowledge_points_list'],
  460. 'details' => $overview['details']
  461. ];
  462. } catch (\Exception $e) {
  463. Log::error('Get Student Mastery Overview Error', [
  464. 'student_id' => $studentId,
  465. 'error' => $e->getMessage()
  466. ]);
  467. return [
  468. 'total_knowledge_points' => 0,
  469. 'average_mastery_level' => 0,
  470. 'mastered_knowledge_points' => 0,
  471. 'good_knowledge_points' => 0,
  472. 'weak_knowledge_points' => 0,
  473. 'weak_knowledge_points_list' => [],
  474. 'details' => []
  475. ];
  476. }
  477. }
  478. /**
  479. * 获取学生技能摘要
  480. */
  481. public function getStudentSkillSummary(string $studentId): array
  482. {
  483. try {
  484. $proficiency = $this->getStudentSkillProficiency($studentId);
  485. // 无论是否有error,都继续处理,返回空数据
  486. $data = $proficiency['data'] ?? [];
  487. $totalSkills = count($data);
  488. $averageLevel = $totalSkills > 0 ? array_sum(array_column($data, 'proficiency_level')) / $totalSkills : 0;
  489. // 计算总答题数
  490. $totalQuestions = 0;
  491. foreach ($data as $skill) {
  492. $totalQuestions += $skill['total_questions_attempted'] ?? 0;
  493. }
  494. return [
  495. 'total_skills' => $totalSkills,
  496. 'average_proficiency_level' => $averageLevel,
  497. 'total_questions_attempted' => $totalQuestions,
  498. 'skill_list' => $data
  499. ];
  500. } catch (\Exception $e) {
  501. Log::warning('Get Student Skill Summary Error', [
  502. 'student_id' => $studentId,
  503. 'error' => $e->getMessage()
  504. ]);
  505. // 发生异常时返回空数据
  506. return [
  507. 'total_skills' => 0,
  508. 'average_proficiency_level' => 0,
  509. 'total_questions_attempted' => 0,
  510. 'skill_list' => []
  511. ];
  512. }
  513. }
  514. /**
  515. * 获取学生预测数据(本地化 - 已停用外部API)
  516. */
  517. public function getStudentPredictions(string $studentId, int $count = 5): array
  518. {
  519. // 外部API已停用,基于本地数据生成预测
  520. try {
  521. Log::info('LearningAnalyticsService: 获取学生预测 (本地)', [
  522. 'student_id' => $studentId,
  523. ]);
  524. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  525. $avgMastery = $overview['average_mastery_level'] ?? 0;
  526. // 基于掌握度生成简单预测
  527. $predictions = [];
  528. if ($avgMastery > 0) {
  529. $predictions[] = [
  530. 'type' => 'score_improvement',
  531. 'current_level' => round($avgMastery * 100),
  532. 'predicted_improvement' => rand(5, 15),
  533. 'confidence' => 0.75,
  534. ];
  535. }
  536. return [
  537. 'predictions' => $predictions
  538. ];
  539. } catch (\Exception $e) {
  540. Log::error('Get Student Predictions Error', [
  541. 'student_id' => $studentId,
  542. 'error' => $e->getMessage()
  543. ]);
  544. return [
  545. 'predictions' => []
  546. ];
  547. }
  548. }
  549. /**
  550. * 获取学生学习路径(本地化 - 已停用外部API)
  551. */
  552. public function getStudentLearningPaths(string $studentId, int $count = 3): array
  553. {
  554. // 外部API已停用,基于薄弱点生成学习路径
  555. try {
  556. Log::info('LearningAnalyticsService: 获取学习路径 (本地)', [
  557. 'student_id' => $studentId,
  558. ]);
  559. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  560. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  561. $paths = [];
  562. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  563. $paths[] = [
  564. 'kp_code' => $weak->kp_code ?? $weak['kp_code'] ?? '',
  565. 'current_mastery' => $weak->mastery_level ?? $weak['mastery_level'] ?? 0,
  566. 'target_mastery' => 0.85,
  567. 'recommended_practice' => 5,
  568. ];
  569. }
  570. return [
  571. 'paths' => $paths
  572. ];
  573. } catch (\Exception $e) {
  574. Log::error('Get Student Learning Paths Error', [
  575. 'student_id' => $studentId,
  576. 'error' => $e->getMessage()
  577. ]);
  578. return [
  579. 'paths' => []
  580. ];
  581. }
  582. }
  583. /**
  584. * 获取预测分析数据
  585. */
  586. public function getPredictionAnalytics(string $studentId): array
  587. {
  588. try {
  589. $predictions = $this->getStudentPredictions($studentId, 10);
  590. if (empty($predictions)) {
  591. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  592. }
  593. $accuracy = 0;
  594. $confidence = 0;
  595. if (!empty($predictions)) {
  596. $accuracy = rand(75, 95); // 模拟准确率
  597. $confidence = rand(70, 90); // 模拟置信度
  598. }
  599. $trend = 'improving'; // improving, stable, declining
  600. return [
  601. 'accuracy' => $accuracy,
  602. 'trend' => $trend,
  603. 'confidence' => $confidence,
  604. 'sample_size' => count($predictions)
  605. ];
  606. } catch (\Exception $e) {
  607. Log::error('Get Prediction Analytics Error', [
  608. 'student_id' => $studentId,
  609. 'error' => $e->getMessage()
  610. ]);
  611. return ['accuracy' => 0, 'trend' => 'stable', 'confidence' => 0];
  612. }
  613. }
  614. /**
  615. * 获取学习路径分析数据
  616. */
  617. public function getLearningPathAnalytics(string $studentId): array
  618. {
  619. try {
  620. $paths = $this->getStudentLearningPaths($studentId, 5);
  621. if (empty($paths)) {
  622. return [
  623. 'active_paths' => 0,
  624. 'completed_paths' => 0,
  625. 'average_efficiency_score' => 0,
  626. 'completion_rate' => 0,
  627. 'average_time' => 0,
  628. 'total_paths' => 0
  629. ];
  630. }
  631. $activePaths = 0;
  632. $completedPaths = 0;
  633. $efficiencyScores = [];
  634. foreach ($paths as $path) {
  635. if (($path['status'] ?? '') === 'active') {
  636. $activePaths++;
  637. }
  638. if (($path['status'] ?? '') === 'completed') {
  639. $completedPaths++;
  640. }
  641. if (isset($path['efficiency_score'])) {
  642. $efficiencyScores[] = $path['efficiency_score'];
  643. }
  644. }
  645. $averageEfficiency = !empty($efficiencyScores)
  646. ? array_sum($efficiencyScores) / count($efficiencyScores)
  647. : rand(60, 85) / 100;
  648. $completionRate = count($paths) > 0
  649. ? ($completedPaths / count($paths)) * 100
  650. : 0;
  651. $averageTime = rand(30, 60); // 模拟平均时间(分钟)
  652. return [
  653. 'active_paths' => $activePaths,
  654. 'completed_paths' => $completedPaths,
  655. 'average_efficiency_score' => $averageEfficiency,
  656. 'completion_rate' => $completionRate,
  657. 'average_time' => $averageTime,
  658. 'total_paths' => count($paths)
  659. ];
  660. } catch (\Exception $e) {
  661. Log::error('Get Learning Path Analytics Error', [
  662. 'student_id' => $studentId,
  663. 'error' => $e->getMessage()
  664. ]);
  665. return [
  666. 'active_paths' => 0,
  667. 'completed_paths' => 0,
  668. 'average_efficiency_score' => 0,
  669. 'completion_rate' => 0,
  670. 'average_time' => 0,
  671. 'total_paths' => 0
  672. ];
  673. }
  674. }
  675. /**
  676. * 快速分数预测
  677. */
  678. public function quickScorePrediction(string $studentId): array
  679. {
  680. Log::info('开始调用快速预测API', ['student_id' => $studentId]);
  681. $response = Http::timeout($this->timeout)
  682. ->post($this->baseUrl . "/api/v1/prediction/student/{$studentId}/quick-prediction");
  683. Log::info('快速预测API响应', [
  684. 'student_id' => $studentId,
  685. 'status' => $response->status(),
  686. 'body' => $response->body()
  687. ]);
  688. if (!$response->successful()) {
  689. throw new \Exception(sprintf(
  690. '快速预测接口失败: %s %s',
  691. $response->status(),
  692. $response->body()
  693. ));
  694. }
  695. $data = $response->json();
  696. Log::info('快速预测API返回数据', ['student_id' => $studentId, 'data' => $data]);
  697. // API 返回结构:{ student_id, current_assumption, target_assumption, quick_prediction, prediction_id, message }
  698. $quickPredictionData = $data['quick_prediction'] ?? [];
  699. return [
  700. 'quick_prediction' => [
  701. 'current_score' => $quickPredictionData['current_score'] ?? $data['current_assumption'] ?? 0,
  702. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  703. 'improvement_potential' => $quickPredictionData['improvement_potential'] ?? (($data['target_assumption'] ?? 0) - ($data['current_assumption'] ?? 0)),
  704. 'estimated_study_hours' => $quickPredictionData['estimated_study_hours'] ?? 0,
  705. 'confidence_level' => $quickPredictionData['confidence_level'] ?? 0,
  706. 'priority_topics' => $quickPredictionData['priority_topics'] ?? [],
  707. 'recommended_actions' => $quickPredictionData['recommended_actions'] ?? [],
  708. 'weak_knowledge_points_count' => $quickPredictionData['weak_knowledge_points_count'] ?? 0,
  709. 'total_knowledge_points' => $quickPredictionData['total_knowledge_points'] ?? 0
  710. ],
  711. 'predicted_score' => $quickPredictionData['predicted_score'] ?? $data['target_assumption'] ?? 0,
  712. 'confidence' => isset($quickPredictionData['confidence_level']) ? $quickPredictionData['confidence_level'] * 100 : 0,
  713. 'time_estimate' => $quickPredictionData['estimated_study_hours'] ?? 0,
  714. 'prediction_id' => $data['prediction_id'] ?? null,
  715. 'message' => $data['message'] ?? null,
  716. ];
  717. }
  718. /**
  719. * 推荐学习路径(本地化)
  720. */
  721. public function recommendLearningPaths(string $studentId, int $count = 3): array
  722. {
  723. try {
  724. Log::info('LearningAnalyticsService: 推荐学习路径 (本地)', [
  725. 'student_id' => $studentId,
  726. ]);
  727. $overview = $this->masteryCalculator->getStudentMasteryOverview($studentId);
  728. $weakPoints = $overview['weak_knowledge_points_list'] ?? [];
  729. $recommendations = [];
  730. foreach (array_slice($weakPoints, 0, $count) as $weak) {
  731. $kpCode = is_object($weak) ? $weak->kp_code : ($weak['kp_code'] ?? '');
  732. $masteryLevel = is_object($weak) ? $weak->mastery_level : ($weak['mastery_level'] ?? 0);
  733. $recommendations[] = [
  734. 'kp_code' => $kpCode,
  735. 'kp_name' => $this->getKnowledgePointName($kpCode),
  736. 'current_mastery' => $masteryLevel,
  737. 'target_mastery' => 0.85,
  738. 'priority' => 1 - $masteryLevel,
  739. 'recommended_practice_count' => max(3, intval((0.85 - $masteryLevel) * 10)),
  740. 'estimated_time_minutes' => max(15, intval((0.85 - $masteryLevel) * 60)),
  741. ];
  742. }
  743. return [
  744. 'recommendations' => $recommendations
  745. ];
  746. } catch (\Exception $e) {
  747. Log::error('Recommend Learning Paths Error', [
  748. 'student_id' => $studentId,
  749. 'error' => $e->getMessage()
  750. ]);
  751. return [
  752. 'recommendations' => []
  753. ];
  754. }
  755. }
  756. /**
  757. * 获取知识点名称
  758. */
  759. private function getKnowledgePointName(string $kpCode): string
  760. {
  761. try {
  762. $kp = DB::table('knowledge_points')
  763. ->where('kp_code', $kpCode)
  764. ->value('name');
  765. return $kp ?? $kpCode;
  766. } catch (\Exception $e) {
  767. return $kpCode;
  768. }
  769. }
  770. /**
  771. * 重新计算掌握度(本地化)
  772. */
  773. public function recalculateMastery(string $studentId, string $kpCode): bool
  774. {
  775. try {
  776. Log::info('LearningAnalyticsService: 重新计算掌握度 (本地)', [
  777. 'student_id' => $studentId,
  778. 'kp_code' => $kpCode,
  779. ]);
  780. // 使用MasteryCalculator重新计算
  781. $result = $this->masteryCalculator->calculateMasteryLevel($studentId, $kpCode);
  782. // 更新到数据库
  783. DB::table('student_knowledge_mastery')
  784. ->updateOrInsert(
  785. ['student_id' => $studentId, 'kp_code' => $kpCode],
  786. [
  787. 'mastery_level' => $result['mastery'],
  788. 'confidence_level' => $result['confidence'],
  789. 'total_attempts' => $result['total_attempts'],
  790. 'correct_attempts' => $result['correct_attempts'],
  791. 'mastery_trend' => $result['trend'],
  792. 'last_mastery_update' => now(),
  793. 'updated_at' => now(),
  794. ]
  795. );
  796. return true;
  797. } catch (\Exception $e) {
  798. Log::error('Recalculate Mastery Error', [
  799. 'student_id' => $studentId,
  800. 'kp_code' => $kpCode,
  801. 'error' => $e->getMessage()
  802. ]);
  803. return false;
  804. }
  805. }
  806. /**
  807. * 批量更新技能熟练度(本地化)
  808. */
  809. public function batchUpdateSkillProficiency(string $studentId): bool
  810. {
  811. try {
  812. Log::info('LearningAnalyticsService: 批量更新技能熟练度 (本地)', [
  813. 'student_id' => $studentId,
  814. ]);
  815. // 获取学生所有知识点
  816. $kpCodes = DB::table('student_knowledge_mastery')
  817. ->where('student_id', $studentId)
  818. ->pluck('kp_code')
  819. ->toArray();
  820. // 批量更新
  821. $this->masteryCalculator->batchUpdateMastery($studentId, $kpCodes);
  822. return true;
  823. } catch (\Exception $e) {
  824. Log::error('Batch Update Skill Proficiency Error', [
  825. 'student_id' => $studentId,
  826. 'error' => $e->getMessage()
  827. ]);
  828. return false;
  829. }
  830. }
  831. /**
  832. * 清空学生所有答题数据(本地化)
  833. */
  834. public function clearStudentData(string $studentId): bool
  835. {
  836. try {
  837. Log::info('LearningAnalyticsService: 清空学生数据 (本地)', [
  838. 'student_id' => $studentId,
  839. ]);
  840. // 清空MySQL中的数据
  841. $this->clearStudentMySQLData($studentId);
  842. Log::info('Student Data Cleared Successfully', [
  843. 'student_id' => $studentId,
  844. ]);
  845. return true;
  846. } catch (\Exception $e) {
  847. Log::error('Clear Student Data Error', [
  848. 'student_id' => $studentId,
  849. 'error' => $e->getMessage()
  850. ]);
  851. return false;
  852. }
  853. }
  854. /**
  855. * 清空学生MySQL中的答题数据
  856. */
  857. private function clearStudentMySQLData(string $studentId): void
  858. {
  859. try {
  860. // 清空student_exercises表
  861. DB::table('student_exercises')
  862. ->where('student_id', $studentId)
  863. ->delete();
  864. // 清空student_mastery表
  865. DB::table('student_mastery')
  866. ->where('student_id', $studentId)
  867. ->delete();
  868. Log::info('Student MySQL Data Cleared', [
  869. 'student_id' => $studentId
  870. ]);
  871. } catch (\Exception $e) {
  872. Log::error('Clear Student MySQL Data Error', [
  873. 'student_id' => $studentId,
  874. 'error' => $e->getMessage()
  875. ]);
  876. throw $e; // 重新抛出异常,让上层处理
  877. }
  878. }
  879. /**
  880. * 获取学生列表(供智能出卷使用)
  881. */
  882. public function getStudentsList(): array
  883. {
  884. try {
  885. $response = Http::timeout($this->timeout)
  886. ->get($this->baseUrl . '/api/v1/students/list');
  887. if ($response->successful()) {
  888. return $response->json('data', []);
  889. }
  890. // 如果API失败,尝试从MySQL直接读取
  891. return $this->getStudentsFromMySQL();
  892. } catch (\Exception $e) {
  893. Log::error('Get Students List Error', [
  894. 'error' => $e->getMessage()
  895. ]);
  896. // 返回模拟数据
  897. return [
  898. ['student_id' => 'stu_001', 'name' => '张三'],
  899. ['student_id' => 'stu_002', 'name' => '李四'],
  900. ['student_id' => 'stu_003', 'name' => '王五'],
  901. ];
  902. }
  903. }
  904. /**
  905. * 从MySQL获取学生列表
  906. */
  907. private function getStudentsFromMySQL(): array
  908. {
  909. try {
  910. return DB::table('students')
  911. ->select('student_id', 'name')
  912. ->limit(100)
  913. ->get()
  914. ->toArray();
  915. } catch (\Exception $e) {
  916. Log::error('Get Students From MySQL Error', [
  917. 'error' => $e->getMessage()
  918. ]);
  919. return [];
  920. }
  921. }
  922. /**
  923. * 获取学生薄弱点列表
  924. * 策略:MySQL作为权威数据源,LearningAnalytics API仅作为辅助/缓存
  925. */
  926. public function getStudentWeaknesses(string $studentId, int $limit = 10): array
  927. {
  928. try {
  929. // 从本地MySQL数据库获取学生薄弱点
  930. Log::info('从本地MySQL数据库获取学生薄弱点', [
  931. 'student_id' => $studentId,
  932. 'limit' => $limit
  933. ]);
  934. $weaknesses = $this->getStudentWeaknessesFromMySQL($studentId, $limit);
  935. if (!empty($weaknesses)) {
  936. Log::info('从本地数据库获取到薄弱点数据', [
  937. 'student_id' => $studentId,
  938. 'count' => count($weaknesses)
  939. ]);
  940. return $weaknesses;
  941. }
  942. Log::warning('本地数据库中无该学生薄弱点数据', [
  943. 'student_id' => $studentId
  944. ]);
  945. return [];
  946. } catch (\Exception $e) {
  947. Log::error('Get Student Weaknesses Error', [
  948. 'student_id' => $studentId,
  949. 'error' => $e->getMessage()
  950. ]);
  951. // 发生异常时,返回空数组
  952. return [];
  953. }
  954. }
  955. /**
  956. * 从MySQL获取学生薄弱点
  957. */
  958. private function getStudentWeaknessesFromMySQL(string $studentId, int $limit = 10): array
  959. {
  960. try {
  961. // 优先从 student_knowledge_mastery 表读取(更完整的掌握度数据)
  962. $weaknesses = DB::table('student_knowledge_mastery as skm')
  963. ->where('skm.student_id', $studentId)
  964. ->where('skm.mastery_level', '<', 0.9) // 掌握度低于70%视为薄弱点
  965. ->orderBy('skm.mastery_level', 'asc')
  966. ->limit($limit)
  967. ->select([
  968. 'skm.kp_code',
  969. 'skm.mastery_level',
  970. 'skm.total_attempts',
  971. 'skm.correct_attempts',
  972. 'skm.incorrect_attempts',
  973. 'skm.confidence_level',
  974. 'skm.mastery_trend'
  975. ])
  976. ->get()
  977. ->toArray();
  978. // 如果student_knowledge_mastery表没有数据,尝试从student_mastery表读取
  979. if (empty($weaknesses)) {
  980. Log::info('student_knowledge_mastery表无数据,尝试从student_mastery表读取', [
  981. 'student_id' => $studentId
  982. ]);
  983. $weaknesses = DB::table('student_mastery as sm')
  984. ->leftJoin('knowledge_points as kp', 'sm.kp', '=', 'kp.kp_code')
  985. ->where('sm.student_id', $studentId)
  986. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  987. ->orderBy('sm.mastery', 'asc')
  988. ->limit($limit)
  989. ->select([
  990. 'sm.kp as kp_code',
  991. 'kp.name as kp_name',
  992. 'sm.mastery',
  993. 'sm.attempts',
  994. 'sm.correct'
  995. ])
  996. ->get()
  997. ->toArray();
  998. // 转换为统一格式
  999. return array_map(function ($item) {
  1000. $mastery = (float) ($item->mastery ?? 0);
  1001. $attempts = (int) ($item->attempts ?? 0);
  1002. $correct = (int) ($item->correct ?? 0);
  1003. return [
  1004. 'kp_code' => $item->kp_code,
  1005. 'kp_name' => $item->kp_name ?? $item->kp_code,
  1006. 'mastery' => $mastery,
  1007. 'stability' => 0.5, // 默认稳定性
  1008. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1009. 'practice_count' => $attempts,
  1010. 'success_rate' => $attempts > 0 ? ($correct / $attempts) : 0,
  1011. 'priority' => $mastery < 0.3 ? '高' : ($mastery < 0.5 ? '中' : '低'),
  1012. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)) // 掌握度越低,建议题目越多
  1013. ];
  1014. }, $weaknesses);
  1015. }
  1016. // 转换student_knowledge_mastery表的数据格式
  1017. return array_map(function ($item) {
  1018. $mastery = (float) ($item->mastery_level ?? 0);
  1019. $totalAttempts = (int) ($item->total_attempts ?? 0);
  1020. $correctAttempts = (int) ($item->correct_attempts ?? 0);
  1021. $incorrectAttempts = (int) ($item->incorrect_attempts ?? 0);
  1022. $confidence = (float) ($item->confidence_level ?? 0.5);
  1023. $trend = $item->mastery_trend ?? 'stable';
  1024. // 计算成功率
  1025. $successRate = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : 0;
  1026. // 确定优先级
  1027. $priority = '中';
  1028. if ($mastery < 0.3) {
  1029. $priority = '高';
  1030. } elseif ($mastery < 0.5) {
  1031. $priority = '中';
  1032. } else {
  1033. $priority = '低';
  1034. }
  1035. return [
  1036. 'kp_code' => $item->kp_code,
  1037. 'kp_name' => $item->kp_code, // 如果没有中文名,使用代码作为名称
  1038. 'mastery' => $mastery,
  1039. 'stability' => $confidence,
  1040. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1041. 'practice_count' => $totalAttempts,
  1042. 'success_rate' => $successRate,
  1043. 'priority' => $priority,
  1044. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)), // 掌握度越低,建议题目越多
  1045. 'trend' => $trend,
  1046. 'correct_attempts' => $correctAttempts,
  1047. 'incorrect_attempts' => $incorrectAttempts
  1048. ];
  1049. }, $weaknesses);
  1050. } catch (\Exception $e) {
  1051. Log::error('Get Student Weaknesses From MySQL Error', [
  1052. 'student_id' => $studentId,
  1053. 'error' => $e->getMessage(),
  1054. 'trace' => $e->getTraceAsString()
  1055. ]);
  1056. return [];
  1057. }
  1058. }
  1059. /**
  1060. * 智能出卷:根据学生掌握度智能选择题目
  1061. */
  1062. public function generateIntelligentExam(array $params): array
  1063. {
  1064. $startTime = microtime(true);
  1065. try {
  1066. // 应用组卷类型策略
  1067. $assembleType = (int) ($params['assemble_type'] ?? 4); // 默认为通用类型(4)
  1068. $examTypeLegacy = $params['exam_type'] ?? 'general'; // 兼容旧版参数
  1069. Log::info('LearningAnalyticsService: 检查组卷策略', [
  1070. 'assemble_type' => $assembleType,
  1071. 'exam_type_legacy' => $examTypeLegacy,
  1072. 'has_question_expansion_service' => !empty($this->questionExpansionService)
  1073. ]);
  1074. // 如果有 assemble_type 参数,优先使用新的参数系统
  1075. if (isset($params['assemble_type'])) {
  1076. try {
  1077. // 确保QuestionExpansionService和QuestionLocalService可用
  1078. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1079. $questionLocalService = app(QuestionLocalService::class);
  1080. Log::info('LearningAnalyticsService: 从容器获取服务实例');
  1081. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1082. $params = $strategy->buildParams($params, $assembleType);
  1083. Log::info('LearningAnalyticsService: 已应用组卷策略', [
  1084. 'assemble_type' => $assembleType,
  1085. 'enhanced_params_keys' => array_keys($params)
  1086. ]);
  1087. } catch (Exception $e) {
  1088. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1089. 'assemble_type' => $assembleType,
  1090. 'error' => $e->getMessage(),
  1091. 'trace' => $e->getTraceAsString()
  1092. ]);
  1093. }
  1094. } elseif ($examTypeLegacy !== 'general') {
  1095. // 兼容旧版 exam_type 参数
  1096. try {
  1097. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1098. $questionLocalService = app(QuestionLocalService::class);
  1099. Log::info('LearningAnalyticsService: 从容器获取服务实例(兼容模式)');
  1100. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1101. $params = $strategy->buildParamsLegacy($params, $examTypeLegacy);
  1102. Log::info('LearningAnalyticsService: 已应用组卷策略(兼容模式)', [
  1103. 'exam_type' => $examTypeLegacy,
  1104. 'enhanced_params_keys' => array_keys($params)
  1105. ]);
  1106. } catch (Exception $e) {
  1107. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1108. 'exam_type' => $examTypeLegacy,
  1109. 'error' => $e->getMessage(),
  1110. 'trace' => $e->getTraceAsString()
  1111. ]);
  1112. }
  1113. } else {
  1114. Log::info('LearningAnalyticsService: 跳过组卷策略', [
  1115. 'reason' => '通用类型不需要特殊策略'
  1116. ]);
  1117. }
  1118. $studentId = $params['student_id'] ?? null;
  1119. $grade = $params['grade'] ?? null; // 用户选择的年级
  1120. $totalQuestions = $params['total_questions'] ?? 20;
  1121. // 【修复】参数映射:支持 kp_codes 和 kp_code_list 两种参数名
  1122. $kpCodes = $params['kp_codes'] ?? $params['kp_code_list'] ?? [];
  1123. if (!is_array($kpCodes)) {
  1124. $kpCodes = [];
  1125. }
  1126. $skills = $params['skills'] ?? [];
  1127. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1128. '选择题' => 40,
  1129. '填空题' => 30,
  1130. '解答题' => 30,
  1131. ];
  1132. // 新增:题目分类筛选
  1133. $questionCategory = $params['question_category'] ?? null;
  1134. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  1135. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1136. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1137. Log::info("generateIntelligentExam 开始", [
  1138. 'student_id' => $studentId,
  1139. 'total_questions' => $totalQuestions,
  1140. 'kp_codes' => $kpCodes,
  1141. 'skills' => $skills,
  1142. 'assemble_type' => $assembleType,
  1143. 'exam_type_legacy' => $examTypeLegacy,
  1144. 'question_category' => $questionCategory,
  1145. ]);
  1146. // 1. 如果指定了学生,获取学生的薄弱点
  1147. $weaknessFilter = [];
  1148. if ($studentId) {
  1149. Log::info("获取学生薄弱点: $studentId");
  1150. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1151. Log::info("薄弱点数量: " . count($weaknesses), [
  1152. '薄弱点' => $weaknesses,
  1153. ]);
  1154. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1155. // 【修复】教材出卷(assemble_type=3)不使用薄弱点,严格按章节获取知识点
  1156. if ($assembleType == 3) {
  1157. Log::info("LearningAnalyticsService: 教材出卷不使用薄弱点", [
  1158. 'assemble_type' => $assembleType,
  1159. 'weakness_count' => count($weaknessFilter),
  1160. 'action' => '将使用ExamTypeStrategy从章节关联获取的知识点'
  1161. ]);
  1162. // 教材组卷不使用薄弱点
  1163. } else {
  1164. // 如果用户没有指定知识点,使用学生的薄弱点(非教材组卷)
  1165. if (empty($kpCodes)) {
  1166. $kpCodes = $weaknessFilter;
  1167. Log::info("用户未选择知识点,使用薄弱点作为kp_codes", [
  1168. '最终kp_codes' => $kpCodes,
  1169. ]);
  1170. }
  1171. }
  1172. }
  1173. Log::info("准备调用 getQuestionsFromBank", [
  1174. 'kp_codes' => $kpCodes,
  1175. 'skills' => $skills,
  1176. ]);
  1177. // 2. 优先使用学生错题(如果存在)
  1178. $mistakeQuestionIds = $params['mistake_question_ids'] ?? [];
  1179. $priorityQuestions = [];
  1180. $maxQuestions = 50; // 错题最大题目数限制
  1181. $poolLimit = 0; // 题库池不设上限,0 表示不限制
  1182. if (!empty($mistakeQuestionIds)) {
  1183. Log::info('LearningAnalyticsService: 优先获取学生错题', [
  1184. 'mistake_question_ids' => $mistakeQuestionIds,
  1185. 'count' => count($mistakeQuestionIds),
  1186. 'max_limit' => $maxQuestions
  1187. ]);
  1188. // 如果错题超过最大值,截取到最大值
  1189. $truncatedMistakeIds = $mistakeQuestionIds;
  1190. if (count($mistakeQuestionIds) > $maxQuestions) {
  1191. Log::warning('LearningAnalyticsService: 错题数量超过最大值限制,已截取', [
  1192. 'mistake_count' => count($mistakeQuestionIds),
  1193. 'max_limit' => $maxQuestions,
  1194. 'truncated_count' => $maxQuestions
  1195. ]);
  1196. $truncatedMistakeIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  1197. }
  1198. // 获取学生错题的详细信息(错题获取不需要智能补充,不传入 grade/textbook_id)
  1199. $priorityQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $truncatedMistakeIds, [], null, null, null, null, 1);
  1200. Log::info('LearningAnalyticsService: 错题获取完成', [
  1201. 'priority_questions_count' => count($priorityQuestions),
  1202. 'expected_count' => count($truncatedMistakeIds)
  1203. ]);
  1204. // 如果获取的错题数量少于预期,记录警告
  1205. if (count($priorityQuestions) < count($truncatedMistakeIds)) {
  1206. Log::warning('LearningAnalyticsService: 错题获取不完整', [
  1207. 'expected' => count($truncatedMistakeIds),
  1208. 'actual' => count($priorityQuestions),
  1209. 'missing_ids' => array_diff($truncatedMistakeIds, array_column($priorityQuestions, 'id'))
  1210. ]);
  1211. }
  1212. }
  1213. // 3. 处理错题本逻辑
  1214. $allQuestions = $priorityQuestions;
  1215. $isMistakeBook = ($assembleType === 5); // 错题本类型
  1216. $hasMistakePriority = !empty($priorityQuestions);
  1217. $strictMistakeBook = $isMistakeBook && $hasMistakePriority;
  1218. // 【修改】错题本类型严格按错题组卷,不补充题目
  1219. if ($isMistakeBook) {
  1220. // 记录错题本组卷信息
  1221. Log::info('LearningAnalyticsService: 错题本严格按错题组卷,不补充题目', [
  1222. 'mistake_count' => count($priorityQuestions),
  1223. 'assemble_type' => $assembleType,
  1224. 'action' => '只使用学生错题,不从原卷子补充'
  1225. ]);
  1226. // 如果完全没有错题,回退到知识点/题库组卷
  1227. if (!$hasMistakePriority) {
  1228. Log::warning('LearningAnalyticsService: 错题本无错题', [
  1229. 'student_id' => $studentId,
  1230. 'paper_ids' => $params['paper_ids'] ?? []
  1231. ]);
  1232. Log::info('LearningAnalyticsService: 错题本无错题,允许补充题目', [
  1233. 'assemble_type' => $assembleType,
  1234. 'action' => 'fallback_to_kp_or_bank'
  1235. ]);
  1236. }
  1237. }
  1238. if (!$strictMistakeBook && count($priorityQuestions) < $totalQuestions) {
  1239. try {
  1240. // 【优化】教材出卷(assemble_type=3)保留知识点筛选,但额外使用章节筛选
  1241. if ($assembleType == 3) {
  1242. Log::info('LearningAnalyticsService: 教材出卷模式,保留知识点筛选', [
  1243. 'assemble_type' => $assembleType,
  1244. 'kp_codes_count' => count($kpCodes),
  1245. 'chapter_ids' => $params['chapter_id_list'] ?? [],
  1246. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? [],
  1247. ]);
  1248. }
  1249. // 【优化】获取textbook_catalog_node_ids参数(教材组卷时使用)
  1250. $textbookCatalogNodeIds = $params['textbook_catalog_node_ids'] ?? null;
  1251. // 【修复超纲问题】获取 textbook_id 和 difficulty_category,用于智能补充时限制范围
  1252. $textbookId = isset($params['textbook_id']) ? (int) $params['textbook_id'] : null;
  1253. $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
  1254. Log::info('开始调用 getQuestionsFromBank 补充题目', [
  1255. 'kp_codes_count' => count($kpCodes),
  1256. 'skills_count' => count($skills),
  1257. 'has_mistake_priority' => !empty($mistakeQuestionIds),
  1258. 'need_more' => $totalQuestions - count($priorityQuestions),
  1259. 'assemble_type' => $assembleType,
  1260. 'grade' => $grade,
  1261. 'textbook_id' => $textbookId,
  1262. 'difficulty_category' => $difficultyCategory,
  1263. 'note' => $textbookId ? '将使用 textbook_id 限制补充范围,避免超纲' : '未指定教材,使用整个年级范围'
  1264. ]);
  1265. // 【修复超纲问题】传入 grade 和 textbook_id,用于智能补充时限制范围
  1266. $additionalQuestions = $this->getQuestionsFromBank(
  1267. $kpCodes,
  1268. $skills,
  1269. $studentId,
  1270. $questionTypeRatio,
  1271. $poolLimit,
  1272. [],
  1273. [],
  1274. $questionCategory,
  1275. $textbookCatalogNodeIds,
  1276. $grade ? (int) $grade : null, // 年级
  1277. $textbookId, // 教材ID(避免超纲)
  1278. $difficultyCategory // 难度类别
  1279. );
  1280. $allQuestions = array_merge($priorityQuestions, $additionalQuestions);
  1281. Log::info('getQuestionsFromBank 调用完成', [
  1282. 'questions_count' => count($allQuestions),
  1283. 'is_array' => is_array($allQuestions),
  1284. 'first_question_id' => !empty($allQuestions) ? ($allQuestions[0]['id'] ?? 'N/A') : 'N/A',
  1285. '耗时' => round((microtime(true) - $startTime) * 1000, 2) . 'ms',
  1286. ]);
  1287. Log::info('getQuestionsFromBank 返回', [
  1288. 'questions_count' => count($allQuestions),
  1289. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1290. ]);
  1291. } catch (\Exception $e) {
  1292. Log::error('getQuestionsFromBank 调用失败', [
  1293. 'error' => $e->getMessage(),
  1294. 'trace' => $e->getTraceAsString()
  1295. ]);
  1296. throw $e;
  1297. }
  1298. } elseif ($strictMistakeBook) {
  1299. // 错题本类型:不补充题目,只使用错题
  1300. Log::info('错题本类型:不补充题目,只使用错题', [
  1301. 'assemble_type' => $assembleType,
  1302. 'mistake_questions_count' => count($priorityQuestions),
  1303. 'total_questions_requested' => $totalQuestions
  1304. ]);
  1305. }
  1306. if (empty($allQuestions)) {
  1307. // 如果指定了知识点但题库为空,给出明确提示
  1308. if (!empty($kpCodes)) {
  1309. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1310. } else {
  1311. // 没有选择知识点时,从所有题目中选择
  1312. // 如果仍然没有题目,说明题库为空,提示补充题库
  1313. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1314. }
  1315. Log::warning('智能出卷失败 - 未找到题目', [
  1316. 'student_id' => $studentId,
  1317. 'selected_kp_codes' => $kpCodes,
  1318. 'kp_codes_count' => count($kpCodes),
  1319. 'message' => $message,
  1320. 'hint' => '如果选择了知识点但题库为空,请检查知识点代码是否正确,或尝试取消知识点选择'
  1321. ]);
  1322. return [
  1323. 'success' => false,
  1324. 'message' => $message,
  1325. 'questions' => []
  1326. ];
  1327. }
  1328. // 3. 根据掌握度对题目进行筛选和排序
  1329. // 错题本类型:使用所有错题,但不超过最大值限制
  1330. $targetQuestionCount = $strictMistakeBook ? min(count($allQuestions), $maxQuestions) : $totalQuestions;
  1331. Log::info('开始调用 selectQuestionsByMastery', [
  1332. 'input_count' => count($allQuestions),
  1333. 'target_count' => $targetQuestionCount,
  1334. 'is_mistake_book' => $isMistakeBook,
  1335. 'strict_mistake_book' => $strictMistakeBook,
  1336. 'assemble_type' => $assembleType,
  1337. 'total_questions_param' => $totalQuestions
  1338. ]);
  1339. $startTime = microtime(true);
  1340. $selectedQuestions = $this->selectQuestionsByMastery(
  1341. $allQuestions,
  1342. $studentId,
  1343. $targetQuestionCount,
  1344. $questionTypeRatio,
  1345. $difficultyLevels,
  1346. $weaknessFilter,
  1347. $assembleType // 新增assembleType参数
  1348. );
  1349. $selectTime = (microtime(true) - $startTime) * 1000;
  1350. Log::info('题目筛选结果', [
  1351. 'input_count' => count($allQuestions),
  1352. 'selected_count' => count($selectedQuestions),
  1353. 'target_count' => $targetQuestionCount,
  1354. 'is_mistake_book' => $isMistakeBook,
  1355. 'select_time_ms' => round($selectTime, 2)
  1356. ]);
  1357. if (empty($selectedQuestions)) {
  1358. return [
  1359. 'success' => false,
  1360. 'message' => '题目筛选失败',
  1361. 'questions' => []
  1362. ];
  1363. }
  1364. // 【恢复】简化难度分布检查
  1365. $difficultyCategory = $params['difficulty_category'] ?? 1;
  1366. $enableDistribution = $params['enable_difficulty_distribution'] ?? false;
  1367. $isExcludedType = false; // 统一允许应用难度分布(错题本类型也允许)
  1368. // 【重要】添加详细的difficulty_category追踪日志
  1369. Log::info('LearningAnalyticsService: 难度分布检查开始', [
  1370. 'input_difficulty_category' => $difficultyCategory,
  1371. 'assemble_type' => $assembleType,
  1372. 'enable_distribution' => $enableDistribution,
  1373. 'is_excluded_type' => $isExcludedType,
  1374. 'selected_questions_before' => count($selectedQuestions),
  1375. 'params_keys' => array_keys($params)
  1376. ]);
  1377. if ($enableDistribution && !$isExcludedType) {
  1378. Log::info('LearningAnalyticsService: 应用难度系数分布', [
  1379. 'difficulty_category_before' => $difficultyCategory,
  1380. 'assemble_type' => $assembleType,
  1381. 'before_count' => count($selectedQuestions)
  1382. ]);
  1383. try {
  1384. // 使用 ExamTypeStrategy 的独立方法应用难度分布
  1385. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1386. $examStrategy = new ExamTypeStrategy($questionExpansionService);
  1387. $distributionCandidates = $this->buildDistributionCandidates(
  1388. $allQuestions,
  1389. $selectedQuestions,
  1390. (int) $difficultyCategory
  1391. );
  1392. $selectedQuestions = $examStrategy->applyDifficultyDistributionToQuestions(
  1393. $distributionCandidates,
  1394. $totalQuestions,
  1395. $difficultyCategory,
  1396. $params
  1397. );
  1398. Log::info('LearningAnalyticsService: 难度分布应用完成', [
  1399. 'difficulty_category_after' => $difficultyCategory,
  1400. 'before_count' => count($distributionCandidates),
  1401. 'after_count' => count($selectedQuestions),
  1402. 'success' => count($selectedQuestions) >= $totalQuestions
  1403. ]);
  1404. } catch (\Exception $e) {
  1405. Log::warning('LearningAnalyticsService: 难度分布应用失败,继续使用原结果', [
  1406. 'error' => $e->getMessage(),
  1407. 'difficulty_category_when_error' => $difficultyCategory
  1408. ]);
  1409. }
  1410. }
  1411. return [
  1412. 'success' => true,
  1413. 'message' => '智能出卷成功',
  1414. 'questions' => $selectedQuestions,
  1415. 'stats' => [
  1416. 'total_selected' => count($selectedQuestions),
  1417. 'source_questions' => count($allQuestions),
  1418. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1419. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1420. })) : 0,
  1421. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1422. 'difficulty_category' => $difficultyCategory,
  1423. 'final_distribution' => $this->buildDifficultyDistributionStats($selectedQuestions, (int) $difficultyCategory),
  1424. 'final_distribution_shortage' => $this->buildDifficultyDistributionShortage(
  1425. $selectedQuestions,
  1426. (int) $difficultyCategory,
  1427. (int) $totalQuestions
  1428. ),
  1429. // 【新增】章节知识点数量统计(教材组卷时)
  1430. 'chapter_knowledge_point_stats' => $params['chapter_knowledge_point_stats'] ?? null,
  1431. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? null
  1432. ]
  1433. ];
  1434. } catch (\Exception $e) {
  1435. Log::error('Generate Intelligent Exam Error', [
  1436. 'error' => $e->getMessage(),
  1437. 'trace' => $e->getTraceAsString()
  1438. ]);
  1439. return [
  1440. 'success' => false,
  1441. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1442. 'questions' => []
  1443. ];
  1444. }
  1445. }
  1446. /**
  1447. * 从题库获取题目
  1448. *
  1449. * @param array $kpCodes 知识点代码列表
  1450. * @param array $skills 技能标签列表
  1451. * @param string|null $studentId 学生ID
  1452. * @param array $questionTypeRatio 题型比例
  1453. * @param int $totalNeeded 需要的题目数量
  1454. * @param array $priorityQuestionIds 优先获取的题目ID(错题)
  1455. * @param array $excludeQuestionIds 排除的题目ID
  1456. * @param int|null $questionCategory 题目分类
  1457. * @param array|null $textbookCatalogNodeIds 教材章节节点ID
  1458. * @param int|null $grade 年级(用于智能补充时限制范围)
  1459. * @param int|null $textbookId 教材ID(用于智能补充时限制范围,避免超纲)
  1460. * @param int $difficultyCategory 难度类别(用于智能补充)
  1461. * @return array 题目列表
  1462. */
  1463. private function getQuestionsFromBank(array $kpCodes, array $skills, ?string $studentId, array $questionTypeRatio = [], int $totalNeeded = 100, array $priorityQuestionIds = [], array $excludeQuestionIds = [], ?int $questionCategory = null, ?array $textbookCatalogNodeIds = null, ?int $grade = null, ?int $textbookId = null, int $difficultyCategory = 1): array
  1464. {
  1465. $startTime = microtime(true);
  1466. try {
  1467. // 错题回顾:优先获取指定的学生错题
  1468. if (!empty($priorityQuestionIds)) {
  1469. Log::info('getQuestionsFromBank: 优先获取学生错题', [
  1470. 'priority_count' => count($priorityQuestionIds),
  1471. 'priority_ids' => $priorityQuestionIds
  1472. ]);
  1473. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1474. if (!empty($priorityQuestions)) {
  1475. Log::info('getQuestionsFromBank: 优先错题获取成功', [
  1476. 'count' => count($priorityQuestions)
  1477. ]);
  1478. return $priorityQuestions;
  1479. } else {
  1480. Log::warning('getQuestionsFromBank: 优先错题获取失败,返回空数组让上层处理');
  1481. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1482. return [];
  1483. }
  1484. }
  1485. // 从本地数据库查询题目
  1486. Log::info('getQuestionsFromBank: 从本地数据库查询题目', [
  1487. 'kp_codes' => $kpCodes,
  1488. 'skills' => $skills,
  1489. 'total_needed' => $totalNeeded,
  1490. 'question_type_ratio' => $questionTypeRatio,
  1491. 'note' => $totalNeeded > 0 ? '难度筛选由 QuestionLocalService 处理' : '不限制题库池大小,难度筛选由 QuestionLocalService 处理'
  1492. ]);
  1493. $query = \App\Models\Question::query();
  1494. // 【新增】只获取审核通过的题目(audit_status = 0 表示合格)
  1495. $query->where('audit_status', 0);
  1496. // 按知识点筛选
  1497. if (!empty($kpCodes)) {
  1498. $query->whereIn('kp_code', $kpCodes);
  1499. Log::info('应用知识点筛选', ['kp_codes' => $kpCodes]);
  1500. }
  1501. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1502. if (!empty($skills)) {
  1503. $query->where(function ($q) use ($skills) {
  1504. foreach ($skills as $skill) {
  1505. $q->orWhere('tags', 'like', "%{$skill}%");
  1506. }
  1507. });
  1508. Log::info('应用技能筛选', ['skills' => $skills]);
  1509. }
  1510. // 排除学生已做过的题目
  1511. if (!empty($excludeQuestionIds)) {
  1512. $query->whereNotIn('id', $excludeQuestionIds);
  1513. Log::info('应用排除筛选', ['exclude_count' => count($excludeQuestionIds)]);
  1514. }
  1515. // 按题目分类筛选(如果指定了 question_category)
  1516. if ($questionCategory !== null) {
  1517. $query->where('question_category', $questionCategory);
  1518. Log::info('应用题目分类筛选', ['question_category' => $questionCategory]);
  1519. }
  1520. // 筛选有解题思路的题目
  1521. $query->whereNotNull('solution')
  1522. ->where('solution', '!=', '')
  1523. ->where('solution', '!=', '[]');
  1524. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1525. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1526. // 【重要】移除数量限制,获取所有符合条件的题目
  1527. // 不使用limit()限制查询结果,让后续处理逻辑决定最终数量
  1528. $query->inRandomOrder();
  1529. $questions = $query->get();
  1530. Log::info('getQuestionsFromBank: 查询完成', [
  1531. 'raw_count' => $questions->count(),
  1532. 'total_needed' => $totalNeeded,
  1533. 'note' => '移除limit限制,获取所有符合条件的题目',
  1534. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1535. ]);
  1536. // 【重要】添加更详细的日志来追踪题目筛选过程
  1537. Log::info('getQuestionsFromBank: 题目筛选过程详情', [
  1538. 'database_query_count' => $questions->count(),
  1539. 'kp_codes_filter' => $kpCodes,
  1540. 'skills_filter' => $skills,
  1541. 'exclude_count' => count($excludeQuestionIds),
  1542. 'question_category' => $questionCategory,
  1543. 'textbook_catalog_node_ids_filter' => $textbookCatalogNodeIds,
  1544. 'note' => '将返回所有符合条件的题目,不限制数量'
  1545. ]);
  1546. // 转换为标准格式
  1547. $formattedQuestions = $questions->map(function ($q) {
  1548. return [
  1549. 'id' => $q->id,
  1550. 'question_code' => $q->question_code,
  1551. 'kp_code' => $q->kp_code,
  1552. 'question_type' => $q->question_type,
  1553. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1554. 'stem' => $q->stem,
  1555. 'solution' => $q->solution,
  1556. 'metadata' => [
  1557. 'has_solution' => true,
  1558. 'is_choice' => $q->question_type === 'choice',
  1559. 'is_fill' => $q->question_type === 'fill',
  1560. 'is_answer' => $q->question_type === 'answer',
  1561. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1562. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1563. ]
  1564. ];
  1565. })->toArray();
  1566. // 【重要】返回所有符合条件的题目,不限制数量
  1567. // 让上层调用者根据需要选择题目数量
  1568. $selectedQuestions = $formattedQuestions;
  1569. // 【修复】重新启用智能补充功能,增加 textbook_id 限制避免超纲
  1570. if ($totalNeeded > 0 && count($selectedQuestions) < $totalNeeded && $grade !== null) {
  1571. $deficit = $totalNeeded - count($selectedQuestions);
  1572. Log::warning('getQuestionsFromBank: 指定知识点题目不足,尝试智能补充', [
  1573. 'deficit' => $deficit,
  1574. 'available_count' => count($selectedQuestions),
  1575. 'grade' => $grade,
  1576. 'textbook_id' => $textbookId,
  1577. 'strategy' => $textbookId ? '从指定教材的其他知识点补充(避免超纲)' : '从同年级其他知识点补充'
  1578. ]);
  1579. // 【修复超纲问题】补充策略:从同年级同教材的其他知识点补充
  1580. // 传入 textbook_id 参数,避免七年级上册学生拿到下册题目
  1581. $supplementaryQuestions = $this->getSupplementaryQuestionsForGrade(
  1582. $grade,
  1583. array_column($selectedQuestions, 'kp_code'),
  1584. $deficit,
  1585. $difficultyCategory,
  1586. $textbookId // 【关键】传入教材ID,限制补充范围
  1587. );
  1588. if (!empty($supplementaryQuestions)) {
  1589. $selectedQuestions = array_merge($selectedQuestions, $supplementaryQuestions);
  1590. Log::info('getQuestionsFromBank: 智能补充完成', [
  1591. 'supplementary_count' => count($supplementaryQuestions),
  1592. 'total_after_supplement' => count($selectedQuestions),
  1593. 'textbook_id' => $textbookId
  1594. ]);
  1595. } else {
  1596. Log::warning('getQuestionsFromBank: 智能补充失败,未找到合适的题目', [
  1597. 'grade' => $grade,
  1598. 'textbook_id' => $textbookId,
  1599. 'note' => $textbookId ? '可能是该教材知识点题目不足' : '该年级题目不足'
  1600. ]);
  1601. }
  1602. }
  1603. Log::info('getQuestionsFromBank 完成', [
  1604. 'final_count' => count($selectedQuestions),
  1605. 'raw_database_count' => $questions->count(),
  1606. 'total_needed' => $totalNeeded,
  1607. 'success' => $totalNeeded > 0 ? count($selectedQuestions) >= $totalNeeded : true,
  1608. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1609. ]);
  1610. return $selectedQuestions;
  1611. } catch (\Exception $e) {
  1612. Log::error('getQuestionsFromBank 查询失败', [
  1613. 'error' => $e->getMessage(),
  1614. 'trace' => $e->getTraceAsString()
  1615. ]);
  1616. throw $e;
  1617. }
  1618. }
  1619. /**
  1620. * 获取指定ID的题目详情
  1621. */
  1622. private function getLocalQuestionsByIds(array $questionIds): array
  1623. {
  1624. try {
  1625. // 通过QuestionBankService获取题目详情
  1626. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1627. // 批量获取题目详情
  1628. $response = $questionBankService->getQuestionsByIds($questionIds);
  1629. if (empty($response['data'])) {
  1630. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1631. 'requested_ids' => $questionIds
  1632. ]);
  1633. return [];
  1634. }
  1635. $questions = $response['data'];
  1636. // 转换为标准格式
  1637. $result = array_map(function ($q) {
  1638. $difficulty = $q['difficulty'] ?? 0.5;
  1639. return [
  1640. 'id' => $q['id'],
  1641. 'question_code' => $q['question_code'] ?? '',
  1642. 'kp_code' => $q['kp_code'] ?? '',
  1643. 'question_type' => $q['question_type'] ?? 'choice',
  1644. 'difficulty' => (float) $difficulty,
  1645. 'stem' => $q['stem'] ?? '',
  1646. 'solution' => $q['solution'] ?? '',
  1647. 'answer' => $q['answer'] ?? '',
  1648. 'metadata' => [
  1649. 'has_solution' => !empty($q['solution']),
  1650. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1651. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1652. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1653. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1654. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1655. ]
  1656. ];
  1657. }, $questions);
  1658. Log::info('getLocalQuestionsByIds 获取成功', [
  1659. 'requested_count' => count($questionIds),
  1660. 'found_count' => count($result),
  1661. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1662. 'question_ids' => array_slice($questionIds, 0, 20),
  1663. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1664. ]);
  1665. return $result;
  1666. } catch (\Exception $e) {
  1667. Log::error('getLocalQuestionsByIds 获取失败', [
  1668. 'question_ids' => $questionIds,
  1669. 'error' => $e->getMessage(),
  1670. 'trace' => $e->getTraceAsString()
  1671. ]);
  1672. return [];
  1673. }
  1674. }
  1675. /**
  1676. * 获取卷子的所有题目ID(不区分对错)
  1677. */
  1678. private function getPaperAllQuestions(array $paperIds): array
  1679. {
  1680. try {
  1681. // 查询 paper_questions 表获取所有题目ID
  1682. $questionIds = DB::table('paper_questions')
  1683. ->whereIn('paper_id', $paperIds)
  1684. ->pluck('question_bank_id')
  1685. ->unique()
  1686. ->filter()
  1687. ->values()
  1688. ->toArray();
  1689. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1690. 'paper_ids' => $paperIds,
  1691. 'question_count' => count($questionIds)
  1692. ]);
  1693. return $questionIds;
  1694. } catch (\Exception $e) {
  1695. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1696. 'paper_ids' => $paperIds,
  1697. 'error' => $e->getMessage()
  1698. ]);
  1699. return [];
  1700. }
  1701. }
  1702. /**
  1703. * 获取难度标签
  1704. */
  1705. private function getDifficultyLabel(?float $difficulty): string
  1706. {
  1707. if ($difficulty === null) {
  1708. return '未知';
  1709. }
  1710. return match (true) {
  1711. $difficulty < 0.4 => '基础',
  1712. $difficulty < 0.7 => '中等',
  1713. default => '拔高'
  1714. };
  1715. }
  1716. /**
  1717. * 获取题型标签
  1718. */
  1719. private function getQuestionTypeLabel(string $questionType): string
  1720. {
  1721. return match ($questionType) {
  1722. 'choice' => '选择题',
  1723. 'fill' => '填空题',
  1724. 'answer' => '解答题',
  1725. default => '未知题型'
  1726. };
  1727. }
  1728. /**
  1729. * 根据题型配比选择题目
  1730. * 注意: 难度配比调整由 QuestionLocalService 处理
  1731. */
  1732. private function selectQuestionsByRatio(
  1733. array $questions,
  1734. int $totalNeeded,
  1735. array $questionTypeRatio = []
  1736. ): array {
  1737. if (empty($questions)) {
  1738. return [];
  1739. }
  1740. // 如果没有配比要求,直接返回
  1741. if (empty($questionTypeRatio)) {
  1742. return array_slice($questions, 0, $totalNeeded);
  1743. }
  1744. $selected = [];
  1745. $usedIndices = [];
  1746. // 按题型配比选择
  1747. if (!empty($questionTypeRatio)) {
  1748. foreach ($questionTypeRatio as $type => $ratio) {
  1749. $count = (int) round(($ratio / 100) * $totalNeeded);
  1750. if ($count <= 0) continue;
  1751. $typeQuestions = [];
  1752. foreach ($questions as $idx => $q) {
  1753. if (in_array($idx, $usedIndices)) continue;
  1754. $qType = $q['question_type'] ?? '';
  1755. $label = $this->getQuestionTypeLabel($qType);
  1756. if ($label === $type) {
  1757. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1758. }
  1759. }
  1760. // 随机选择
  1761. shuffle($typeQuestions);
  1762. $selectedCount = min($count, count($typeQuestions));
  1763. for ($i = 0; $i < $selectedCount; $i++) {
  1764. $selected[] = $typeQuestions[$i]['question'];
  1765. $usedIndices[] = $typeQuestions[$i]['idx'];
  1766. }
  1767. }
  1768. }
  1769. // 如果还有空缺,补充剩余题目
  1770. // 注意: 难度配比调整由 QuestionLocalService 处理
  1771. if (count($selected) < $totalNeeded) {
  1772. foreach ($questions as $idx => $q) {
  1773. if (count($selected) >= $totalNeeded) break;
  1774. if (!in_array($idx, $usedIndices)) {
  1775. $selected[] = $q;
  1776. $usedIndices[] = $idx;
  1777. }
  1778. }
  1779. }
  1780. return array_slice($selected, 0, $totalNeeded);
  1781. }
  1782. /**
  1783. * 根据学生掌握度筛选题目
  1784. */
  1785. private function selectQuestionsByMastery(
  1786. array $questions,
  1787. ?string $studentId,
  1788. int $totalQuestions,
  1789. array $questionTypeRatio,
  1790. array $difficultyLevels,
  1791. array $weaknessFilter,
  1792. int $assembleType // 新增assembleType参数
  1793. ): array {
  1794. Log::info('selectQuestionsByMastery 开始', [
  1795. 'question_count' => count($questions),
  1796. 'student_id' => $studentId,
  1797. 'total_questions' => $totalQuestions,
  1798. 'unique_kp_count' => count(array_unique(array_column($questions, 'kp_code'))),
  1799. 'assemble_type' => $assembleType,
  1800. 'note' => '追踪输入题目数量和知识点多样性'
  1801. ]);
  1802. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1803. // 如果题目数量超过目标,则截取到目标数量
  1804. // 如果题目数量不足,则使用所有题目,并记录警告
  1805. if (count($questions) > $totalQuestions) {
  1806. Log::info('题目数量超过目标,进行截取', [
  1807. 'question_count' => count($questions),
  1808. 'total_questions' => $totalQuestions,
  1809. 'note' => '将按权重选择最合适的题目'
  1810. ]);
  1811. } else {
  1812. Log::warning('题目数量不足,将使用所有可用题目', [
  1813. 'available_count' => count($questions),
  1814. 'requested_count' => $totalQuestions,
  1815. 'note' => '可能需要补充题库或放宽筛选条件'
  1816. ]);
  1817. }
  1818. // 【移除】删除多余的难度筛选逻辑
  1819. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1820. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1821. Log::info('跳过多余的难度筛选,使用题目原始难度分布', [
  1822. 'question_count' => count($questions),
  1823. 'note' => '由QuestionLocalService处理难度分布'
  1824. ]);
  1825. // 1. 按知识点分组
  1826. Log::info('开始按知识点分组', [
  1827. 'question_count' => count($questions)
  1828. ]);
  1829. $groupStartTime = microtime(true);
  1830. $questionsByKp = [];
  1831. foreach ($questions as $question) {
  1832. $kpCode = $question['kp_code'] ?? '';
  1833. if (!isset($questionsByKp[$kpCode])) {
  1834. $questionsByKp[$kpCode] = [];
  1835. }
  1836. $questionsByKp[$kpCode][] = $question;
  1837. }
  1838. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1839. Log::info('按知识点分组完成', [
  1840. 'kp_count' => count($questionsByKp),
  1841. 'group_time_ms' => round($groupTime, 2)
  1842. ]);
  1843. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1844. $kpWeights = [];
  1845. $kpCodes = array_keys($questionsByKp);
  1846. Log::info('开始计算知识点权重(用于题型内排序)', [
  1847. 'kp_count' => count($kpCodes),
  1848. 'student_id' => $studentId
  1849. ]);
  1850. $startTime = microtime(true);
  1851. $allMastery = [];
  1852. if ($studentId) {
  1853. // 批量获取所有知识点的掌握度(一次查询)
  1854. $masteryStart = microtime(true);
  1855. try {
  1856. $masteryRecords = DB::table('student_mastery')
  1857. ->where('student_id', $studentId)
  1858. ->whereIn('kp', $kpCodes)
  1859. ->pluck('mastery', 'kp')
  1860. ->all();
  1861. Log::debug('批量获取掌握度', [
  1862. 'student_id' => $studentId,
  1863. 'kp_count' => count($kpCodes),
  1864. 'found_count' => count($masteryRecords),
  1865. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1866. ]);
  1867. $allMastery = $masteryRecords;
  1868. } catch (\Exception $e) {
  1869. Log::warning('批量获取掌握度失败,将使用默认值', [
  1870. 'student_id' => $studentId,
  1871. 'error' => $e->getMessage()
  1872. ]);
  1873. }
  1874. }
  1875. foreach ($kpCodes as $kpCode) {
  1876. if ($studentId) {
  1877. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1878. // 薄弱点权重更高
  1879. if (in_array($kpCode, $weaknessFilter)) {
  1880. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1881. } else {
  1882. // 掌握度越低,权重越高
  1883. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1884. }
  1885. Log::debug('计算知识点权重', [
  1886. 'kp_code' => $kpCode,
  1887. 'mastery' => $mastery,
  1888. 'weight' => $kpWeights[$kpCode]
  1889. ]);
  1890. } else {
  1891. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1892. }
  1893. }
  1894. $totalWeightTime = (microtime(true) - $startTime) * 1000;
  1895. Log::info('知识点权重计算完成', [
  1896. 'total_kp_count' => count($kpCodes),
  1897. 'total_weight_time_ms' => round($totalWeightTime, 2),
  1898. 'avg_time_per_kp_ms' => count($kpCodes) > 0 ? round($totalWeightTime / count($kpCodes), 2) : 0
  1899. ]);
  1900. // 3. 按题型分配题目数量(权重用于题型内排序)
  1901. $selectedQuestions = [];
  1902. // 将所有题目合并
  1903. $weightedQuestions = [];
  1904. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1905. foreach ($kpQuestions as $q) {
  1906. $q['kp_code'] = $kpCode;
  1907. $weightedQuestions[] = $q;
  1908. }
  1909. }
  1910. // ========== 知识点优先选择机制 ==========
  1911. // 摸底测试的核心目标是最大化知识点覆盖
  1912. // 题型只是约束条件(每种至少1题)
  1913. // 首先按题型分组
  1914. $questionsByType = [
  1915. 'choice' => [],
  1916. 'fill' => [],
  1917. 'answer' => [],
  1918. ];
  1919. foreach ($weightedQuestions as $q) {
  1920. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1921. if ($qid && isset($questionTypeCache[$qid])) {
  1922. $type = $questionTypeCache[$qid];
  1923. } else {
  1924. $type = $this->determineQuestionType($q);
  1925. if ($qid) {
  1926. $questionTypeCache[$qid] = $type;
  1927. }
  1928. }
  1929. if (!isset($questionsByType[$type])) {
  1930. $type = 'answer'; // 默认归类为answer
  1931. }
  1932. $questionsByType[$type][] = $q;
  1933. }
  1934. // ========== 步骤1:按题型分配题目 ==========
  1935. $selectedQuestions = [];
  1936. // 【区分】根据assembleType决定是否使用知识点优先机制
  1937. $useKnowledgePointPriority = ($assembleType === 0); // 摸底测试需要知识点优先
  1938. $kpSelected = []; // 已选知识点记录
  1939. Log::info('selectQuestionsByMastery: 知识点优先策略', [
  1940. 'assemble_type' => $assembleType,
  1941. 'use_knowledge_point_priority' => $useKnowledgePointPriority,
  1942. 'note' => $useKnowledgePointPriority ? '摸底测试:需要均衡分配知识点' : '知识点组卷:允许同一知识点选多题'
  1943. ]);
  1944. // 确保每种题型至少选1题
  1945. foreach (['choice', 'fill', 'answer'] as $type) {
  1946. if (empty($questionsByType[$type])) {
  1947. Log::warning('题型分配:题型无题目', ['type' => $type]);
  1948. continue;
  1949. }
  1950. // 按权重排序该题型的题目
  1951. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  1952. $kpA = $a['kp_code'] ?? '';
  1953. $kpB = $b['kp_code'] ?? '';
  1954. $weightA = $kpWeights[$kpA] ?? 1.0;
  1955. $weightB = $kpWeights[$kpB] ?? 1.0;
  1956. return $weightB <=> $weightA;
  1957. });
  1958. // 【修复】摸底测试题型基础分配:记录每个题型的知识点分布
  1959. $typeKpDistribution = [];
  1960. foreach ($questionsByType[$type] as $q) {
  1961. $kpCode = $q['kp_code'] ?? '';
  1962. if (!isset($typeKpDistribution[$kpCode])) {
  1963. $typeKpDistribution[$kpCode] = 0;
  1964. }
  1965. $typeKpDistribution[$kpCode]++;
  1966. }
  1967. Log::info('摸底测试题型基础分配开始', [
  1968. 'type' => $type,
  1969. 'total_questions_in_type' => count($questionsByType[$type]),
  1970. 'kp_distribution_in_type' => $typeKpDistribution,
  1971. 'available_kp_count' => count($typeKpDistribution)
  1972. ]);
  1973. // 根据策略选择题目
  1974. if ($useKnowledgePointPriority) {
  1975. // 摸底测试:选择第一个未选过知识点的题目
  1976. $selectedInThisType = 0;
  1977. foreach ($questionsByType[$type] as $q) {
  1978. $kpCode = $q['kp_code'] ?? '';
  1979. if (!isset($kpSelected[$kpCode])) {
  1980. $selectedQuestions[] = $q;
  1981. $kpSelected[$kpCode] = true;
  1982. $selectedInThisType++;
  1983. Log::debug('题型基础分配(知识点优先)', [
  1984. 'type' => $type,
  1985. 'kp' => $kpCode,
  1986. 'question_id' => $q['id'] ?? 'unknown',
  1987. 'selected_in_type' => $selectedInThisType
  1988. ]);
  1989. break; // 只选1题
  1990. }
  1991. }
  1992. Log::info('摸底测试题型基础分配完成', [
  1993. 'type' => $type,
  1994. 'selected_count' => $selectedInThisType,
  1995. 'note' => $selectedInThisType > 0 ? '成功选择' : '无可用知识点'
  1996. ]);
  1997. } else {
  1998. // 【修复】知识点组卷:随机选择该题型的一道题,避免固定选择第一个导致知识点分布不均
  1999. $randomIndex = array_rand($questionsByType[$type]);
  2000. $selectedQuestions[] = $questionsByType[$type][$randomIndex];
  2001. Log::debug('题型基础分配(随机选择)', [
  2002. 'type' => $type,
  2003. 'kp' => $questionsByType[$type][$randomIndex]['kp_code'] ?? 'unknown',
  2004. 'random_index' => $randomIndex,
  2005. 'total_in_type' => count($questionsByType[$type])
  2006. ]);
  2007. }
  2008. }
  2009. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  2010. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  2011. // 【重要】添加排序前的知识点分布日志
  2012. $preSortKpDistribution = [];
  2013. foreach ($allQuestions as $q) {
  2014. $kpCode = $q['kp_code'] ?? '';
  2015. if (!isset($preSortKpDistribution[$kpCode])) {
  2016. $preSortKpDistribution[$kpCode] = 0;
  2017. }
  2018. $preSortKpDistribution[$kpCode]++;
  2019. }
  2020. Log::info('selectQuestionsByMastery: 排序前知识点分布', [
  2021. 'total_questions' => count($allQuestions),
  2022. 'kp_distribution' => $preSortKpDistribution,
  2023. 'note' => '用于对比排序后的分布变化'
  2024. ]);
  2025. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  2026. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  2027. $kpA = $a['kp_code'] ?? '';
  2028. $kpB = $b['kp_code'] ?? '';
  2029. $weightA = $kpWeights[$kpA] ?? 1.0;
  2030. $weightB = $kpWeights[$kpB] ?? 1.0;
  2031. // 主要按权重排序
  2032. if ($weightA != $weightB) {
  2033. return $weightB <=> $weightA;
  2034. }
  2035. // 权重相同时,添加随机排序而不是按ID排序
  2036. // 使用随机因子确保相同权重的知识点有公平的选中机会
  2037. return mt_rand(-1, 1);
  2038. });
  2039. // 【重要】添加排序后的知识点分布日志
  2040. $postSortKpDistribution = [];
  2041. $postSortFirst50 = []; // 记录前50题的知识点分布
  2042. foreach ($allQuestions as $idx => $q) {
  2043. $kpCode = $q['kp_code'] ?? '';
  2044. if (!isset($postSortKpDistribution[$kpCode])) {
  2045. $postSortKpDistribution[$kpCode] = 0;
  2046. }
  2047. $postSortKpDistribution[$kpCode]++;
  2048. // 记录前50题的知识点
  2049. if ($idx < 50) {
  2050. $postSortFirst50[] = $kpCode;
  2051. }
  2052. }
  2053. Log::info('selectQuestionsByMastery: 排序后知识点分布', [
  2054. 'total_questions' => count($allQuestions),
  2055. 'kp_distribution' => $postSortKpDistribution,
  2056. 'first_50_kp_codes' => $postSortFirst50,
  2057. 'note' => '观察排序是否均衡分布A07和A08'
  2058. ]);
  2059. // 【修复】摸底测试继续选择题目:记录详细的选题过程
  2060. Log::info('摸底测试继续选择题目开始', [
  2061. 'selected_count_after_basic' => count($selectedQuestions),
  2062. 'total_questions' => $totalQuestions,
  2063. 'selected_kp_codes' => array_keys($kpSelected),
  2064. 'available_kp_count' => count($preSortKpDistribution),
  2065. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制'
  2066. ]);
  2067. if ($useKnowledgePointPriority) {
  2068. // 摸底测试:优先选择未选过知识点的题目
  2069. $initialSelectedCount = count($selectedQuestions);
  2070. $prioritySelectedCount = 0;
  2071. foreach ($allQuestions as $q) {
  2072. if (count($selectedQuestions) >= $totalQuestions) break;
  2073. $kpCode = $q['kp_code'] ?? '';
  2074. if (!isset($kpSelected[$kpCode])) {
  2075. $selectedQuestions[] = $q;
  2076. $kpSelected[$kpCode] = true;
  2077. $prioritySelectedCount++;
  2078. Log::debug('继续选择题目(知识点优先)', [
  2079. 'kp' => $kpCode,
  2080. 'id' => $q['id'] ?? 'unknown',
  2081. 'priority_selected_count' => $prioritySelectedCount,
  2082. 'total_selected' => count($selectedQuestions)
  2083. ]);
  2084. }
  2085. }
  2086. Log::info('摸底测试优先阶段完成', [
  2087. 'priority_selected_count' => $prioritySelectedCount,
  2088. 'total_selected' => count($selectedQuestions),
  2089. 'unique_kp_count' => count($kpSelected),
  2090. 'note' => '优先选择未选过知识点的题目'
  2091. ]);
  2092. // 【修复】降级策略:如果仍未达到目标数量,允许重复选择知识点
  2093. if (count($selectedQuestions) < $totalQuestions) {
  2094. Log::warning('selectQuestionsByMastery: 知识点优先策略无法满足数量要求,启用降级策略', [
  2095. 'requested_count' => $totalQuestions,
  2096. 'selected_count' => count($selectedQuestions),
  2097. 'priority_selected_count' => $prioritySelectedCount,
  2098. 'unique_kp_count' => count($kpSelected),
  2099. 'available_kp_count' => count($preSortKpDistribution),
  2100. 'note' => '将允许重复选择知识点以达到目标数量'
  2101. ]);
  2102. $fallbackSelectedCount = 0;
  2103. $selectedIds = array_column($selectedQuestions, 'id');
  2104. foreach ($allQuestions as $q) {
  2105. if (count($selectedQuestions) >= $totalQuestions) break;
  2106. $qid = $q['id'] ?? null;
  2107. if ($qid && !in_array($qid, $selectedIds)) {
  2108. $selectedQuestions[] = $q;
  2109. $selectedIds[] = $qid;
  2110. $fallbackSelectedCount++;
  2111. Log::debug('降级选择题目(允许知识点重复)', [
  2112. 'kp' => $q['kp_code'] ?? 'unknown',
  2113. 'id' => $qid,
  2114. 'fallback_selected_count' => $fallbackSelectedCount,
  2115. 'current_count' => count($selectedQuestions)
  2116. ]);
  2117. }
  2118. }
  2119. Log::info('摸底测试降级阶段完成', [
  2120. 'fallback_selected_count' => $fallbackSelectedCount,
  2121. 'total_selected' => count($selectedQuestions),
  2122. 'note' => '允许重复选择知识点补充数量'
  2123. ]);
  2124. }
  2125. } else {
  2126. // 知识点组卷:选择未选过的题目(不要求知识点不重复)
  2127. $selectedIds = array_column($selectedQuestions, 'id');
  2128. foreach ($allQuestions as $q) {
  2129. if (count($selectedQuestions) >= $totalQuestions) break;
  2130. $qid = $q['id'] ?? null;
  2131. if ($qid && !in_array($qid, $selectedIds)) {
  2132. $selectedQuestions[] = $q;
  2133. $selectedIds[] = $qid;
  2134. Log::debug('继续选择题目(无知识点限制)', ['kp' => $q['kp_code'] ?? 'unknown', 'id' => $qid]);
  2135. }
  2136. }
  2137. }
  2138. // 【移除】删除步骤3的多余逻辑
  2139. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2140. Log::info('selectQuestionsByMastery: 题目选择完成', [
  2141. 'total_questions' => $totalQuestions,
  2142. 'selected_count' => count($selectedQuestions),
  2143. 'success' => count($selectedQuestions) === $totalQuestions,
  2144. 'assemble_type' => $assembleType,
  2145. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制',
  2146. 'type_distribution' => array_count_values(array_map(function($q) {
  2147. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2148. if ($qid && isset($questionTypeCache[$qid])) {
  2149. return $questionTypeCache[$qid];
  2150. }
  2151. return $this->determineQuestionType($q);
  2152. }, $selectedQuestions)),
  2153. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2154. ]);
  2155. // 【重要】最终截取到目标数量(如果超过)
  2156. if (count($selectedQuestions) > $totalQuestions) {
  2157. Log::info('题目数量超过目标,进行最终截取', [
  2158. 'before' => count($selectedQuestions),
  2159. 'after' => $totalQuestions
  2160. ]);
  2161. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2162. }
  2163. // 【重要】添加最终数量验证日志
  2164. Log::info('selectQuestionsByMastery: 最终题目数量验证', [
  2165. 'before_final_check' => count($selectedQuestions),
  2166. 'target_count' => $totalQuestions,
  2167. 'is_array' => is_array($selectedQuestions)
  2168. ]);
  2169. // 【新增】最终知识点分布统计
  2170. $finalKpDistribution = array_count_values(array_column($selectedQuestions, 'kp_code'));
  2171. Log::info('摸底测试最终知识点分布', [
  2172. 'final_total_count' => count($selectedQuestions),
  2173. 'target_count' => $totalQuestions,
  2174. 'final_kp_distribution' => $finalKpDistribution,
  2175. 'unique_kp_count' => count($finalKpDistribution),
  2176. 'success' => count($selectedQuestions) === $totalQuestions,
  2177. 'kp_coverage_rate' => count($finalKpDistribution) / max(count($preSortKpDistribution), 1) * 100
  2178. ]);
  2179. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2180. $finalQuestions = [];
  2181. $seenQuestionIds = [];
  2182. $duplicateCount = 0;
  2183. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2184. foreach ($selectedQuestions as $question) {
  2185. $qbId = $question['question_bank_id'] ?? $question['id'];
  2186. if (!in_array($qbId, $seenQuestionIds)) {
  2187. $seenQuestionIds[] = $qbId;
  2188. $finalQuestions[] = $question;
  2189. // 统计题型分布
  2190. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2191. $type = null;
  2192. if ($qid && isset($questionTypeCache[$qid])) {
  2193. $type = $questionTypeCache[$qid];
  2194. } else {
  2195. $type = $this->determineQuestionType($question);
  2196. if ($qid) {
  2197. $questionTypeCache[$qid] = $type;
  2198. }
  2199. }
  2200. if (isset($typeDistribution[$type])) {
  2201. $typeDistribution[$type]++;
  2202. }
  2203. } else {
  2204. $duplicateCount++;
  2205. Log::warning('发现重复题目(已自动移除)', [
  2206. 'question_id' => $qbId,
  2207. 'duplicate_count' => $duplicateCount
  2208. ]);
  2209. }
  2210. }
  2211. // 【重要】如果去重后数量不足,补充到目标数量
  2212. if (count($finalQuestions) < $totalQuestions) {
  2213. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2214. 'final_count' => count($finalQuestions),
  2215. 'target_count' => $totalQuestions,
  2216. 'need_more' => $totalQuestions - count($finalQuestions)
  2217. ]);
  2218. // 从原始题目中选择未选过的题目补充
  2219. $usedIds = array_column($finalQuestions, 'id');
  2220. $supplementCount = 0;
  2221. foreach ($selectedQuestions as $question) {
  2222. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2223. $qid = $question['id'] ?? null;
  2224. if ($qid && !in_array($qid, $usedIds)) {
  2225. $finalQuestions[] = $question;
  2226. $usedIds[] = $qid;
  2227. $supplementCount++;
  2228. }
  2229. }
  2230. Log::info('selectQuestionsByMastery: 补充完成', [
  2231. 'supplement_added' => $supplementCount,
  2232. 'final_count_after_supplement' => count($finalQuestions)
  2233. ]);
  2234. }
  2235. Log::info('最终排查完成', [
  2236. 'original_count' => count($selectedQuestions),
  2237. 'final_count' => count($finalQuestions),
  2238. 'duplicate_removed' => $duplicateCount,
  2239. 'final_type_distribution' => $typeDistribution,
  2240. 'target_count' => $totalQuestions
  2241. ]);
  2242. // 【重要】确保返回的题目数量正确
  2243. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2244. Log::info('selectQuestionsByMastery: 返回结果', [
  2245. 'return_count' => count($finalQuestions),
  2246. 'target_count' => $totalQuestions,
  2247. 'success' => count($finalQuestions) === $totalQuestions
  2248. ]);
  2249. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2250. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2251. return $finalQuestions;
  2252. }
  2253. /**
  2254. * 获取学生对特定知识点的掌握度
  2255. */
  2256. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2257. {
  2258. try {
  2259. $mastery = DB::table('student_mastery')
  2260. ->where('student_id', $studentId)
  2261. ->where('kp', $kpCode)
  2262. ->value('mastery');
  2263. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2264. } catch (\Exception $e) {
  2265. Log::error('Get Student Kp Mastery Error', [
  2266. 'student_id' => $studentId,
  2267. 'kp_code' => $kpCode,
  2268. 'error' => $e->getMessage()
  2269. ]);
  2270. return 0.5;
  2271. }
  2272. }
  2273. /**
  2274. * 根据题型和难度配比调整题目
  2275. */
  2276. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2277. {
  2278. Log::info('开始题型配比调整', [
  2279. 'input_questions' => count($questions),
  2280. 'target_count' => $targetCount,
  2281. 'type_ratio' => $typeRatio
  2282. ]);
  2283. // 缓存题目类型,避免重复计算
  2284. $questionTypeCache = [];
  2285. // 按题型分桶
  2286. $buckets = [
  2287. 'choice' => [],
  2288. 'fill' => [],
  2289. 'answer' => [],
  2290. ];
  2291. foreach ($questions as $q) {
  2292. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2293. if ($qid && isset($questionTypeCache[$qid])) {
  2294. $type = $questionTypeCache[$qid];
  2295. } else {
  2296. $type = $this->determineQuestionType($q);
  2297. if ($qid) {
  2298. $questionTypeCache[$qid] = $type;
  2299. }
  2300. }
  2301. if (!isset($buckets[$type])) {
  2302. $type = 'answer';
  2303. }
  2304. $buckets[$type][] = $q;
  2305. }
  2306. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2307. // 修复:不自动减少目标数量,确保达到用户要求
  2308. $availableCount = count($questions);
  2309. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2310. Log::info('题型配比调整前桶统计', [
  2311. 'target_count' => $targetCount,
  2312. 'available_count' => $availableCount,
  2313. 'targets' => $targets,
  2314. 'bucket_counts' => [
  2315. 'choice' => count($buckets['choice']),
  2316. 'fill' => count($buckets['fill']),
  2317. 'answer' => count($buckets['answer']),
  2318. ],
  2319. 'raw_ratio' => $typeRatio,
  2320. ]);
  2321. // 随机打乱桶
  2322. foreach ($buckets as $k => $v) {
  2323. if (!empty($v)) {
  2324. shuffle($v);
  2325. $buckets[$k] = $v;
  2326. }
  2327. }
  2328. $selected = [];
  2329. $selectedIds = [];
  2330. // 按目标数依次取题
  2331. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2332. $need = $targets[$typeKey] ?? 0;
  2333. if ($need <= 0 || empty($buckets[$typeKey])) {
  2334. continue;
  2335. }
  2336. $take = min($need, count($buckets[$typeKey]));
  2337. $slice = array_slice($buckets[$typeKey], 0, $take);
  2338. foreach ($slice as $q) {
  2339. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2340. if (isset($selectedIds[$id])) {
  2341. continue;
  2342. }
  2343. $selected[] = $q;
  2344. $selectedIds[$id] = true;
  2345. }
  2346. }
  2347. // 不足则从剩余题中补齐
  2348. if (count($selected) < $targetCount) {
  2349. $remaining = [];
  2350. foreach ($buckets as $v) {
  2351. foreach ($v as $q) {
  2352. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2353. if (!isset($selectedIds[$id])) {
  2354. $remaining[] = $q;
  2355. }
  2356. }
  2357. }
  2358. shuffle($remaining);
  2359. $needMore = $targetCount - count($selected);
  2360. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2361. }
  2362. // 截断至目标数
  2363. $selected = array_slice($selected, 0, $targetCount);
  2364. // 使用缓存统计题型分布
  2365. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2366. foreach ($selected as $q) {
  2367. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2368. if ($qid && isset($questionTypeCache[$qid])) {
  2369. $type = $questionTypeCache[$qid];
  2370. } else {
  2371. $type = $this->determineQuestionType($q);
  2372. }
  2373. if (isset($selectedCounts[$type])) {
  2374. $selectedCounts[$type]++;
  2375. }
  2376. }
  2377. Log::info('题型配比调整完成', [
  2378. 'target_count' => $targetCount,
  2379. 'targets' => $targets,
  2380. 'selected_counts' => $selectedCounts,
  2381. 'final_selected_count' => count($selected)
  2382. ]);
  2383. return $selected;
  2384. }
  2385. private function determineQuestionType(array $q): string
  2386. {
  2387. // 优先根据题目内容判断(而不是数据库字段)
  2388. $stem = $q['stem'] ?? $q['content'] ?? '';
  2389. // 处理 stem 可能是数组的情况
  2390. if (is_array($stem)) {
  2391. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2392. }
  2393. $tags = $q['tags'] ?? '';
  2394. // 处理 tags 可能是数组的情况
  2395. if (is_array($tags)) {
  2396. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2397. }
  2398. $skills = $q['skills'] ?? [];
  2399. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2400. if (is_string($stem)) {
  2401. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2402. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2403. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2404. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2405. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2406. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2407. // 至少有2个选项就认为是选择题(降低阈值)
  2408. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2409. if ($optionCount >= 2) {
  2410. return 'choice';
  2411. }
  2412. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2413. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2414. return 'choice';
  2415. }
  2416. }
  2417. // 2. 根据技能点判断
  2418. if (is_array($skills) && !empty($skills)) {
  2419. // 过滤非字符串元素,避免 implode 报错
  2420. $skillsFiltered = array_filter($skills, 'is_string');
  2421. if (!empty($skillsFiltered)) {
  2422. $skillsStr = implode(',', $skillsFiltered);
  2423. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2424. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2425. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2426. }
  2427. }
  2428. // 3. 根据题目已有类型字段判断(作为后备)
  2429. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2430. if (is_string($typeField)) {
  2431. $t = strtolower($typeField);
  2432. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2433. return 'choice';
  2434. }
  2435. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2436. return 'fill';
  2437. }
  2438. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2439. return 'answer';
  2440. }
  2441. }
  2442. // 4. 根据标签判断
  2443. if (is_string($tags)) {
  2444. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2445. return 'choice';
  2446. }
  2447. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2448. return 'fill';
  2449. }
  2450. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2451. return 'answer';
  2452. }
  2453. }
  2454. // 5. 根据options字段判断
  2455. if (!empty($q['options']) && is_array($q['options'])) {
  2456. return 'choice';
  2457. }
  2458. // 6. 填空题特征:连续下划线或明显的填空括号
  2459. if (is_string($stem)) {
  2460. // 检查填空题特征:连续下划线
  2461. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2462. return 'fill';
  2463. }
  2464. // 空括号填空
  2465. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2466. return 'fill';
  2467. }
  2468. }
  2469. // 7. 根据题干内容关键词判断
  2470. if (is_string($stem)) {
  2471. // 有证明、解答、计算、求证等关键词的是解答题
  2472. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2473. return 'answer';
  2474. }
  2475. }
  2476. // 默认是解答题(更安全的默认值)
  2477. return 'answer';
  2478. }
  2479. // 【移除】删除未使用的mapDifficultyLevel方法
  2480. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2481. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2482. {
  2483. $map = [
  2484. '选择题' => 'choice',
  2485. '填空题' => 'fill',
  2486. '解答题' => 'answer',
  2487. ];
  2488. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2489. foreach ($questionTypeRatio as $label => $ratio) {
  2490. $key = $map[$label] ?? null;
  2491. if (!$key) {
  2492. continue;
  2493. }
  2494. $cnt = (int) round($targetCount * ($ratio / 100));
  2495. if ($ratio > 0 && $cnt < 1) {
  2496. $cnt = 1;
  2497. }
  2498. $targets[$key] = $cnt;
  2499. }
  2500. $sum = array_sum($targets);
  2501. if ($sum === 0) {
  2502. $targets['answer'] = $targetCount;
  2503. return $targets;
  2504. }
  2505. while ($sum > $targetCount) {
  2506. arsort($targets);
  2507. foreach ($targets as $k => $v) {
  2508. if ($v > 1) {
  2509. $targets[$k]--;
  2510. $sum--;
  2511. break;
  2512. }
  2513. }
  2514. }
  2515. if ($sum < $targetCount) {
  2516. $ratioByKey = [
  2517. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2518. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2519. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  2520. ];
  2521. while ($sum < $targetCount) {
  2522. arsort($ratioByKey);
  2523. $k = array_key_first($ratioByKey);
  2524. $targets[$k]++;
  2525. $sum++;
  2526. }
  2527. }
  2528. return $targets;
  2529. }
  2530. /**
  2531. * 提交手动评分结果到 LearningAnalytics
  2532. *
  2533. * @param array $data 包含 student_id, paper_id, grades 的数组
  2534. * @return array
  2535. */
  2536. public function submitManualGrading(array $data): array
  2537. {
  2538. try {
  2539. $response = Http::timeout($this->timeout)
  2540. ->post($this->baseUrl . '/api/ocr/analyze', [
  2541. 'student_id' => $data['student_id'],
  2542. 'paper_id' => $data['paper_id'],
  2543. 'answers' => $data['grades'],
  2544. ]);
  2545. if ($response->successful()) {
  2546. Log::info('Manual grading submitted successfully', [
  2547. 'student_id' => $data['student_id'],
  2548. 'paper_id' => $data['paper_id'],
  2549. 'question_count' => count($data['grades'])
  2550. ]);
  2551. return $response->json();
  2552. }
  2553. Log::error('Submit Manual Grading Error', [
  2554. 'data' => $data,
  2555. 'status' => $response->status(),
  2556. 'response' => $response->body()
  2557. ]);
  2558. return [
  2559. 'error' => true,
  2560. 'message' => 'Failed to submit manual grading'
  2561. ];
  2562. } catch (\Exception $e) {
  2563. Log::error('Submit Manual Grading Exception', [
  2564. 'error' => $e->getMessage(),
  2565. 'data' => $data
  2566. ]);
  2567. return [
  2568. 'error' => true,
  2569. 'message' => $e->getMessage()
  2570. ];
  2571. }
  2572. }
  2573. /**
  2574. * 分析学生作答结果
  2575. *
  2576. * @param array $data 包含 paper_id, student_id, answers 等
  2577. * @return array
  2578. */
  2579. public function analyzeStudentAnswers(array $data): array
  2580. {
  2581. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  2582. 'student_id' => $data['student_id'] ?? null,
  2583. 'paper_id' => $data['paper_id'] ?? null,
  2584. ]);
  2585. return [
  2586. 'success' => false,
  2587. 'message' => 'analysis_api_disabled',
  2588. ];
  2589. }
  2590. /**
  2591. * 智能补充题目(当指定知识点的题目不足时)
  2592. *
  2593. * @param int $grade 年级
  2594. * @param array $existingKpCodes 已有的知识点代码(用于排除)
  2595. * @param int $needCount 需要补充的题目数量
  2596. * @param int $difficultyCategory 难度类别
  2597. * @param int|null $textbookId 教材ID(用于限制补充范围,避免超纲)
  2598. * @return array 补充的题目列表
  2599. */
  2600. private function getSupplementaryQuestionsForGrade(
  2601. int $grade,
  2602. array $existingKpCodes,
  2603. int $needCount,
  2604. int $difficultyCategory,
  2605. ?int $textbookId = null
  2606. ): array {
  2607. try {
  2608. Log::info('getSupplementaryQuestionsForGrade: 开始智能补充', [
  2609. 'grade' => $grade,
  2610. 'existing_kp_count' => count($existingKpCodes),
  2611. 'need_count' => $needCount,
  2612. 'difficulty_category' => $difficultyCategory,
  2613. 'textbook_id' => $textbookId,
  2614. 'note' => $textbookId ? '限制在指定教材范围内,避免超纲' : '使用整个年级范围'
  2615. ]);
  2616. // 查询同年级其他知识点的题目
  2617. $query = \App\Models\Question::query();
  2618. // 排除已选知识点
  2619. if (!empty($existingKpCodes)) {
  2620. $query->whereNotIn('kp_code', $existingKpCodes);
  2621. }
  2622. // 【修复超纲问题】限制在指定教材范围内(通过教材关联)
  2623. // 如果有 textbook_id,只从该教材的知识点中补充,避免七年级上册学生拿到下册题目
  2624. $gradeKpCodes = $this->getGradeKnowledgePoints($grade, $textbookId);
  2625. if (!empty($gradeKpCodes)) {
  2626. $query->whereIn('kp_code', $gradeKpCodes);
  2627. Log::info('getSupplementaryQuestionsForGrade: 应用知识点范围限制', [
  2628. 'kp_codes_count' => count($gradeKpCodes),
  2629. 'textbook_id' => $textbookId
  2630. ]);
  2631. } else {
  2632. Log::warning('getSupplementaryQuestionsForGrade: 未找到年级知识点,跳过补充', [
  2633. 'grade' => $grade,
  2634. 'textbook_id' => $textbookId
  2635. ]);
  2636. return [];
  2637. }
  2638. // 筛选有解题思路的题目
  2639. $query->whereNotNull('solution')
  2640. ->where('solution', '!=', '')
  2641. ->where('solution', '!=', '[]');
  2642. // 【重要】移除题目分类限制,允许补充其他分类的题目
  2643. // $query->where('question_category', 1); // 移除这行
  2644. // 根据难度类别调整查询
  2645. $difficultyRanges = $this->getDifficultyRangesForCategory($difficultyCategory);
  2646. $query->where(function ($q) use ($difficultyRanges) {
  2647. foreach ($difficultyRanges as $range) {
  2648. $q->orWhereBetween('difficulty', [$range['min'], $range['max']]);
  2649. }
  2650. });
  2651. // 随机排序,增加多样性
  2652. $query->inRandomOrder()
  2653. ->limit($needCount * 2); // 多取一些,后续筛选
  2654. $supplementaryQuestions = $query->get();
  2655. Log::info('getSupplementaryQuestionsForGrade: 查询完成', [
  2656. 'found_count' => $supplementaryQuestions->count(),
  2657. 'need_count' => $needCount
  2658. ]);
  2659. // 格式化题目
  2660. $formatted = [];
  2661. foreach ($supplementaryQuestions as $question) {
  2662. // 优先使用题库原始题型
  2663. $stem = $question->stem ?? '';
  2664. $options = is_array($question->options) ? $question->options : (json_decode($question->options ?? '[]', true) ?: []);
  2665. $correctAnswer = $question->correct_answer ?? '';
  2666. $questionType = $question->question_type ?? 'answer';
  2667. $formatted[] = [
  2668. 'id' => $question->id,
  2669. 'question_bank_id' => $question->id,
  2670. 'question_type' => $questionType,
  2671. 'kp_code' => $question->kp_code,
  2672. 'difficulty' => $question->difficulty !== null ? (float) $question->difficulty : 0.5,
  2673. 'stem' => $stem,
  2674. 'options' => $options,
  2675. 'correct_answer' => $correctAnswer,
  2676. 'solution' => $question->solution,
  2677. 'score' => $question->score ?? 4,
  2678. 'estimated_time' => $question->estimated_time ?? 300,
  2679. 'metadata' => [
  2680. 'question_type_label' => $questionType === 'choice' ? '选择题' : ($questionType === 'fill' ? '填空题' : '解答题'),
  2681. 'difficulty_label' => $this->getDifficultyLabelFromObject($question->difficulty ?? 0.5),
  2682. 'is_supplementary' => true
  2683. ]
  2684. ];
  2685. }
  2686. // 随机选择需要的数量
  2687. shuffle($formatted);
  2688. $selected = array_slice($formatted, 0, $needCount);
  2689. Log::info('getSupplementaryQuestionsForGrade: 补充完成', [
  2690. 'supplementary_count' => count($selected),
  2691. 'kp_distribution' => array_count_values(array_column($selected, 'kp_code'))
  2692. ]);
  2693. return $selected;
  2694. } catch (\Exception $e) {
  2695. Log::error('getSupplementaryQuestionsForGrade: 补充失败', [
  2696. 'grade' => $grade,
  2697. 'need_count' => $needCount,
  2698. 'error' => $e->getMessage()
  2699. ]);
  2700. return [];
  2701. }
  2702. }
  2703. /**
  2704. * 获取指定年级的知识点列表
  2705. *
  2706. * @param int $grade 年级
  2707. * @param int|null $textbookId 教材ID(可选,用于限制在特定教材范围内,避免超纲)
  2708. * @return array 知识点代码列表
  2709. */
  2710. private function getGradeKnowledgePoints(int $grade, ?int $textbookId = null): array
  2711. {
  2712. try {
  2713. $query = DB::table('textbook_chapter_knowledge_relation as tckr')
  2714. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  2715. ->join('textbooks as t', 'tcn.textbook_id', '=', 't.id')
  2716. ->where('t.grade', $grade);
  2717. // 【修复超纲问题】如果有 textbook_id,严格限制在该教材范围内
  2718. // 避免七年级上册学生拿到七年级下册的知识点
  2719. if ($textbookId) {
  2720. $query->where('t.id', $textbookId);
  2721. Log::info('getGradeKnowledgePoints: 限制在指定教材范围内', [
  2722. 'grade' => $grade,
  2723. 'textbook_id' => $textbookId
  2724. ]);
  2725. }
  2726. $kpCodes = $query->distinct()
  2727. ->pluck('tckr.kp_code')
  2728. ->toArray();
  2729. Log::info('getGradeKnowledgePoints: 获取知识点完成', [
  2730. 'grade' => $grade,
  2731. 'textbook_id' => $textbookId,
  2732. 'kp_count' => count($kpCodes)
  2733. ]);
  2734. return array_filter($kpCodes);
  2735. } catch (\Exception $e) {
  2736. Log::error('getGradeKnowledgePoints: 查询失败', [
  2737. 'grade' => $grade,
  2738. 'textbook_id' => $textbookId,
  2739. 'error' => $e->getMessage()
  2740. ]);
  2741. return [];
  2742. }
  2743. }
  2744. /**
  2745. * 【新增】根据难度类别获取难度范围
  2746. */
  2747. private function getDifficultyRangesForCategory(int $difficultyCategory): array
  2748. {
  2749. return match($difficultyCategory) {
  2750. 1 => [
  2751. ['min' => 0.0, 'max' => 0.5], // 基础型:偏向低难度
  2752. ['min' => 0.5, 'max' => 1.0],
  2753. ],
  2754. 2 => [
  2755. ['min' => 0.0, 'max' => 0.5], // 进阶型:均衡分布
  2756. ['min' => 0.5, 'max' => 1.0],
  2757. ],
  2758. 3 => [
  2759. ['min' => 0.25, 'max' => 0.75], // 中等型:偏向中等难度
  2760. ['min' => 0.0, 'max' => 1.0],
  2761. ],
  2762. 4 => [
  2763. ['min' => 0.5, 'max' => 1.0], // 拔高型:偏向高难度
  2764. ['min' => 0.0, 'max' => 0.5],
  2765. ],
  2766. default => [
  2767. ['min' => 0.0, 'max' => 1.0],
  2768. ]
  2769. };
  2770. }
  2771. /**
  2772. * 【新增】获取难度标签(重载版本)
  2773. */
  2774. private function getDifficultyLabelFromObject(?float $difficulty): string
  2775. {
  2776. if ($difficulty === null) return '未知';
  2777. if ($difficulty < 0.3) return '基础';
  2778. if ($difficulty < 0.7) return '中等';
  2779. return '拔高';
  2780. }
  2781. private function buildDifficultyDistributionStats(array $questions, int $difficultyCategory): array
  2782. {
  2783. if (empty($questions)) {
  2784. return [];
  2785. }
  2786. $service = app(DifficultyDistributionService::class);
  2787. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  2788. $total = max(1, count($questions));
  2789. return array_map(static function ($bucket) use ($total) {
  2790. $count = count($bucket);
  2791. return [
  2792. 'count' => $count,
  2793. 'ratio' => round(($count / $total) * 100, 2),
  2794. ];
  2795. }, $buckets);
  2796. }
  2797. private function buildDifficultyDistributionShortage(array $questions, int $difficultyCategory, int $totalQuestions): array
  2798. {
  2799. $service = app(DifficultyDistributionService::class);
  2800. $distribution = $service->calculateDistribution($difficultyCategory, $totalQuestions);
  2801. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  2802. $expected = [
  2803. 'primary_low' => 0,
  2804. 'primary_medium' => 0,
  2805. 'primary_high' => 0,
  2806. 'secondary' => 0,
  2807. 'other' => 0,
  2808. ];
  2809. foreach ($distribution as $level => $config) {
  2810. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  2811. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  2812. }
  2813. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  2814. $shortage = [];
  2815. foreach ($expected as $bucketKey => $count) {
  2816. $actualCount = $actual[$bucketKey] ?? 0;
  2817. $shortage[$bucketKey] = [
  2818. 'expected' => $count,
  2819. 'actual' => $actualCount,
  2820. 'short' => max(0, $count - $actualCount),
  2821. ];
  2822. }
  2823. return $shortage;
  2824. }
  2825. private function buildDistributionCandidates(array $allQuestions, array $selectedQuestions, int $difficultyCategory): array
  2826. {
  2827. if (empty($allQuestions)) {
  2828. return $selectedQuestions;
  2829. }
  2830. $service = app(DifficultyDistributionService::class);
  2831. $distribution = $service->calculateDistribution($difficultyCategory, max(1, count($selectedQuestions)));
  2832. $buckets = $service->groupQuestionsByDifficultyRange($allQuestions, $difficultyCategory);
  2833. $preferredBuckets = [];
  2834. foreach ($distribution as $level => $config) {
  2835. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  2836. $preferredBuckets[$bucketKey] = true;
  2837. }
  2838. $candidates = [];
  2839. foreach (array_keys($preferredBuckets) as $bucketKey) {
  2840. foreach ($buckets[$bucketKey] ?? [] as $q) {
  2841. $candidates[] = $q;
  2842. }
  2843. }
  2844. foreach ($selectedQuestions as $q) {
  2845. $candidates[] = $q;
  2846. }
  2847. $seen = [];
  2848. $unique = [];
  2849. foreach ($candidates as $q) {
  2850. $id = $q['id'] ?? null;
  2851. if (!$id || isset($seen[$id])) {
  2852. continue;
  2853. }
  2854. $seen[$id] = true;
  2855. $unique[] = $q;
  2856. }
  2857. return $unique;
  2858. }
  2859. }