LearningAnalyticsService.php 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278
  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.7) // 掌握度低于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. // 按学段筛选(题库 grade: 2=初中, 3=高中)
  1502. if ($grade !== null) {
  1503. $stageGrade = $this->normalizeQuestionStageGrade((int) $grade);
  1504. if ($stageGrade !== null) {
  1505. $query->where('grade', $stageGrade);
  1506. Log::info('应用学段筛选', [
  1507. 'input_grade' => $grade,
  1508. 'stage_grade' => $stageGrade
  1509. ]);
  1510. }
  1511. }
  1512. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1513. if (!empty($skills)) {
  1514. $query->where(function ($q) use ($skills) {
  1515. foreach ($skills as $skill) {
  1516. $q->orWhere('tags', 'like', "%{$skill}%");
  1517. }
  1518. });
  1519. Log::info('应用技能筛选', ['skills' => $skills]);
  1520. }
  1521. // 排除学生已做过的题目
  1522. if (!empty($excludeQuestionIds)) {
  1523. $query->whereNotIn('id', $excludeQuestionIds);
  1524. Log::info('应用排除筛选', ['exclude_count' => count($excludeQuestionIds)]);
  1525. }
  1526. // 按题目分类筛选(如果指定了 question_category)
  1527. if ($questionCategory !== null) {
  1528. $query->where('question_category', $questionCategory);
  1529. Log::info('应用题目分类筛选', ['question_category' => $questionCategory]);
  1530. }
  1531. // 筛选有解题思路的题目
  1532. $query->whereNotNull('solution')
  1533. ->where('solution', '!=', '')
  1534. ->where('solution', '!=', '[]');
  1535. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1536. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1537. // 【重要】移除数量限制,获取所有符合条件的题目
  1538. // 不使用limit()限制查询结果,让后续处理逻辑决定最终数量
  1539. $query->inRandomOrder();
  1540. $questions = $query->get();
  1541. Log::info('getQuestionsFromBank: 查询完成', [
  1542. 'raw_count' => $questions->count(),
  1543. 'total_needed' => $totalNeeded,
  1544. 'note' => '移除limit限制,获取所有符合条件的题目',
  1545. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1546. ]);
  1547. // 【重要】添加更详细的日志来追踪题目筛选过程
  1548. Log::info('getQuestionsFromBank: 题目筛选过程详情', [
  1549. 'database_query_count' => $questions->count(),
  1550. 'kp_codes_filter' => $kpCodes,
  1551. 'skills_filter' => $skills,
  1552. 'exclude_count' => count($excludeQuestionIds),
  1553. 'question_category' => $questionCategory,
  1554. 'textbook_catalog_node_ids_filter' => $textbookCatalogNodeIds,
  1555. 'note' => '将返回所有符合条件的题目,不限制数量'
  1556. ]);
  1557. // 转换为标准格式
  1558. $formattedQuestions = $questions->map(function ($q) {
  1559. return [
  1560. 'id' => $q->id,
  1561. 'question_code' => $q->question_code,
  1562. 'kp_code' => $q->kp_code,
  1563. 'question_type' => $q->question_type,
  1564. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1565. 'stem' => $q->stem,
  1566. 'solution' => $q->solution,
  1567. 'metadata' => [
  1568. 'has_solution' => true,
  1569. 'is_choice' => $q->question_type === 'choice',
  1570. 'is_fill' => $q->question_type === 'fill',
  1571. 'is_answer' => $q->question_type === 'answer',
  1572. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1573. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1574. ]
  1575. ];
  1576. })->toArray();
  1577. // 【重要】返回所有符合条件的题目,不限制数量
  1578. // 让上层调用者根据需要选择题目数量
  1579. $selectedQuestions = $formattedQuestions;
  1580. // 【修复】重新启用智能补充功能,增加 textbook_id 限制避免超纲
  1581. if ($totalNeeded > 0 && count($selectedQuestions) < $totalNeeded && $grade !== null) {
  1582. $deficit = $totalNeeded - count($selectedQuestions);
  1583. Log::warning('getQuestionsFromBank: 指定知识点题目不足,尝试智能补充', [
  1584. 'deficit' => $deficit,
  1585. 'available_count' => count($selectedQuestions),
  1586. 'grade' => $grade,
  1587. 'textbook_id' => $textbookId,
  1588. 'strategy' => $textbookId ? '从指定教材的其他知识点补充(避免超纲)' : '从同年级其他知识点补充'
  1589. ]);
  1590. // 【修复超纲问题】补充策略:从同年级同教材的其他知识点补充
  1591. // 传入 textbook_id 参数,避免七年级上册学生拿到下册题目
  1592. $supplementaryQuestions = $this->getSupplementaryQuestionsForGrade(
  1593. $grade,
  1594. array_column($selectedQuestions, 'kp_code'),
  1595. $deficit,
  1596. $difficultyCategory,
  1597. $textbookId // 【关键】传入教材ID,限制补充范围
  1598. );
  1599. if (!empty($supplementaryQuestions)) {
  1600. $selectedQuestions = array_merge($selectedQuestions, $supplementaryQuestions);
  1601. Log::info('getQuestionsFromBank: 智能补充完成', [
  1602. 'supplementary_count' => count($supplementaryQuestions),
  1603. 'total_after_supplement' => count($selectedQuestions),
  1604. 'textbook_id' => $textbookId
  1605. ]);
  1606. } else {
  1607. Log::warning('getQuestionsFromBank: 智能补充失败,未找到合适的题目', [
  1608. 'grade' => $grade,
  1609. 'textbook_id' => $textbookId,
  1610. 'note' => $textbookId ? '可能是该教材知识点题目不足' : '该年级题目不足'
  1611. ]);
  1612. }
  1613. }
  1614. Log::info('getQuestionsFromBank 完成', [
  1615. 'final_count' => count($selectedQuestions),
  1616. 'raw_database_count' => $questions->count(),
  1617. 'total_needed' => $totalNeeded,
  1618. 'success' => $totalNeeded > 0 ? count($selectedQuestions) >= $totalNeeded : true,
  1619. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1620. ]);
  1621. return $selectedQuestions;
  1622. } catch (\Exception $e) {
  1623. Log::error('getQuestionsFromBank 查询失败', [
  1624. 'error' => $e->getMessage(),
  1625. 'trace' => $e->getTraceAsString()
  1626. ]);
  1627. throw $e;
  1628. }
  1629. }
  1630. /**
  1631. * 获取指定ID的题目详情
  1632. */
  1633. private function getLocalQuestionsByIds(array $questionIds): array
  1634. {
  1635. try {
  1636. // 通过QuestionBankService获取题目详情
  1637. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1638. // 批量获取题目详情
  1639. $response = $questionBankService->getQuestionsByIds($questionIds);
  1640. if (empty($response['data'])) {
  1641. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1642. 'requested_ids' => $questionIds
  1643. ]);
  1644. return [];
  1645. }
  1646. $questions = $response['data'];
  1647. // 转换为标准格式
  1648. $result = array_map(function ($q) {
  1649. $difficulty = $q['difficulty'] ?? 0.5;
  1650. return [
  1651. 'id' => $q['id'],
  1652. 'question_code' => $q['question_code'] ?? '',
  1653. 'kp_code' => $q['kp_code'] ?? '',
  1654. 'question_type' => $q['question_type'] ?? 'choice',
  1655. 'difficulty' => (float) $difficulty,
  1656. 'stem' => $q['stem'] ?? '',
  1657. 'solution' => $q['solution'] ?? '',
  1658. 'answer' => $q['answer'] ?? '',
  1659. 'metadata' => [
  1660. 'has_solution' => !empty($q['solution']),
  1661. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1662. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1663. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1664. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1665. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1666. ]
  1667. ];
  1668. }, $questions);
  1669. Log::info('getLocalQuestionsByIds 获取成功', [
  1670. 'requested_count' => count($questionIds),
  1671. 'found_count' => count($result),
  1672. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1673. 'question_ids' => array_slice($questionIds, 0, 20),
  1674. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1675. ]);
  1676. return $result;
  1677. } catch (\Exception $e) {
  1678. Log::error('getLocalQuestionsByIds 获取失败', [
  1679. 'question_ids' => $questionIds,
  1680. 'error' => $e->getMessage(),
  1681. 'trace' => $e->getTraceAsString()
  1682. ]);
  1683. return [];
  1684. }
  1685. }
  1686. /**
  1687. * 获取卷子的所有题目ID(不区分对错)
  1688. */
  1689. private function getPaperAllQuestions(array $paperIds): array
  1690. {
  1691. try {
  1692. // 查询 paper_questions 表获取所有题目ID
  1693. $questionIds = DB::table('paper_questions')
  1694. ->whereIn('paper_id', $paperIds)
  1695. ->pluck('question_bank_id')
  1696. ->unique()
  1697. ->filter()
  1698. ->values()
  1699. ->toArray();
  1700. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1701. 'paper_ids' => $paperIds,
  1702. 'question_count' => count($questionIds)
  1703. ]);
  1704. return $questionIds;
  1705. } catch (\Exception $e) {
  1706. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1707. 'paper_ids' => $paperIds,
  1708. 'error' => $e->getMessage()
  1709. ]);
  1710. return [];
  1711. }
  1712. }
  1713. /**
  1714. * 获取难度标签
  1715. */
  1716. private function getDifficultyLabel(?float $difficulty): string
  1717. {
  1718. if ($difficulty === null) {
  1719. return '未知';
  1720. }
  1721. return match (true) {
  1722. $difficulty < 0.4 => '基础',
  1723. $difficulty < 0.7 => '中等',
  1724. default => '拔高'
  1725. };
  1726. }
  1727. /**
  1728. * 获取题型标签
  1729. */
  1730. private function getQuestionTypeLabel(string $questionType): string
  1731. {
  1732. return match ($questionType) {
  1733. 'choice' => '选择题',
  1734. 'fill' => '填空题',
  1735. 'answer' => '解答题',
  1736. default => '未知题型'
  1737. };
  1738. }
  1739. /**
  1740. * 根据题型配比选择题目
  1741. * 注意: 难度配比调整由 QuestionLocalService 处理
  1742. */
  1743. private function selectQuestionsByRatio(
  1744. array $questions,
  1745. int $totalNeeded,
  1746. array $questionTypeRatio = []
  1747. ): array {
  1748. if (empty($questions)) {
  1749. return [];
  1750. }
  1751. // 如果没有配比要求,直接返回
  1752. if (empty($questionTypeRatio)) {
  1753. return array_slice($questions, 0, $totalNeeded);
  1754. }
  1755. $selected = [];
  1756. $usedIndices = [];
  1757. // 按题型配比选择
  1758. if (!empty($questionTypeRatio)) {
  1759. foreach ($questionTypeRatio as $type => $ratio) {
  1760. $count = (int) round(($ratio / 100) * $totalNeeded);
  1761. if ($count <= 0) continue;
  1762. $typeQuestions = [];
  1763. foreach ($questions as $idx => $q) {
  1764. if (in_array($idx, $usedIndices)) continue;
  1765. $qType = $q['question_type'] ?? '';
  1766. $label = $this->getQuestionTypeLabel($qType);
  1767. if ($label === $type) {
  1768. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1769. }
  1770. }
  1771. // 随机选择
  1772. shuffle($typeQuestions);
  1773. $selectedCount = min($count, count($typeQuestions));
  1774. for ($i = 0; $i < $selectedCount; $i++) {
  1775. $selected[] = $typeQuestions[$i]['question'];
  1776. $usedIndices[] = $typeQuestions[$i]['idx'];
  1777. }
  1778. }
  1779. }
  1780. // 如果还有空缺,补充剩余题目
  1781. // 注意: 难度配比调整由 QuestionLocalService 处理
  1782. if (count($selected) < $totalNeeded) {
  1783. foreach ($questions as $idx => $q) {
  1784. if (count($selected) >= $totalNeeded) break;
  1785. if (!in_array($idx, $usedIndices)) {
  1786. $selected[] = $q;
  1787. $usedIndices[] = $idx;
  1788. }
  1789. }
  1790. }
  1791. return array_slice($selected, 0, $totalNeeded);
  1792. }
  1793. /**
  1794. * 根据学生掌握度筛选题目
  1795. */
  1796. private function selectQuestionsByMastery(
  1797. array $questions,
  1798. ?string $studentId,
  1799. int $totalQuestions,
  1800. array $questionTypeRatio,
  1801. array $difficultyLevels,
  1802. array $weaknessFilter,
  1803. int $assembleType // 新增assembleType参数
  1804. ): array {
  1805. Log::info('selectQuestionsByMastery 开始', [
  1806. 'question_count' => count($questions),
  1807. 'student_id' => $studentId,
  1808. 'total_questions' => $totalQuestions,
  1809. 'unique_kp_count' => count(array_unique(array_column($questions, 'kp_code'))),
  1810. 'assemble_type' => $assembleType,
  1811. 'note' => '追踪输入题目数量和知识点多样性'
  1812. ]);
  1813. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1814. // 如果题目数量超过目标,则截取到目标数量
  1815. // 如果题目数量不足,则使用所有题目,并记录警告
  1816. if (count($questions) > $totalQuestions) {
  1817. Log::info('题目数量超过目标,进行截取', [
  1818. 'question_count' => count($questions),
  1819. 'total_questions' => $totalQuestions,
  1820. 'note' => '将按权重选择最合适的题目'
  1821. ]);
  1822. } else {
  1823. Log::warning('题目数量不足,将使用所有可用题目', [
  1824. 'available_count' => count($questions),
  1825. 'requested_count' => $totalQuestions,
  1826. 'note' => '可能需要补充题库或放宽筛选条件'
  1827. ]);
  1828. }
  1829. // 【移除】删除多余的难度筛选逻辑
  1830. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1831. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1832. Log::info('跳过多余的难度筛选,使用题目原始难度分布', [
  1833. 'question_count' => count($questions),
  1834. 'note' => '由QuestionLocalService处理难度分布'
  1835. ]);
  1836. // 1. 按知识点分组
  1837. Log::info('开始按知识点分组', [
  1838. 'question_count' => count($questions)
  1839. ]);
  1840. $groupStartTime = microtime(true);
  1841. $questionsByKp = [];
  1842. foreach ($questions as $question) {
  1843. $kpCode = $question['kp_code'] ?? '';
  1844. if (!isset($questionsByKp[$kpCode])) {
  1845. $questionsByKp[$kpCode] = [];
  1846. }
  1847. $questionsByKp[$kpCode][] = $question;
  1848. }
  1849. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1850. Log::info('按知识点分组完成', [
  1851. 'kp_count' => count($questionsByKp),
  1852. 'group_time_ms' => round($groupTime, 2)
  1853. ]);
  1854. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1855. $kpWeights = [];
  1856. $kpCodes = array_keys($questionsByKp);
  1857. Log::info('开始计算知识点权重(用于题型内排序)', [
  1858. 'kp_count' => count($kpCodes),
  1859. 'student_id' => $studentId
  1860. ]);
  1861. $startTime = microtime(true);
  1862. $allMastery = [];
  1863. if ($studentId) {
  1864. // 批量获取所有知识点的掌握度(一次查询)
  1865. $masteryStart = microtime(true);
  1866. try {
  1867. $masteryRecords = DB::table('student_mastery')
  1868. ->where('student_id', $studentId)
  1869. ->whereIn('kp', $kpCodes)
  1870. ->pluck('mastery', 'kp')
  1871. ->all();
  1872. Log::debug('批量获取掌握度', [
  1873. 'student_id' => $studentId,
  1874. 'kp_count' => count($kpCodes),
  1875. 'found_count' => count($masteryRecords),
  1876. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1877. ]);
  1878. $allMastery = $masteryRecords;
  1879. } catch (\Exception $e) {
  1880. Log::warning('批量获取掌握度失败,将使用默认值', [
  1881. 'student_id' => $studentId,
  1882. 'error' => $e->getMessage()
  1883. ]);
  1884. }
  1885. }
  1886. foreach ($kpCodes as $kpCode) {
  1887. if ($studentId) {
  1888. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1889. // 薄弱点权重更高
  1890. if (in_array($kpCode, $weaknessFilter)) {
  1891. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1892. } else {
  1893. // 掌握度越低,权重越高
  1894. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1895. }
  1896. Log::debug('计算知识点权重', [
  1897. 'kp_code' => $kpCode,
  1898. 'mastery' => $mastery,
  1899. 'weight' => $kpWeights[$kpCode]
  1900. ]);
  1901. } else {
  1902. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1903. }
  1904. }
  1905. $totalWeightTime = (microtime(true) - $startTime) * 1000;
  1906. Log::info('知识点权重计算完成', [
  1907. 'total_kp_count' => count($kpCodes),
  1908. 'total_weight_time_ms' => round($totalWeightTime, 2),
  1909. 'avg_time_per_kp_ms' => count($kpCodes) > 0 ? round($totalWeightTime / count($kpCodes), 2) : 0
  1910. ]);
  1911. // 3. 按题型分配题目数量(权重用于题型内排序)
  1912. $selectedQuestions = [];
  1913. // 将所有题目合并
  1914. $weightedQuestions = [];
  1915. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1916. foreach ($kpQuestions as $q) {
  1917. $q['kp_code'] = $kpCode;
  1918. $weightedQuestions[] = $q;
  1919. }
  1920. }
  1921. // ========== 知识点优先选择机制 ==========
  1922. // 摸底测试的核心目标是最大化知识点覆盖
  1923. // 题型只是约束条件(每种至少1题)
  1924. // 首先按题型分组
  1925. $questionsByType = [
  1926. 'choice' => [],
  1927. 'fill' => [],
  1928. 'answer' => [],
  1929. ];
  1930. foreach ($weightedQuestions as $q) {
  1931. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1932. if ($qid && isset($questionTypeCache[$qid])) {
  1933. $type = $questionTypeCache[$qid];
  1934. } else {
  1935. $type = $this->determineQuestionType($q);
  1936. if ($qid) {
  1937. $questionTypeCache[$qid] = $type;
  1938. }
  1939. }
  1940. if (!isset($questionsByType[$type])) {
  1941. $type = 'answer'; // 默认归类为answer
  1942. }
  1943. $questionsByType[$type][] = $q;
  1944. }
  1945. // ========== 步骤1:按题型分配题目 ==========
  1946. $selectedQuestions = [];
  1947. // 【区分】根据assembleType决定是否使用知识点优先机制
  1948. $useKnowledgePointPriority = ($assembleType === 0); // 摸底测试需要知识点优先
  1949. $kpSelected = []; // 已选知识点记录
  1950. Log::info('selectQuestionsByMastery: 知识点优先策略', [
  1951. 'assemble_type' => $assembleType,
  1952. 'use_knowledge_point_priority' => $useKnowledgePointPriority,
  1953. 'note' => $useKnowledgePointPriority ? '摸底测试:需要均衡分配知识点' : '知识点组卷:允许同一知识点选多题'
  1954. ]);
  1955. // 确保每种题型至少选1题
  1956. foreach (['choice', 'fill', 'answer'] as $type) {
  1957. if (empty($questionsByType[$type])) {
  1958. Log::warning('题型分配:题型无题目', ['type' => $type]);
  1959. continue;
  1960. }
  1961. // 按权重排序该题型的题目
  1962. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  1963. $kpA = $a['kp_code'] ?? '';
  1964. $kpB = $b['kp_code'] ?? '';
  1965. $weightA = $kpWeights[$kpA] ?? 1.0;
  1966. $weightB = $kpWeights[$kpB] ?? 1.0;
  1967. return $weightB <=> $weightA;
  1968. });
  1969. // 【修复】摸底测试题型基础分配:记录每个题型的知识点分布
  1970. $typeKpDistribution = [];
  1971. foreach ($questionsByType[$type] as $q) {
  1972. $kpCode = $q['kp_code'] ?? '';
  1973. if (!isset($typeKpDistribution[$kpCode])) {
  1974. $typeKpDistribution[$kpCode] = 0;
  1975. }
  1976. $typeKpDistribution[$kpCode]++;
  1977. }
  1978. Log::info('摸底测试题型基础分配开始', [
  1979. 'type' => $type,
  1980. 'total_questions_in_type' => count($questionsByType[$type]),
  1981. 'kp_distribution_in_type' => $typeKpDistribution,
  1982. 'available_kp_count' => count($typeKpDistribution)
  1983. ]);
  1984. // 根据策略选择题目
  1985. if ($useKnowledgePointPriority) {
  1986. // 摸底测试:选择第一个未选过知识点的题目
  1987. $selectedInThisType = 0;
  1988. foreach ($questionsByType[$type] as $q) {
  1989. $kpCode = $q['kp_code'] ?? '';
  1990. if (!isset($kpSelected[$kpCode])) {
  1991. $selectedQuestions[] = $q;
  1992. $kpSelected[$kpCode] = true;
  1993. $selectedInThisType++;
  1994. Log::debug('题型基础分配(知识点优先)', [
  1995. 'type' => $type,
  1996. 'kp' => $kpCode,
  1997. 'question_id' => $q['id'] ?? 'unknown',
  1998. 'selected_in_type' => $selectedInThisType
  1999. ]);
  2000. break; // 只选1题
  2001. }
  2002. }
  2003. Log::info('摸底测试题型基础分配完成', [
  2004. 'type' => $type,
  2005. 'selected_count' => $selectedInThisType,
  2006. 'note' => $selectedInThisType > 0 ? '成功选择' : '无可用知识点'
  2007. ]);
  2008. } else {
  2009. // 【修复】知识点组卷:随机选择该题型的一道题,避免固定选择第一个导致知识点分布不均
  2010. $randomIndex = array_rand($questionsByType[$type]);
  2011. $selectedQuestions[] = $questionsByType[$type][$randomIndex];
  2012. Log::debug('题型基础分配(随机选择)', [
  2013. 'type' => $type,
  2014. 'kp' => $questionsByType[$type][$randomIndex]['kp_code'] ?? 'unknown',
  2015. 'random_index' => $randomIndex,
  2016. 'total_in_type' => count($questionsByType[$type])
  2017. ]);
  2018. }
  2019. }
  2020. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  2021. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  2022. // 【重要】添加排序前的知识点分布日志
  2023. $preSortKpDistribution = [];
  2024. foreach ($allQuestions as $q) {
  2025. $kpCode = $q['kp_code'] ?? '';
  2026. if (!isset($preSortKpDistribution[$kpCode])) {
  2027. $preSortKpDistribution[$kpCode] = 0;
  2028. }
  2029. $preSortKpDistribution[$kpCode]++;
  2030. }
  2031. Log::info('selectQuestionsByMastery: 排序前知识点分布', [
  2032. 'total_questions' => count($allQuestions),
  2033. 'kp_distribution' => $preSortKpDistribution,
  2034. 'note' => '用于对比排序后的分布变化'
  2035. ]);
  2036. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  2037. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  2038. $kpA = $a['kp_code'] ?? '';
  2039. $kpB = $b['kp_code'] ?? '';
  2040. $weightA = $kpWeights[$kpA] ?? 1.0;
  2041. $weightB = $kpWeights[$kpB] ?? 1.0;
  2042. // 主要按权重排序
  2043. if ($weightA != $weightB) {
  2044. return $weightB <=> $weightA;
  2045. }
  2046. // 权重相同时,添加随机排序而不是按ID排序
  2047. // 使用随机因子确保相同权重的知识点有公平的选中机会
  2048. return mt_rand(-1, 1);
  2049. });
  2050. // 【重要】添加排序后的知识点分布日志
  2051. $postSortKpDistribution = [];
  2052. $postSortFirst50 = []; // 记录前50题的知识点分布
  2053. foreach ($allQuestions as $idx => $q) {
  2054. $kpCode = $q['kp_code'] ?? '';
  2055. if (!isset($postSortKpDistribution[$kpCode])) {
  2056. $postSortKpDistribution[$kpCode] = 0;
  2057. }
  2058. $postSortKpDistribution[$kpCode]++;
  2059. // 记录前50题的知识点
  2060. if ($idx < 50) {
  2061. $postSortFirst50[] = $kpCode;
  2062. }
  2063. }
  2064. Log::info('selectQuestionsByMastery: 排序后知识点分布', [
  2065. 'total_questions' => count($allQuestions),
  2066. 'kp_distribution' => $postSortKpDistribution,
  2067. 'first_50_kp_codes' => $postSortFirst50,
  2068. 'note' => '观察排序是否均衡分布A07和A08'
  2069. ]);
  2070. // 【修复】摸底测试继续选择题目:记录详细的选题过程
  2071. Log::info('摸底测试继续选择题目开始', [
  2072. 'selected_count_after_basic' => count($selectedQuestions),
  2073. 'total_questions' => $totalQuestions,
  2074. 'selected_kp_codes' => array_keys($kpSelected),
  2075. 'available_kp_count' => count($preSortKpDistribution),
  2076. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制'
  2077. ]);
  2078. if ($useKnowledgePointPriority) {
  2079. // 摸底测试:优先选择未选过知识点的题目
  2080. $initialSelectedCount = count($selectedQuestions);
  2081. $prioritySelectedCount = 0;
  2082. foreach ($allQuestions as $q) {
  2083. if (count($selectedQuestions) >= $totalQuestions) break;
  2084. $kpCode = $q['kp_code'] ?? '';
  2085. if (!isset($kpSelected[$kpCode])) {
  2086. $selectedQuestions[] = $q;
  2087. $kpSelected[$kpCode] = true;
  2088. $prioritySelectedCount++;
  2089. Log::debug('继续选择题目(知识点优先)', [
  2090. 'kp' => $kpCode,
  2091. 'id' => $q['id'] ?? 'unknown',
  2092. 'priority_selected_count' => $prioritySelectedCount,
  2093. 'total_selected' => count($selectedQuestions)
  2094. ]);
  2095. }
  2096. }
  2097. Log::info('摸底测试优先阶段完成', [
  2098. 'priority_selected_count' => $prioritySelectedCount,
  2099. 'total_selected' => count($selectedQuestions),
  2100. 'unique_kp_count' => count($kpSelected),
  2101. 'note' => '优先选择未选过知识点的题目'
  2102. ]);
  2103. // 【修复】降级策略:如果仍未达到目标数量,允许重复选择知识点
  2104. if (count($selectedQuestions) < $totalQuestions) {
  2105. Log::warning('selectQuestionsByMastery: 知识点优先策略无法满足数量要求,启用降级策略', [
  2106. 'requested_count' => $totalQuestions,
  2107. 'selected_count' => count($selectedQuestions),
  2108. 'priority_selected_count' => $prioritySelectedCount,
  2109. 'unique_kp_count' => count($kpSelected),
  2110. 'available_kp_count' => count($preSortKpDistribution),
  2111. 'note' => '将允许重复选择知识点以达到目标数量'
  2112. ]);
  2113. $fallbackSelectedCount = 0;
  2114. $selectedIds = array_column($selectedQuestions, 'id');
  2115. foreach ($allQuestions as $q) {
  2116. if (count($selectedQuestions) >= $totalQuestions) break;
  2117. $qid = $q['id'] ?? null;
  2118. if ($qid && !in_array($qid, $selectedIds)) {
  2119. $selectedQuestions[] = $q;
  2120. $selectedIds[] = $qid;
  2121. $fallbackSelectedCount++;
  2122. Log::debug('降级选择题目(允许知识点重复)', [
  2123. 'kp' => $q['kp_code'] ?? 'unknown',
  2124. 'id' => $qid,
  2125. 'fallback_selected_count' => $fallbackSelectedCount,
  2126. 'current_count' => count($selectedQuestions)
  2127. ]);
  2128. }
  2129. }
  2130. Log::info('摸底测试降级阶段完成', [
  2131. 'fallback_selected_count' => $fallbackSelectedCount,
  2132. 'total_selected' => count($selectedQuestions),
  2133. 'note' => '允许重复选择知识点补充数量'
  2134. ]);
  2135. }
  2136. } else {
  2137. // 知识点组卷:选择未选过的题目(不要求知识点不重复)
  2138. $selectedIds = array_column($selectedQuestions, 'id');
  2139. foreach ($allQuestions as $q) {
  2140. if (count($selectedQuestions) >= $totalQuestions) break;
  2141. $qid = $q['id'] ?? null;
  2142. if ($qid && !in_array($qid, $selectedIds)) {
  2143. $selectedQuestions[] = $q;
  2144. $selectedIds[] = $qid;
  2145. Log::debug('继续选择题目(无知识点限制)', ['kp' => $q['kp_code'] ?? 'unknown', 'id' => $qid]);
  2146. }
  2147. }
  2148. }
  2149. // 【移除】删除步骤3的多余逻辑
  2150. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2151. Log::info('selectQuestionsByMastery: 题目选择完成', [
  2152. 'total_questions' => $totalQuestions,
  2153. 'selected_count' => count($selectedQuestions),
  2154. 'success' => count($selectedQuestions) === $totalQuestions,
  2155. 'assemble_type' => $assembleType,
  2156. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制',
  2157. 'type_distribution' => array_count_values(array_map(function($q) {
  2158. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2159. if ($qid && isset($questionTypeCache[$qid])) {
  2160. return $questionTypeCache[$qid];
  2161. }
  2162. return $this->determineQuestionType($q);
  2163. }, $selectedQuestions)),
  2164. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2165. ]);
  2166. // 【重要】最终截取到目标数量(如果超过)
  2167. if (count($selectedQuestions) > $totalQuestions) {
  2168. Log::info('题目数量超过目标,进行最终截取', [
  2169. 'before' => count($selectedQuestions),
  2170. 'after' => $totalQuestions
  2171. ]);
  2172. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2173. }
  2174. // 【重要】添加最终数量验证日志
  2175. Log::info('selectQuestionsByMastery: 最终题目数量验证', [
  2176. 'before_final_check' => count($selectedQuestions),
  2177. 'target_count' => $totalQuestions,
  2178. 'is_array' => is_array($selectedQuestions)
  2179. ]);
  2180. // 【新增】最终知识点分布统计
  2181. $finalKpDistribution = array_count_values(array_column($selectedQuestions, 'kp_code'));
  2182. Log::info('摸底测试最终知识点分布', [
  2183. 'final_total_count' => count($selectedQuestions),
  2184. 'target_count' => $totalQuestions,
  2185. 'final_kp_distribution' => $finalKpDistribution,
  2186. 'unique_kp_count' => count($finalKpDistribution),
  2187. 'success' => count($selectedQuestions) === $totalQuestions,
  2188. 'kp_coverage_rate' => count($finalKpDistribution) / max(count($preSortKpDistribution), 1) * 100
  2189. ]);
  2190. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2191. $finalQuestions = [];
  2192. $seenQuestionIds = [];
  2193. $duplicateCount = 0;
  2194. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2195. foreach ($selectedQuestions as $question) {
  2196. $qbId = $question['question_bank_id'] ?? $question['id'];
  2197. if (!in_array($qbId, $seenQuestionIds)) {
  2198. $seenQuestionIds[] = $qbId;
  2199. $finalQuestions[] = $question;
  2200. // 统计题型分布
  2201. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2202. $type = null;
  2203. if ($qid && isset($questionTypeCache[$qid])) {
  2204. $type = $questionTypeCache[$qid];
  2205. } else {
  2206. $type = $this->determineQuestionType($question);
  2207. if ($qid) {
  2208. $questionTypeCache[$qid] = $type;
  2209. }
  2210. }
  2211. if (isset($typeDistribution[$type])) {
  2212. $typeDistribution[$type]++;
  2213. }
  2214. } else {
  2215. $duplicateCount++;
  2216. Log::warning('发现重复题目(已自动移除)', [
  2217. 'question_id' => $qbId,
  2218. 'duplicate_count' => $duplicateCount
  2219. ]);
  2220. }
  2221. }
  2222. // 【重要】如果去重后数量不足,补充到目标数量
  2223. if (count($finalQuestions) < $totalQuestions) {
  2224. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2225. 'final_count' => count($finalQuestions),
  2226. 'target_count' => $totalQuestions,
  2227. 'need_more' => $totalQuestions - count($finalQuestions)
  2228. ]);
  2229. // 从原始题目中选择未选过的题目补充
  2230. $usedIds = array_column($finalQuestions, 'id');
  2231. $supplementCount = 0;
  2232. foreach ($selectedQuestions as $question) {
  2233. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2234. $qid = $question['id'] ?? null;
  2235. if ($qid && !in_array($qid, $usedIds)) {
  2236. $finalQuestions[] = $question;
  2237. $usedIds[] = $qid;
  2238. $supplementCount++;
  2239. }
  2240. }
  2241. Log::info('selectQuestionsByMastery: 补充完成', [
  2242. 'supplement_added' => $supplementCount,
  2243. 'final_count_after_supplement' => count($finalQuestions)
  2244. ]);
  2245. }
  2246. Log::info('最终排查完成', [
  2247. 'original_count' => count($selectedQuestions),
  2248. 'final_count' => count($finalQuestions),
  2249. 'duplicate_removed' => $duplicateCount,
  2250. 'final_type_distribution' => $typeDistribution,
  2251. 'target_count' => $totalQuestions
  2252. ]);
  2253. // 【重要】确保返回的题目数量正确
  2254. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2255. Log::info('selectQuestionsByMastery: 返回结果', [
  2256. 'return_count' => count($finalQuestions),
  2257. 'target_count' => $totalQuestions,
  2258. 'success' => count($finalQuestions) === $totalQuestions
  2259. ]);
  2260. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2261. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2262. return $finalQuestions;
  2263. }
  2264. /**
  2265. * 获取学生对特定知识点的掌握度
  2266. */
  2267. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2268. {
  2269. try {
  2270. $mastery = DB::table('student_mastery')
  2271. ->where('student_id', $studentId)
  2272. ->where('kp', $kpCode)
  2273. ->value('mastery');
  2274. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2275. } catch (\Exception $e) {
  2276. Log::error('Get Student Kp Mastery Error', [
  2277. 'student_id' => $studentId,
  2278. 'kp_code' => $kpCode,
  2279. 'error' => $e->getMessage()
  2280. ]);
  2281. return 0.5;
  2282. }
  2283. }
  2284. /**
  2285. * 根据题型和难度配比调整题目
  2286. */
  2287. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2288. {
  2289. Log::info('开始题型配比调整', [
  2290. 'input_questions' => count($questions),
  2291. 'target_count' => $targetCount,
  2292. 'type_ratio' => $typeRatio
  2293. ]);
  2294. // 缓存题目类型,避免重复计算
  2295. $questionTypeCache = [];
  2296. // 按题型分桶
  2297. $buckets = [
  2298. 'choice' => [],
  2299. 'fill' => [],
  2300. 'answer' => [],
  2301. ];
  2302. foreach ($questions as $q) {
  2303. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2304. if ($qid && isset($questionTypeCache[$qid])) {
  2305. $type = $questionTypeCache[$qid];
  2306. } else {
  2307. $type = $this->determineQuestionType($q);
  2308. if ($qid) {
  2309. $questionTypeCache[$qid] = $type;
  2310. }
  2311. }
  2312. if (!isset($buckets[$type])) {
  2313. $type = 'answer';
  2314. }
  2315. $buckets[$type][] = $q;
  2316. }
  2317. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2318. // 修复:不自动减少目标数量,确保达到用户要求
  2319. $availableCount = count($questions);
  2320. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2321. Log::info('题型配比调整前桶统计', [
  2322. 'target_count' => $targetCount,
  2323. 'available_count' => $availableCount,
  2324. 'targets' => $targets,
  2325. 'bucket_counts' => [
  2326. 'choice' => count($buckets['choice']),
  2327. 'fill' => count($buckets['fill']),
  2328. 'answer' => count($buckets['answer']),
  2329. ],
  2330. 'raw_ratio' => $typeRatio,
  2331. ]);
  2332. // 随机打乱桶
  2333. foreach ($buckets as $k => $v) {
  2334. if (!empty($v)) {
  2335. shuffle($v);
  2336. $buckets[$k] = $v;
  2337. }
  2338. }
  2339. $selected = [];
  2340. $selectedIds = [];
  2341. // 按目标数依次取题
  2342. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2343. $need = $targets[$typeKey] ?? 0;
  2344. if ($need <= 0 || empty($buckets[$typeKey])) {
  2345. continue;
  2346. }
  2347. $take = min($need, count($buckets[$typeKey]));
  2348. $slice = array_slice($buckets[$typeKey], 0, $take);
  2349. foreach ($slice as $q) {
  2350. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2351. if (isset($selectedIds[$id])) {
  2352. continue;
  2353. }
  2354. $selected[] = $q;
  2355. $selectedIds[$id] = true;
  2356. }
  2357. }
  2358. // 不足则从剩余题中补齐
  2359. if (count($selected) < $targetCount) {
  2360. $remaining = [];
  2361. foreach ($buckets as $v) {
  2362. foreach ($v as $q) {
  2363. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2364. if (!isset($selectedIds[$id])) {
  2365. $remaining[] = $q;
  2366. }
  2367. }
  2368. }
  2369. shuffle($remaining);
  2370. $needMore = $targetCount - count($selected);
  2371. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2372. }
  2373. // 截断至目标数
  2374. $selected = array_slice($selected, 0, $targetCount);
  2375. // 使用缓存统计题型分布
  2376. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2377. foreach ($selected as $q) {
  2378. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2379. if ($qid && isset($questionTypeCache[$qid])) {
  2380. $type = $questionTypeCache[$qid];
  2381. } else {
  2382. $type = $this->determineQuestionType($q);
  2383. }
  2384. if (isset($selectedCounts[$type])) {
  2385. $selectedCounts[$type]++;
  2386. }
  2387. }
  2388. Log::info('题型配比调整完成', [
  2389. 'target_count' => $targetCount,
  2390. 'targets' => $targets,
  2391. 'selected_counts' => $selectedCounts,
  2392. 'final_selected_count' => count($selected)
  2393. ]);
  2394. return $selected;
  2395. }
  2396. private function determineQuestionType(array $q): string
  2397. {
  2398. // 优先根据题目内容判断(而不是数据库字段)
  2399. $stem = $q['stem'] ?? $q['content'] ?? '';
  2400. // 处理 stem 可能是数组的情况
  2401. if (is_array($stem)) {
  2402. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2403. }
  2404. $tags = $q['tags'] ?? '';
  2405. // 处理 tags 可能是数组的情况
  2406. if (is_array($tags)) {
  2407. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2408. }
  2409. $skills = $q['skills'] ?? [];
  2410. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2411. if (is_string($stem)) {
  2412. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2413. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2414. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2415. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2416. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2417. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2418. // 至少有2个选项就认为是选择题(降低阈值)
  2419. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2420. if ($optionCount >= 2) {
  2421. return 'choice';
  2422. }
  2423. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2424. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2425. return 'choice';
  2426. }
  2427. }
  2428. // 2. 根据技能点判断
  2429. if (is_array($skills) && !empty($skills)) {
  2430. // 过滤非字符串元素,避免 implode 报错
  2431. $skillsFiltered = array_filter($skills, 'is_string');
  2432. if (!empty($skillsFiltered)) {
  2433. $skillsStr = implode(',', $skillsFiltered);
  2434. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2435. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2436. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2437. }
  2438. }
  2439. // 3. 根据题目已有类型字段判断(作为后备)
  2440. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2441. if (is_string($typeField)) {
  2442. $t = strtolower($typeField);
  2443. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2444. return 'choice';
  2445. }
  2446. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2447. return 'fill';
  2448. }
  2449. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2450. return 'answer';
  2451. }
  2452. }
  2453. // 4. 根据标签判断
  2454. if (is_string($tags)) {
  2455. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2456. return 'choice';
  2457. }
  2458. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2459. return 'fill';
  2460. }
  2461. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2462. return 'answer';
  2463. }
  2464. }
  2465. // 5. 根据options字段判断
  2466. if (!empty($q['options']) && is_array($q['options'])) {
  2467. return 'choice';
  2468. }
  2469. // 6. 填空题特征:连续下划线或明显的填空括号
  2470. if (is_string($stem)) {
  2471. // 检查填空题特征:连续下划线
  2472. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2473. return 'fill';
  2474. }
  2475. // 空括号填空
  2476. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2477. return 'fill';
  2478. }
  2479. }
  2480. // 7. 根据题干内容关键词判断
  2481. if (is_string($stem)) {
  2482. // 有证明、解答、计算、求证等关键词的是解答题
  2483. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2484. return 'answer';
  2485. }
  2486. }
  2487. // 默认是解答题(更安全的默认值)
  2488. return 'answer';
  2489. }
  2490. // 【移除】删除未使用的mapDifficultyLevel方法
  2491. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2492. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2493. {
  2494. $map = [
  2495. '选择题' => 'choice',
  2496. '填空题' => 'fill',
  2497. '解答题' => 'answer',
  2498. ];
  2499. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2500. foreach ($questionTypeRatio as $label => $ratio) {
  2501. $key = $map[$label] ?? null;
  2502. if (!$key) {
  2503. continue;
  2504. }
  2505. $cnt = (int) round($targetCount * ($ratio / 100));
  2506. if ($ratio > 0 && $cnt < 1) {
  2507. $cnt = 1;
  2508. }
  2509. $targets[$key] = $cnt;
  2510. }
  2511. $sum = array_sum($targets);
  2512. if ($sum === 0) {
  2513. $targets['answer'] = $targetCount;
  2514. return $targets;
  2515. }
  2516. while ($sum > $targetCount) {
  2517. arsort($targets);
  2518. foreach ($targets as $k => $v) {
  2519. if ($v > 1) {
  2520. $targets[$k]--;
  2521. $sum--;
  2522. break;
  2523. }
  2524. }
  2525. }
  2526. if ($sum < $targetCount) {
  2527. $ratioByKey = [
  2528. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2529. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2530. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  2531. ];
  2532. while ($sum < $targetCount) {
  2533. arsort($ratioByKey);
  2534. $k = array_key_first($ratioByKey);
  2535. $targets[$k]++;
  2536. $sum++;
  2537. }
  2538. }
  2539. return $targets;
  2540. }
  2541. /**
  2542. * 提交手动评分结果到 LearningAnalytics
  2543. *
  2544. * @param array $data 包含 student_id, paper_id, grades 的数组
  2545. * @return array
  2546. */
  2547. public function submitManualGrading(array $data): array
  2548. {
  2549. try {
  2550. $response = Http::timeout($this->timeout)
  2551. ->post($this->baseUrl . '/api/ocr/analyze', [
  2552. 'student_id' => $data['student_id'],
  2553. 'paper_id' => $data['paper_id'],
  2554. 'answers' => $data['grades'],
  2555. ]);
  2556. if ($response->successful()) {
  2557. Log::info('Manual grading submitted successfully', [
  2558. 'student_id' => $data['student_id'],
  2559. 'paper_id' => $data['paper_id'],
  2560. 'question_count' => count($data['grades'])
  2561. ]);
  2562. return $response->json();
  2563. }
  2564. Log::error('Submit Manual Grading Error', [
  2565. 'data' => $data,
  2566. 'status' => $response->status(),
  2567. 'response' => $response->body()
  2568. ]);
  2569. return [
  2570. 'error' => true,
  2571. 'message' => 'Failed to submit manual grading'
  2572. ];
  2573. } catch (\Exception $e) {
  2574. Log::error('Submit Manual Grading Exception', [
  2575. 'error' => $e->getMessage(),
  2576. 'data' => $data
  2577. ]);
  2578. return [
  2579. 'error' => true,
  2580. 'message' => $e->getMessage()
  2581. ];
  2582. }
  2583. }
  2584. /**
  2585. * 分析学生作答结果
  2586. *
  2587. * @param array $data 包含 paper_id, student_id, answers 等
  2588. * @return array
  2589. */
  2590. public function analyzeStudentAnswers(array $data): array
  2591. {
  2592. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  2593. 'student_id' => $data['student_id'] ?? null,
  2594. 'paper_id' => $data['paper_id'] ?? null,
  2595. ]);
  2596. return [
  2597. 'success' => false,
  2598. 'message' => 'analysis_api_disabled',
  2599. ];
  2600. }
  2601. /**
  2602. * 智能补充题目(当指定知识点的题目不足时)
  2603. *
  2604. * @param int $grade 年级
  2605. * @param array $existingKpCodes 已有的知识点代码(用于排除)
  2606. * @param int $needCount 需要补充的题目数量
  2607. * @param int $difficultyCategory 难度类别
  2608. * @param int|null $textbookId 教材ID(用于限制补充范围,避免超纲)
  2609. * @return array 补充的题目列表
  2610. */
  2611. private function getSupplementaryQuestionsForGrade(
  2612. int $grade,
  2613. array $existingKpCodes,
  2614. int $needCount,
  2615. int $difficultyCategory,
  2616. ?int $textbookId = null
  2617. ): array {
  2618. try {
  2619. Log::info('getSupplementaryQuestionsForGrade: 开始智能补充', [
  2620. 'grade' => $grade,
  2621. 'existing_kp_count' => count($existingKpCodes),
  2622. 'need_count' => $needCount,
  2623. 'difficulty_category' => $difficultyCategory,
  2624. 'textbook_id' => $textbookId,
  2625. 'note' => $textbookId ? '限制在指定教材范围内,避免超纲' : '使用整个年级范围'
  2626. ]);
  2627. // 查询同年级其他知识点的题目
  2628. $query = \App\Models\Question::query();
  2629. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  2630. if ($stageGrade !== null) {
  2631. $query->where('grade', $stageGrade);
  2632. Log::info('getSupplementaryQuestionsForGrade: 应用学段筛选', [
  2633. 'input_grade' => $grade,
  2634. 'stage_grade' => $stageGrade
  2635. ]);
  2636. }
  2637. // 排除已选知识点
  2638. if (!empty($existingKpCodes)) {
  2639. $query->whereNotIn('kp_code', $existingKpCodes);
  2640. }
  2641. // 【修复超纲问题】限制在指定教材范围内(通过教材关联)
  2642. // 如果有 textbook_id,只从该教材的知识点中补充,避免七年级上册学生拿到下册题目
  2643. $gradeKpCodes = $this->getGradeKnowledgePoints($grade, $textbookId);
  2644. if (!empty($gradeKpCodes)) {
  2645. $query->whereIn('kp_code', $gradeKpCodes);
  2646. Log::info('getSupplementaryQuestionsForGrade: 应用知识点范围限制', [
  2647. 'kp_codes_count' => count($gradeKpCodes),
  2648. 'textbook_id' => $textbookId
  2649. ]);
  2650. } else {
  2651. Log::warning('getSupplementaryQuestionsForGrade: 未找到年级知识点,跳过补充', [
  2652. 'grade' => $grade,
  2653. 'textbook_id' => $textbookId
  2654. ]);
  2655. return [];
  2656. }
  2657. // 筛选有解题思路的题目
  2658. $query->whereNotNull('solution')
  2659. ->where('solution', '!=', '')
  2660. ->where('solution', '!=', '[]');
  2661. // 【重要】移除题目分类限制,允许补充其他分类的题目
  2662. // $query->where('question_category', 1); // 移除这行
  2663. // 根据难度类别调整查询
  2664. $difficultyRanges = $this->getDifficultyRangesForCategory($difficultyCategory);
  2665. $query->where(function ($q) use ($difficultyRanges) {
  2666. foreach ($difficultyRanges as $range) {
  2667. $q->orWhereBetween('difficulty', [$range['min'], $range['max']]);
  2668. }
  2669. });
  2670. // 随机排序,增加多样性
  2671. $query->inRandomOrder()
  2672. ->limit($needCount * 2); // 多取一些,后续筛选
  2673. $supplementaryQuestions = $query->get();
  2674. Log::info('getSupplementaryQuestionsForGrade: 查询完成', [
  2675. 'found_count' => $supplementaryQuestions->count(),
  2676. 'need_count' => $needCount
  2677. ]);
  2678. // 格式化题目
  2679. $formatted = [];
  2680. foreach ($supplementaryQuestions as $question) {
  2681. // 优先使用题库原始题型
  2682. $stem = $question->stem ?? '';
  2683. $options = is_array($question->options) ? $question->options : (json_decode($question->options ?? '[]', true) ?: []);
  2684. $correctAnswer = $question->correct_answer ?? '';
  2685. $questionType = $question->question_type ?? 'answer';
  2686. $formatted[] = [
  2687. 'id' => $question->id,
  2688. 'question_bank_id' => $question->id,
  2689. 'question_type' => $questionType,
  2690. 'kp_code' => $question->kp_code,
  2691. 'difficulty' => $question->difficulty !== null ? (float) $question->difficulty : 0.5,
  2692. 'stem' => $stem,
  2693. 'options' => $options,
  2694. 'correct_answer' => $correctAnswer,
  2695. 'solution' => $question->solution,
  2696. 'score' => $question->score ?? 4,
  2697. 'estimated_time' => $question->estimated_time ?? 300,
  2698. 'metadata' => [
  2699. 'question_type_label' => $questionType === 'choice' ? '选择题' : ($questionType === 'fill' ? '填空题' : '解答题'),
  2700. 'difficulty_label' => $this->getDifficultyLabelFromObject($question->difficulty ?? 0.5),
  2701. 'is_supplementary' => true
  2702. ]
  2703. ];
  2704. }
  2705. // 随机选择需要的数量
  2706. shuffle($formatted);
  2707. $selected = array_slice($formatted, 0, $needCount);
  2708. Log::info('getSupplementaryQuestionsForGrade: 补充完成', [
  2709. 'supplementary_count' => count($selected),
  2710. 'kp_distribution' => array_count_values(array_column($selected, 'kp_code'))
  2711. ]);
  2712. return $selected;
  2713. } catch (\Exception $e) {
  2714. Log::error('getSupplementaryQuestionsForGrade: 补充失败', [
  2715. 'grade' => $grade,
  2716. 'need_count' => $needCount,
  2717. 'error' => $e->getMessage()
  2718. ]);
  2719. return [];
  2720. }
  2721. }
  2722. /**
  2723. * 获取指定年级的知识点列表
  2724. *
  2725. * @param int $grade 年级
  2726. * @param int|null $textbookId 教材ID(可选,用于限制在特定教材范围内,避免超纲)
  2727. * @return array 知识点代码列表
  2728. */
  2729. private function getGradeKnowledgePoints(int $grade, ?int $textbookId = null): array
  2730. {
  2731. try {
  2732. $query = DB::table('textbook_chapter_knowledge_relation as tckr')
  2733. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  2734. ->join('textbooks as t', 'tcn.textbook_id', '=', 't.id')
  2735. ->where('t.grade', $grade);
  2736. // 【修复超纲问题】如果有 textbook_id,严格限制在该教材范围内
  2737. // 避免七年级上册学生拿到七年级下册的知识点
  2738. if ($textbookId) {
  2739. $query->where('t.id', $textbookId);
  2740. Log::info('getGradeKnowledgePoints: 限制在指定教材范围内', [
  2741. 'grade' => $grade,
  2742. 'textbook_id' => $textbookId
  2743. ]);
  2744. }
  2745. $kpCodes = $query->distinct()
  2746. ->pluck('tckr.kp_code')
  2747. ->toArray();
  2748. Log::info('getGradeKnowledgePoints: 获取知识点完成', [
  2749. 'grade' => $grade,
  2750. 'textbook_id' => $textbookId,
  2751. 'kp_count' => count($kpCodes)
  2752. ]);
  2753. return array_filter($kpCodes);
  2754. } catch (\Exception $e) {
  2755. Log::error('getGradeKnowledgePoints: 查询失败', [
  2756. 'grade' => $grade,
  2757. 'textbook_id' => $textbookId,
  2758. 'error' => $e->getMessage()
  2759. ]);
  2760. return [];
  2761. }
  2762. }
  2763. /**
  2764. * 【新增】根据难度类别获取难度范围
  2765. */
  2766. private function getDifficultyRangesForCategory(int $difficultyCategory): array
  2767. {
  2768. return match($difficultyCategory) {
  2769. 1 => [
  2770. ['min' => 0.0, 'max' => 0.5], // 基础型:偏向低难度
  2771. ['min' => 0.5, 'max' => 1.0],
  2772. ],
  2773. 2 => [
  2774. ['min' => 0.0, 'max' => 0.5], // 进阶型:均衡分布
  2775. ['min' => 0.5, 'max' => 1.0],
  2776. ],
  2777. 3 => [
  2778. ['min' => 0.25, 'max' => 0.75], // 中等型:偏向中等难度
  2779. ['min' => 0.0, 'max' => 1.0],
  2780. ],
  2781. 4 => [
  2782. ['min' => 0.5, 'max' => 1.0], // 拔高型:偏向高难度
  2783. ['min' => 0.0, 'max' => 0.5],
  2784. ],
  2785. default => [
  2786. ['min' => 0.0, 'max' => 1.0],
  2787. ]
  2788. };
  2789. }
  2790. private function normalizeQuestionStageGrade(int $grade): ?int
  2791. {
  2792. if ($grade <= 0) {
  2793. return null;
  2794. }
  2795. // 年级转学段 todo:下一步需要视频小学
  2796. return $grade <= 9 ? 2 : 3;
  2797. }
  2798. /**
  2799. * 【新增】获取难度标签(重载版本)
  2800. */
  2801. private function getDifficultyLabelFromObject(?float $difficulty): string
  2802. {
  2803. if ($difficulty === null) return '未知';
  2804. if ($difficulty < 0.3) return '基础';
  2805. if ($difficulty < 0.7) return '中等';
  2806. return '拔高';
  2807. }
  2808. private function buildDifficultyDistributionStats(array $questions, int $difficultyCategory): array
  2809. {
  2810. if (empty($questions)) {
  2811. return [];
  2812. }
  2813. $service = app(DifficultyDistributionService::class);
  2814. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  2815. $total = max(1, count($questions));
  2816. return array_map(static function ($bucket) use ($total) {
  2817. $count = count($bucket);
  2818. return [
  2819. 'count' => $count,
  2820. 'ratio' => round(($count / $total) * 100, 2),
  2821. ];
  2822. }, $buckets);
  2823. }
  2824. private function buildDifficultyDistributionShortage(array $questions, int $difficultyCategory, int $totalQuestions): array
  2825. {
  2826. $service = app(DifficultyDistributionService::class);
  2827. $distribution = $service->calculateDistribution($difficultyCategory, $totalQuestions);
  2828. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  2829. $expected = [
  2830. 'primary_low' => 0,
  2831. 'primary_medium' => 0,
  2832. 'primary_high' => 0,
  2833. 'secondary' => 0,
  2834. 'other' => 0,
  2835. ];
  2836. foreach ($distribution as $level => $config) {
  2837. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  2838. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  2839. }
  2840. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  2841. $shortage = [];
  2842. foreach ($expected as $bucketKey => $count) {
  2843. $actualCount = $actual[$bucketKey] ?? 0;
  2844. $shortage[$bucketKey] = [
  2845. 'expected' => $count,
  2846. 'actual' => $actualCount,
  2847. 'short' => max(0, $count - $actualCount),
  2848. ];
  2849. }
  2850. return $shortage;
  2851. }
  2852. private function buildDistributionCandidates(array $allQuestions, array $selectedQuestions, int $difficultyCategory): array
  2853. {
  2854. if (empty($allQuestions)) {
  2855. return $selectedQuestions;
  2856. }
  2857. $service = app(DifficultyDistributionService::class);
  2858. $distribution = $service->calculateDistribution($difficultyCategory, max(1, count($selectedQuestions)));
  2859. $buckets = $service->groupQuestionsByDifficultyRange($allQuestions, $difficultyCategory);
  2860. $preferredBuckets = [];
  2861. foreach ($distribution as $level => $config) {
  2862. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  2863. $preferredBuckets[$bucketKey] = true;
  2864. }
  2865. $candidates = [];
  2866. foreach (array_keys($preferredBuckets) as $bucketKey) {
  2867. foreach ($buckets[$bucketKey] ?? [] as $q) {
  2868. $candidates[] = $q;
  2869. }
  2870. }
  2871. foreach ($selectedQuestions as $q) {
  2872. $candidates[] = $q;
  2873. }
  2874. $seen = [];
  2875. $unique = [];
  2876. foreach ($candidates as $q) {
  2877. $id = $q['id'] ?? null;
  2878. if (!$id || isset($seen[$id])) {
  2879. continue;
  2880. }
  2881. $seen[$id] = true;
  2882. $unique[] = $q;
  2883. }
  2884. return $unique;
  2885. }
  2886. }