LearningAnalyticsService.php 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704
  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. ->join('knowledge_points as kp', 'kp.kp_code', '=', 'skm.kp_code')
  964. ->where('skm.student_id', $studentId)
  965. ->where('skm.mastery_level', '<', 0.9) // 掌握度低于70%视为薄弱点
  966. ->whereNotNull('kp.parent_kp_code') // 排除根节点(如 M00/S000_000)
  967. ->orderBy('skm.mastery_level', 'asc')
  968. ->limit($limit)
  969. ->select([
  970. 'skm.kp_code',
  971. 'skm.mastery_level',
  972. 'skm.total_attempts',
  973. 'skm.correct_attempts',
  974. 'skm.incorrect_attempts',
  975. 'skm.confidence_level',
  976. 'skm.mastery_trend'
  977. ])
  978. ->get()
  979. ->toArray();
  980. // 如果student_knowledge_mastery表没有数据,尝试从student_mastery表读取
  981. if (empty($weaknesses)) {
  982. Log::info('student_knowledge_mastery表无数据,尝试从student_mastery表读取', [
  983. 'student_id' => $studentId
  984. ]);
  985. $weaknesses = DB::table('student_mastery as sm')
  986. ->leftJoin('knowledge_points as kp', 'sm.kp', '=', 'kp.kp_code')
  987. ->where('sm.student_id', $studentId)
  988. ->where('sm.mastery', '<', 0.7) // 掌握度低于70%视为薄弱点
  989. ->whereNotNull('kp.parent_kp_code') // 排除根节点(如 M00/S000_000)
  990. ->orderBy('sm.mastery', 'asc')
  991. ->limit($limit)
  992. ->select([
  993. 'sm.kp as kp_code',
  994. 'kp.name as kp_name',
  995. 'sm.mastery',
  996. 'sm.attempts',
  997. 'sm.correct'
  998. ])
  999. ->get()
  1000. ->toArray();
  1001. // 转换为统一格式
  1002. return array_map(function ($item) {
  1003. $mastery = (float) ($item->mastery ?? 0);
  1004. $attempts = (int) ($item->attempts ?? 0);
  1005. $correct = (int) ($item->correct ?? 0);
  1006. return [
  1007. 'kp_code' => $item->kp_code,
  1008. 'kp_name' => $item->kp_name ?? $item->kp_code,
  1009. 'mastery' => $mastery,
  1010. 'stability' => 0.5, // 默认稳定性
  1011. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1012. 'practice_count' => $attempts,
  1013. 'success_rate' => $attempts > 0 ? ($correct / $attempts) : 0,
  1014. 'priority' => $mastery < 0.3 ? '高' : ($mastery < 0.5 ? '中' : '低'),
  1015. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)) // 掌握度越低,建议题目越多
  1016. ];
  1017. }, $weaknesses);
  1018. }
  1019. // 转换student_knowledge_mastery表的数据格式
  1020. return array_map(function ($item) {
  1021. $mastery = (float) ($item->mastery_level ?? 0);
  1022. $totalAttempts = (int) ($item->total_attempts ?? 0);
  1023. $correctAttempts = (int) ($item->correct_attempts ?? 0);
  1024. $incorrectAttempts = (int) ($item->incorrect_attempts ?? 0);
  1025. $confidence = (float) ($item->confidence_level ?? 0.5);
  1026. $trend = $item->mastery_trend ?? 'stable';
  1027. // 计算成功率
  1028. $successRate = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : 0;
  1029. // 确定优先级
  1030. $priority = '中';
  1031. if ($mastery < 0.3) {
  1032. $priority = '高';
  1033. } elseif ($mastery < 0.5) {
  1034. $priority = '中';
  1035. } else {
  1036. $priority = '低';
  1037. }
  1038. return [
  1039. 'kp_code' => $item->kp_code,
  1040. 'kp_name' => $item->kp_code, // 如果没有中文名,使用代码作为名称
  1041. 'mastery' => $mastery,
  1042. 'stability' => $confidence,
  1043. 'weakness_level' => 1.0 - $mastery, // 薄弱程度
  1044. 'practice_count' => $totalAttempts,
  1045. 'success_rate' => $successRate,
  1046. 'priority' => $priority,
  1047. 'suggested_questions' => max(5, (int)((0.7 - $mastery) * 20)), // 掌握度越低,建议题目越多
  1048. 'trend' => $trend,
  1049. 'correct_attempts' => $correctAttempts,
  1050. 'incorrect_attempts' => $incorrectAttempts
  1051. ];
  1052. }, $weaknesses);
  1053. } catch (\Exception $e) {
  1054. Log::error('Get Student Weaknesses From MySQL Error', [
  1055. 'student_id' => $studentId,
  1056. 'error' => $e->getMessage(),
  1057. 'trace' => $e->getTraceAsString()
  1058. ]);
  1059. return [];
  1060. }
  1061. }
  1062. /**
  1063. * 智能出卷:根据学生掌握度智能选择题目
  1064. */
  1065. public function generateIntelligentExam(array $params): array
  1066. {
  1067. $startTime = microtime(true);
  1068. try {
  1069. // 应用组卷类型策略
  1070. $assembleType = (int) ($params['assemble_type'] ?? 4); // 默认为通用类型(4)
  1071. $examTypeLegacy = $params['exam_type'] ?? 'general'; // 兼容旧版参数
  1072. Log::debug('LearningAnalyticsService: 检查组卷策略', [
  1073. 'assemble_type' => $assembleType
  1074. ]);
  1075. // 如果有 assemble_type 参数,优先使用新的参数系统
  1076. if (isset($params['assemble_type'])) {
  1077. try {
  1078. // 确保QuestionExpansionService和QuestionLocalService可用
  1079. $questionExpansionService = $this->questionExpansionService ?? app(QuestionExpansionService::class);
  1080. $questionLocalService = app(QuestionLocalService::class);
  1081. Log::debug('LearningAnalyticsService: 从容器获取服务实例');
  1082. $strategy = new ExamTypeStrategy($questionExpansionService, $questionLocalService);
  1083. $params = $strategy->buildParams($params, $assembleType);
  1084. Log::debug('LearningAnalyticsService: 已应用组卷策略', [
  1085. 'assemble_type' => $assembleType
  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::debug('LearningAnalyticsService: 已应用组卷策略(兼容模式)', [
  1103. 'exam_type' => $examTypeLegacy
  1104. ]);
  1105. } catch (Exception $e) {
  1106. Log::warning('LearningAnalyticsService: 组卷策略应用失败,使用默认策略', [
  1107. 'exam_type' => $examTypeLegacy,
  1108. 'error' => $e->getMessage(),
  1109. 'trace' => $e->getTraceAsString()
  1110. ]);
  1111. }
  1112. } else {
  1113. Log::info('LearningAnalyticsService: 跳过组卷策略', [
  1114. 'reason' => '通用类型不需要特殊策略'
  1115. ]);
  1116. }
  1117. $studentId = $params['student_id'] ?? null;
  1118. $grade = $params['grade'] ?? null; // 用户选择的年级
  1119. $totalQuestions = $params['total_questions'] ?? (int) config('question_bank.default_total_questions');
  1120. // 【修复】参数映射:支持 kp_codes 和 kp_code_list 两种参数名
  1121. $kpCodes = $params['kp_codes'] ?? $params['kp_code_list'] ?? [];
  1122. if (!is_array($kpCodes)) {
  1123. $kpCodes = [];
  1124. }
  1125. $skills = $params['skills'] ?? [];
  1126. $questionTypeRatio = $params['question_type_ratio'] ?? [
  1127. '选择题' => 40,
  1128. '填空题' => 40,
  1129. '解答题' => 20,
  1130. ];
  1131. // 新增:题目分类筛选
  1132. $questionCategory = $params['question_category'] ?? null;
  1133. // 注意: difficulty_ratio 参数已废弃,使用 difficulty_category 控制难度分布
  1134. $difficultyLevels = $params['difficulty_levels'] ?? [];
  1135. // 如果用户没有选择任何难度,difficultyLevels 为空数组,表示随机难度
  1136. Log::info("generateIntelligentExam 开始", [
  1137. 'student_id' => $studentId,
  1138. 'total_questions' => $totalQuestions,
  1139. 'assemble_type' => $assembleType,
  1140. 'kp_count' => count($kpCodes),
  1141. ]);
  1142. // 1. 如果指定了学生,获取学生的薄弱点
  1143. $weaknessFilter = [];
  1144. if ($studentId) {
  1145. Log::debug("获取学生薄弱点", ['student_id' => $studentId]);
  1146. $weaknesses = $this->getStudentWeaknesses($studentId, 20);
  1147. Log::debug("薄弱点数量", ['count' => count($weaknesses)]);
  1148. $weaknessFilter = array_column($weaknesses, 'kp_code');
  1149. // 【修复】教材出卷(assemble_type=3)不使用薄弱点,严格按章节获取知识点
  1150. if ($assembleType == 3) {
  1151. Log::debug("LearningAnalyticsService: 教材出卷不使用薄弱点");
  1152. // 教材组卷不使用薄弱点
  1153. } else {
  1154. // 如果用户没有指定知识点,使用学生的薄弱点(非教材组卷)
  1155. if (empty($kpCodes)) {
  1156. $kpCodes = $weaknessFilter;
  1157. Log::info("用户未选择知识点,使用薄弱点作为kp_codes", [
  1158. '最终kp_codes' => $kpCodes,
  1159. ]);
  1160. }
  1161. }
  1162. }
  1163. Log::debug("准备调用 getQuestionsFromBank", [
  1164. 'kp_codes_count' => count($kpCodes),
  1165. 'skills_count' => count($skills),
  1166. ]);
  1167. // 2. 优先使用学生错题(如果存在)
  1168. $mistakeQuestionIds = $params['mistake_question_ids'] ?? [];
  1169. $priorityQuestions = [];
  1170. $maxQuestions = 50; // 错题最大题目数限制
  1171. $poolLimit = 0; // 题库池不设上限,0 表示不限制
  1172. if (!empty($mistakeQuestionIds)) {
  1173. Log::info('LearningAnalyticsService: 优先获取学生错题', [
  1174. 'mistake_question_ids' => $mistakeQuestionIds,
  1175. 'count' => count($mistakeQuestionIds),
  1176. 'max_limit' => $maxQuestions
  1177. ]);
  1178. // 如果错题超过最大值,截取到最大值
  1179. $truncatedMistakeIds = $mistakeQuestionIds;
  1180. if (count($mistakeQuestionIds) > $maxQuestions) {
  1181. Log::warning('LearningAnalyticsService: 错题数量超过最大值限制,已截取', [
  1182. 'mistake_count' => count($mistakeQuestionIds),
  1183. 'max_limit' => $maxQuestions,
  1184. 'truncated_count' => $maxQuestions
  1185. ]);
  1186. $truncatedMistakeIds = array_slice($mistakeQuestionIds, 0, $maxQuestions);
  1187. }
  1188. // 获取学生错题的详细信息(错题获取不需要智能补充,不传入 grade/textbook_id)
  1189. $priorityQuestions = $this->getQuestionsFromBank([], [], $studentId, $questionTypeRatio, $maxQuestions, $truncatedMistakeIds, [], null, null, null, null, 1);
  1190. Log::info('LearningAnalyticsService: 错题获取完成', [
  1191. 'priority_questions_count' => count($priorityQuestions),
  1192. 'expected_count' => count($truncatedMistakeIds)
  1193. ]);
  1194. // 如果获取的错题数量少于预期,记录警告
  1195. if (count($priorityQuestions) < count($truncatedMistakeIds)) {
  1196. Log::warning('LearningAnalyticsService: 错题获取不完整', [
  1197. 'expected' => count($truncatedMistakeIds),
  1198. 'actual' => count($priorityQuestions),
  1199. 'missing_ids' => array_diff($truncatedMistakeIds, array_column($priorityQuestions, 'id'))
  1200. ]);
  1201. }
  1202. }
  1203. // 3. 处理错题本逻辑
  1204. $allQuestions = $priorityQuestions;
  1205. $isMistakeBook = ($assembleType === 5); // 错题本类型
  1206. $hasMistakePriority = !empty($priorityQuestions);
  1207. $strictMistakeBook = $isMistakeBook && $hasMistakePriority;
  1208. // 【修改】错题本类型严格按错题组卷,不补充题目
  1209. if ($isMistakeBook) {
  1210. $mistakeKpSource = (bool) ($params['mistake_kp_source'] ?? false);
  1211. // 记录错题本组卷信息
  1212. Log::info('LearningAnalyticsService: 错题本严格按错题组卷,不补充题目', [
  1213. 'mistake_count' => count($priorityQuestions),
  1214. 'assemble_type' => $assembleType,
  1215. 'mistake_kp_source' => $mistakeKpSource,
  1216. 'action' => '只使用学生错题,不从原卷子补充'
  1217. ]);
  1218. // 如果完全没有错题,回退到知识点/题库组卷
  1219. if (!$hasMistakePriority && !$mistakeKpSource) {
  1220. Log::warning('LearningAnalyticsService: 错题本无错题', [
  1221. 'student_id' => $studentId,
  1222. 'paper_ids' => $params['paper_ids'] ?? []
  1223. ]);
  1224. Log::info('LearningAnalyticsService: 错题本无错题,允许补充题目', [
  1225. 'assemble_type' => $assembleType,
  1226. 'action' => 'fallback_to_kp_or_bank'
  1227. ]);
  1228. } elseif (!$hasMistakePriority && $mistakeKpSource) {
  1229. Log::info('LearningAnalyticsService: 错题本使用错题知识点组卷', [
  1230. 'assemble_type' => $assembleType,
  1231. 'action' => 'use_mistake_kp_codes'
  1232. ]);
  1233. }
  1234. }
  1235. if (!$strictMistakeBook && count($priorityQuestions) < $totalQuestions) {
  1236. try {
  1237. // 【优化】教材出卷(assemble_type=3)保留知识点筛选,但额外使用章节筛选
  1238. if ($assembleType == 3) {
  1239. Log::debug('LearningAnalyticsService: 教材出卷模式,保留知识点筛选', [
  1240. 'kp_codes_count' => count($kpCodes),
  1241. ]);
  1242. }
  1243. // 【优化】获取textbook_catalog_node_ids参数(教材组卷时使用)
  1244. $textbookCatalogNodeIds = $params['textbook_catalog_node_ids'] ?? null;
  1245. // 【修复超纲问题】获取 textbook_id 和 difficulty_category,用于智能补充时限制范围
  1246. $textbookId = isset($params['textbook_id']) ? (int) $params['textbook_id'] : null;
  1247. $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
  1248. Log::debug('开始调用 getQuestionsFromBank 补充题目', [
  1249. 'need_more' => $totalQuestions - count($priorityQuestions),
  1250. 'assemble_type' => $assembleType,
  1251. 'grade' => $grade,
  1252. ]);
  1253. // 【修复超纲问题】传入 grade 和 textbook_id,用于智能补充时限制范围
  1254. // 【修复】传入实际需要数量,否则 totalNeeded=0 会导致智能补充不触发
  1255. $excludeQuestionIds = $params['exclude_question_ids'] ?? [];
  1256. $needCount = $totalQuestions - count($priorityQuestions);
  1257. $additionalQuestions = $this->getQuestionsFromBank(
  1258. $kpCodes,
  1259. $skills,
  1260. $studentId,
  1261. $questionTypeRatio,
  1262. $needCount,
  1263. [],
  1264. $excludeQuestionIds,
  1265. $questionCategory,
  1266. $textbookCatalogNodeIds,
  1267. $grade ? (int) $grade : null, // 年级
  1268. $textbookId, // 教材ID(避免超纲)
  1269. $difficultyCategory // 难度类别
  1270. );
  1271. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($priorityQuestions, $additionalQuestions));
  1272. // assemble_type=2:本源 KP 合并后仍不足,用父树补题 KP 拉题(与 getQuestionsFromBank 主条件一致,走专用列表,不混入本源查询)
  1273. if (
  1274. $assembleType === 2
  1275. && count($allQuestions) < $totalQuestions
  1276. && ! empty($params['kp_supplement_subtree_codes'] ?? [])
  1277. && $grade !== null
  1278. ) {
  1279. $excludeForSupp = array_values(array_unique(array_filter(array_merge(
  1280. $excludeQuestionIds,
  1281. array_column($allQuestions, 'id')
  1282. ))));
  1283. $supp = $this->fetchQuestionsForKpAssembleSupplement(
  1284. $params['kp_supplement_subtree_codes'],
  1285. $excludeForSupp,
  1286. (int) $grade,
  1287. $skills,
  1288. $questionCategory,
  1289. $textbookCatalogNodeIds
  1290. );
  1291. $before = count($allQuestions);
  1292. $allQuestions = $this->dedupeQuestionsByBankId(array_merge($allQuestions, $supp));
  1293. Log::info('LearningAnalyticsService: 知识点组卷父树补题(本源池不足后)', [
  1294. 'source_merged_count' => $before,
  1295. 'supplement_fetched' => count($supp),
  1296. 'after_merge_count' => count($allQuestions),
  1297. 'target_total' => $totalQuestions,
  1298. 'supplement_kp_sample' => array_slice($params['kp_supplement_subtree_codes'], 0, 12),
  1299. ]);
  1300. }
  1301. Log::info('getQuestionsFromBank 完成', [
  1302. 'questions_count' => count($allQuestions),
  1303. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1304. ]);
  1305. } catch (\Exception $e) {
  1306. Log::error('getQuestionsFromBank 调用失败', [
  1307. 'error' => $e->getMessage(),
  1308. 'trace' => $e->getTraceAsString()
  1309. ]);
  1310. throw $e;
  1311. }
  1312. } elseif ($strictMistakeBook) {
  1313. // 错题本类型:不补充题目,只使用错题
  1314. Log::info('错题本类型:不补充题目,只使用错题', [
  1315. 'assemble_type' => $assembleType,
  1316. 'mistake_questions_count' => count($priorityQuestions),
  1317. 'total_questions_requested' => $totalQuestions
  1318. ]);
  1319. }
  1320. if (empty($allQuestions)) {
  1321. // 如果指定了知识点但题库为空,给出明确提示
  1322. if (!empty($kpCodes)) {
  1323. $message = '所选知识点 [' . implode(', ', $kpCodes) . '] 在题库中暂无可用题目。您可以:1) 选择其他知识点,2) 点击"生成练习题"按钮先补充题库,或 3) 取消知识点选择让系统随机选题。';
  1324. } else {
  1325. // 没有选择知识点时,从所有题目中选择
  1326. // 如果仍然没有题目,说明题库为空,提示补充题库
  1327. $message = '题库为空,请先添加题目到题库。您可以点击"生成练习题"按钮或手动上传题目。';
  1328. }
  1329. Log::warning('智能出卷失败 - 未找到题目', [
  1330. 'student_id' => $studentId,
  1331. 'selected_kp_codes' => $kpCodes,
  1332. 'kp_codes_count' => count($kpCodes),
  1333. 'message' => $message,
  1334. 'hint' => '如果选择了知识点但题库为空,请检查知识点代码是否正确,或尝试取消知识点选择'
  1335. ]);
  1336. return [
  1337. 'success' => false,
  1338. 'message' => $message,
  1339. 'questions' => []
  1340. ];
  1341. }
  1342. // 3. 根据掌握度对题目进行筛选和排序(含追练:题量与 total_questions / default_total_questions 一致,不再按 50 拉满)
  1343. $targetQuestionCount = min(count($allQuestions), $totalQuestions);
  1344. $startTime = microtime(true);
  1345. $selectedQuestions = $this->selectQuestionsByMastery(
  1346. $allQuestions,
  1347. $studentId,
  1348. $targetQuestionCount,
  1349. $questionTypeRatio,
  1350. $difficultyLevels,
  1351. $weaknessFilter,
  1352. $assembleType // 新增assembleType参数
  1353. );
  1354. $selectTime = (microtime(true) - $startTime) * 1000;
  1355. Log::debug('题目筛选结果', [
  1356. 'input_count' => count($allQuestions),
  1357. 'selected_count' => count($selectedQuestions),
  1358. 'target_count' => $targetQuestionCount,
  1359. 'select_time_ms' => round($selectTime, 2)
  1360. ]);
  1361. if (empty($selectedQuestions)) {
  1362. return [
  1363. 'success' => false,
  1364. 'message' => '题目筛选失败',
  1365. 'questions' => []
  1366. ];
  1367. }
  1368. // 【恢复】简化难度分布检查
  1369. $difficultyCategory = $params['difficulty_category'] ?? 1;
  1370. $enableDistribution = $params['enable_difficulty_distribution'] ?? false;
  1371. $isExcludedType = false; // 统一允许应用难度分布(错题本类型也允许)
  1372. if ($enableDistribution && !$isExcludedType) {
  1373. try {
  1374. $selectedQuestions = $this->applyTypeAwareDifficultyDistribution(
  1375. $allQuestions,
  1376. $selectedQuestions,
  1377. $totalQuestions,
  1378. (int) $difficultyCategory,
  1379. $questionTypeRatio
  1380. );
  1381. Log::debug('LearningAnalyticsService: 题型感知难度分布完成', [
  1382. 'after_count' => count($selectedQuestions),
  1383. 'type_breakdown' => $this->countByType($selectedQuestions),
  1384. ]);
  1385. } catch (\Exception $e) {
  1386. Log::warning('LearningAnalyticsService: 题型感知难度分布失败,继续使用原结果', [
  1387. 'error' => $e->getMessage(),
  1388. ]);
  1389. }
  1390. }
  1391. return [
  1392. 'success' => true,
  1393. 'message' => '智能出卷成功',
  1394. 'questions' => $selectedQuestions,
  1395. // 【新增】传递章节摸底和智能组卷的关键字段
  1396. 'diagnostic_chapter_id' => $params['diagnostic_chapter_id'] ?? null,
  1397. 'explanation_kp_codes' => $params['explanation_kp_codes'] ?? null,
  1398. 'assemble_type' => $params['assembleType'] ?? null, // 策略可能修改assembleType(如章节智能→章节摸底)
  1399. 'stats' => [
  1400. 'total_selected' => count($selectedQuestions),
  1401. 'source_questions' => count($allQuestions),
  1402. 'weakness_targeted' => $studentId && !empty($weaknessFilter) ? count(array_filter($selectedQuestions, function($q) use ($weaknessFilter) {
  1403. return in_array($q['kp_code'] ?? '', $weaknessFilter);
  1404. })) : 0,
  1405. 'difficulty_distribution_applied' => $enableDistribution && !$isExcludedType,
  1406. 'difficulty_category' => $difficultyCategory,
  1407. 'final_distribution' => $this->buildDifficultyDistributionStats($selectedQuestions, (int) $difficultyCategory),
  1408. 'final_distribution_shortage' => $this->buildDifficultyDistributionShortage(
  1409. $selectedQuestions,
  1410. (int) $difficultyCategory,
  1411. (int) $totalQuestions
  1412. ),
  1413. // 【新增】章节知识点数量统计(教材组卷时)
  1414. 'chapter_knowledge_point_stats' => $params['chapter_knowledge_point_stats'] ?? null,
  1415. 'textbook_catalog_node_ids' => $params['textbook_catalog_node_ids'] ?? null
  1416. ]
  1417. ];
  1418. } catch (\Exception $e) {
  1419. Log::error('Generate Intelligent Exam Error', [
  1420. 'error' => $e->getMessage(),
  1421. 'trace' => $e->getTraceAsString()
  1422. ]);
  1423. return [
  1424. 'success' => false,
  1425. 'message' => '智能出卷异常: ' . $e->getMessage(),
  1426. 'questions' => []
  1427. ];
  1428. }
  1429. }
  1430. /**
  1431. * @param array<int, array<string, mixed>> $questions
  1432. * @return array<int, array<string, mixed>>
  1433. */
  1434. private function dedupeQuestionsByBankId(array $questions): array
  1435. {
  1436. $seen = [];
  1437. $out = [];
  1438. foreach ($questions as $q) {
  1439. $id = $q['id'] ?? null;
  1440. if ($id === null || $id === '') {
  1441. continue;
  1442. }
  1443. $k = (string) $id;
  1444. if (isset($seen[$k])) {
  1445. continue;
  1446. }
  1447. $seen[$k] = true;
  1448. $out[] = $q;
  1449. }
  1450. return $out;
  1451. }
  1452. /**
  1453. * 知识点组卷补题:仅按补充 KP 列表查询,筛选条件与 getQuestionsFromBank 主查询一致(不调用教材/已学那条智能补题)。
  1454. *
  1455. * @param array<string> $kpCodes
  1456. * @param array<int|string> $excludeQuestionIds
  1457. * @return array<int, array<string, mixed>>
  1458. */
  1459. private function fetchQuestionsForKpAssembleSupplement(
  1460. array $kpCodes,
  1461. array $excludeQuestionIds,
  1462. int $grade,
  1463. array $skills = [],
  1464. ?int $questionCategory = null,
  1465. ?array $textbookCatalogNodeIds = null
  1466. ): array {
  1467. $kpCodes = array_values(array_unique(array_filter($kpCodes)));
  1468. if ($kpCodes === []) {
  1469. return [];
  1470. }
  1471. $query = \App\Models\Question::query()
  1472. ->where('audit_status', 0)
  1473. ->whereIn('kp_code', $kpCodes);
  1474. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  1475. if ($stageGrade !== null) {
  1476. $query->where('grade', $stageGrade);
  1477. }
  1478. if (! empty($skills)) {
  1479. $query->where(function ($q) use ($skills) {
  1480. foreach ($skills as $skill) {
  1481. $q->orWhere('tags', 'like', '%'.$skill.'%');
  1482. }
  1483. });
  1484. }
  1485. if (! empty($excludeQuestionIds)) {
  1486. $query->whereNotIn('id', $excludeQuestionIds);
  1487. }
  1488. if ($questionCategory !== null) {
  1489. $query->where('question_category', $questionCategory);
  1490. }
  1491. $query->whereNotNull('solution')
  1492. ->where('solution', '!=', '')
  1493. ->where('solution', '!=', '[]');
  1494. if (! empty($textbookCatalogNodeIds)) {
  1495. $query->whereIn('textbook_catalog_nodes_id', $textbookCatalogNodeIds);
  1496. }
  1497. return $query->inRandomOrder()->get()->map(function ($q) {
  1498. return [
  1499. 'id' => $q->id,
  1500. 'question_code' => $q->question_code,
  1501. 'kp_code' => $q->kp_code,
  1502. 'question_type' => $q->question_type,
  1503. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1504. 'stem' => $q->stem,
  1505. 'solution' => $q->solution,
  1506. 'metadata' => [
  1507. 'has_solution' => true,
  1508. 'is_choice' => $q->question_type === 'choice',
  1509. 'is_fill' => $q->question_type === 'fill',
  1510. 'is_answer' => $q->question_type === 'answer',
  1511. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1512. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type),
  1513. ],
  1514. ];
  1515. })->toArray();
  1516. }
  1517. /**
  1518. * 从题库获取题目
  1519. *
  1520. * @param array $kpCodes 知识点代码列表
  1521. * @param array $skills 技能标签列表
  1522. * @param string|null $studentId 学生ID
  1523. * @param array $questionTypeRatio 题型比例
  1524. * @param int $totalNeeded 需要的题目数量
  1525. * @param array $priorityQuestionIds 优先获取的题目ID(错题)
  1526. * @param array $excludeQuestionIds 排除的题目ID
  1527. * @param int|null $questionCategory 题目分类
  1528. * @param array|null $textbookCatalogNodeIds 教材章节节点ID
  1529. * @param int|null $grade 年级(用于智能补充时限制范围)
  1530. * @param int|null $textbookId 教材ID(用于智能补充时限制范围,避免超纲)
  1531. * @param int $difficultyCategory 难度类别(用于智能补充)
  1532. * @return array 题目列表
  1533. */
  1534. 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
  1535. {
  1536. $startTime = microtime(true);
  1537. try {
  1538. // 错题回顾:优先获取指定的学生错题
  1539. if (!empty($priorityQuestionIds)) {
  1540. Log::info('getQuestionsFromBank: 优先获取学生错题', [
  1541. 'priority_count' => count($priorityQuestionIds),
  1542. 'priority_ids' => $priorityQuestionIds
  1543. ]);
  1544. $priorityQuestions = $this->getLocalQuestionsByIds($priorityQuestionIds);
  1545. if (!empty($priorityQuestions)) {
  1546. Log::info('getQuestionsFromBank: 优先错题获取成功', [
  1547. 'count' => count($priorityQuestions)
  1548. ]);
  1549. return $priorityQuestions;
  1550. } else {
  1551. Log::warning('getQuestionsFromBank: 优先错题获取失败,返回空数组让上层处理');
  1552. // 错题本类型获取不到错题时,返回空数组,不回退到题库随机选题
  1553. return [];
  1554. }
  1555. }
  1556. $query = \App\Models\Question::query();
  1557. // 【新增】只获取审核通过的题目(audit_status = 0 表示合格)
  1558. $query->where('audit_status', 0);
  1559. // 按知识点筛选
  1560. if (!empty($kpCodes)) {
  1561. $query->whereIn('kp_code', $kpCodes);
  1562. }
  1563. // 按学段筛选(题库 grade: 2=初中, 3=高中)
  1564. if ($grade !== null) {
  1565. $stageGrade = $this->normalizeQuestionStageGrade((int) $grade);
  1566. if ($stageGrade !== null) {
  1567. $query->where('grade', $stageGrade);
  1568. }
  1569. }
  1570. // 按技能筛选(这里使用 tags 字段模拟技能筛选)
  1571. if (!empty($skills)) {
  1572. $query->where(function ($q) use ($skills) {
  1573. foreach ($skills as $skill) {
  1574. $q->orWhere('tags', 'like', "%{$skill}%");
  1575. }
  1576. });
  1577. }
  1578. // 排除学生已做过的题目
  1579. if (!empty($excludeQuestionIds)) {
  1580. $query->whereNotIn('id', $excludeQuestionIds);
  1581. }
  1582. // 按题目分类筛选(如果指定了 question_category)
  1583. if ($questionCategory !== null) {
  1584. $query->where('question_category', $questionCategory);
  1585. }
  1586. // 筛选有解题思路的题目
  1587. $query->whereNotNull('solution')
  1588. ->where('solution', '!=', '')
  1589. ->where('solution', '!=', '[]');
  1590. // 注意: 难度筛选由 QuestionLocalService 的难度分布系统处理
  1591. // 不在这里进行难度筛选,让 QuestionLocalService 做精确的难度分布
  1592. // 【重要】移除数量限制,获取所有符合条件的题目
  1593. // 不使用limit()限制查询结果,让后续处理逻辑决定最终数量
  1594. $query->inRandomOrder();
  1595. $questions = $query->get();
  1596. Log::info('getQuestionsFromBank: 查询完成', [
  1597. 'raw_count' => $questions->count(),
  1598. 'total_needed' => $totalNeeded,
  1599. 'exclude_count' => count($excludeQuestionIds),
  1600. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1601. ]);
  1602. // 转换为标准格式
  1603. $formattedQuestions = $questions->map(function ($q) {
  1604. return [
  1605. 'id' => $q->id,
  1606. 'question_code' => $q->question_code,
  1607. 'kp_code' => $q->kp_code,
  1608. 'question_type' => $q->question_type,
  1609. 'difficulty' => $q->difficulty !== null ? (float) $q->difficulty : 0.5,
  1610. 'stem' => $q->stem,
  1611. 'solution' => $q->solution,
  1612. 'metadata' => [
  1613. 'has_solution' => true,
  1614. 'is_choice' => $q->question_type === 'choice',
  1615. 'is_fill' => $q->question_type === 'fill',
  1616. 'is_answer' => $q->question_type === 'answer',
  1617. 'difficulty_label' => $this->getDifficultyLabel($q->difficulty ?? 0.5),
  1618. 'question_type_label' => $this->getQuestionTypeLabel($q->question_type)
  1619. ]
  1620. ];
  1621. })->toArray();
  1622. // 【重要】返回所有符合条件的题目,不限制数量
  1623. // 让上层调用者根据需要选择题目数量
  1624. $selectedQuestions = $formattedQuestions;
  1625. // 【修复】重新启用智能补充功能,增加 textbook_id 限制避免超纲
  1626. if ($totalNeeded > 0 && count($selectedQuestions) < $totalNeeded && $grade !== null) {
  1627. $deficit = $totalNeeded - count($selectedQuestions);
  1628. Log::warning('getQuestionsFromBank: 指定知识点题目不足,尝试智能补充', [
  1629. 'deficit' => $deficit,
  1630. 'available_count' => count($selectedQuestions),
  1631. 'grade' => $grade,
  1632. 'textbook_id' => $textbookId,
  1633. 'student_id' => $studentId ? '(有)' : '(无)',
  1634. 'strategy' => $textbookId ? '从同教材前章节补充' : ($studentId ? '从学生已学知识点补充' : '无教材且无学生ID,不补充')
  1635. ]);
  1636. // 【修复超纲问题】补充策略:只从「学过的」内容补充
  1637. // - 有 textbook_id:从同教材的前章节补充
  1638. // - 无 textbook_id:从学生做过的题目对应的知识点补充,避免未学内容
  1639. $supplementaryQuestions = $this->getSupplementaryQuestionsForGrade(
  1640. $grade,
  1641. array_column($selectedQuestions, 'kp_code'),
  1642. $deficit,
  1643. $difficultyCategory,
  1644. $textbookId,
  1645. $excludeQuestionIds,
  1646. $textbookCatalogNodeIds ?? null,
  1647. $studentId
  1648. );
  1649. if (!empty($supplementaryQuestions)) {
  1650. $selectedQuestions = array_merge($selectedQuestions, $supplementaryQuestions);
  1651. Log::info('getQuestionsFromBank: 智能补充完成', [
  1652. 'supplementary_count' => count($supplementaryQuestions),
  1653. 'total_after_supplement' => count($selectedQuestions),
  1654. 'textbook_id' => $textbookId
  1655. ]);
  1656. } else {
  1657. Log::warning('getQuestionsFromBank: 智能补充失败,未找到合适的题目', [
  1658. 'grade' => $grade,
  1659. 'textbook_id' => $textbookId,
  1660. 'note' => $textbookId ? '可能是该教材知识点题目不足' : '该年级题目不足'
  1661. ]);
  1662. }
  1663. }
  1664. Log::info('getQuestionsFromBank 完成', [
  1665. 'final_count' => count($selectedQuestions),
  1666. 'raw_database_count' => $questions->count(),
  1667. 'total_needed' => $totalNeeded,
  1668. 'success' => $totalNeeded > 0 ? count($selectedQuestions) >= $totalNeeded : true,
  1669. 'time_ms' => round((microtime(true) - $startTime) * 1000, 2)
  1670. ]);
  1671. return $selectedQuestions;
  1672. } catch (\Exception $e) {
  1673. Log::error('getQuestionsFromBank 查询失败', [
  1674. 'error' => $e->getMessage(),
  1675. 'trace' => $e->getTraceAsString()
  1676. ]);
  1677. throw $e;
  1678. }
  1679. }
  1680. /**
  1681. * 获取指定ID的题目详情
  1682. */
  1683. private function getLocalQuestionsByIds(array $questionIds): array
  1684. {
  1685. try {
  1686. // 通过QuestionBankService获取题目详情
  1687. $questionBankService = $this->questionBankService ?? app(\App\Services\QuestionBankService::class);
  1688. // 批量获取题目详情
  1689. $response = $questionBankService->getQuestionsByIds($questionIds);
  1690. if (empty($response['data'])) {
  1691. Log::warning('getLocalQuestionsByIds: 未获取到任何题目', [
  1692. 'requested_ids' => $questionIds
  1693. ]);
  1694. return [];
  1695. }
  1696. $questions = $response['data'];
  1697. // 转换为标准格式
  1698. $result = array_map(function ($q) {
  1699. $difficulty = $q['difficulty'] ?? 0.5;
  1700. return [
  1701. 'id' => $q['id'],
  1702. 'question_code' => $q['question_code'] ?? '',
  1703. 'kp_code' => $q['kp_code'] ?? '',
  1704. 'question_type' => $q['question_type'] ?? 'choice',
  1705. 'difficulty' => (float) $difficulty,
  1706. 'stem' => $q['stem'] ?? '',
  1707. 'solution' => $q['solution'] ?? '',
  1708. 'answer' => $q['answer'] ?? '',
  1709. 'metadata' => [
  1710. 'has_solution' => !empty($q['solution']),
  1711. 'is_choice' => ($q['question_type'] ?? 'choice') === 'choice',
  1712. 'is_fill' => ($q['question_type'] ?? 'choice') === 'fill',
  1713. 'is_answer' => ($q['question_type'] ?? 'choice') === 'answer',
  1714. 'difficulty_label' => $this->getDifficultyLabel((float) $difficulty),
  1715. 'question_type_label' => $this->getQuestionTypeLabel($q['question_type'] ?? 'choice')
  1716. ]
  1717. ];
  1718. }, $questions);
  1719. Log::info('getLocalQuestionsByIds 获取成功', [
  1720. 'requested_count' => count($questionIds),
  1721. 'found_count' => count($result),
  1722. 'missing_ids' => array_diff($questionIds, array_column($result, 'id')),
  1723. 'question_ids' => array_slice($questionIds, 0, 20),
  1724. 'found_question_ids' => array_slice(array_column($result, 'id'), 0, 20)
  1725. ]);
  1726. return $result;
  1727. } catch (\Exception $e) {
  1728. Log::error('getLocalQuestionsByIds 获取失败', [
  1729. 'question_ids' => $questionIds,
  1730. 'error' => $e->getMessage(),
  1731. 'trace' => $e->getTraceAsString()
  1732. ]);
  1733. return [];
  1734. }
  1735. }
  1736. /**
  1737. * 获取卷子的所有题目ID(不区分对错)
  1738. */
  1739. private function getPaperAllQuestions(array $paperIds): array
  1740. {
  1741. try {
  1742. // 查询 paper_questions 表获取所有题目ID
  1743. $questionIds = DB::table('paper_questions')
  1744. ->whereIn('paper_id', $paperIds)
  1745. ->pluck('question_bank_id')
  1746. ->unique()
  1747. ->filter()
  1748. ->values()
  1749. ->toArray();
  1750. Log::debug('LearningAnalyticsService: 获取卷子所有题目', [
  1751. 'paper_ids' => $paperIds,
  1752. 'question_count' => count($questionIds)
  1753. ]);
  1754. return $questionIds;
  1755. } catch (\Exception $e) {
  1756. Log::error('LearningAnalyticsService: 获取卷子题目失败', [
  1757. 'paper_ids' => $paperIds,
  1758. 'error' => $e->getMessage()
  1759. ]);
  1760. return [];
  1761. }
  1762. }
  1763. /**
  1764. * 获取难度标签
  1765. */
  1766. private function getDifficultyLabel(?float $difficulty): string
  1767. {
  1768. if ($difficulty === null) {
  1769. return '未知';
  1770. }
  1771. return match (true) {
  1772. $difficulty < 0.4 => '基础',
  1773. $difficulty < 0.7 => '中等',
  1774. default => '拔高'
  1775. };
  1776. }
  1777. /**
  1778. * 获取题型标签
  1779. */
  1780. private function getQuestionTypeLabel(string $questionType): string
  1781. {
  1782. return match ($questionType) {
  1783. 'choice' => '选择题',
  1784. 'fill' => '填空题',
  1785. 'answer' => '解答题',
  1786. default => '未知题型'
  1787. };
  1788. }
  1789. /**
  1790. * 根据题型配比选择题目
  1791. * 注意: 难度配比调整由 QuestionLocalService 处理
  1792. */
  1793. private function selectQuestionsByRatio(
  1794. array $questions,
  1795. int $totalNeeded,
  1796. array $questionTypeRatio = []
  1797. ): array {
  1798. if (empty($questions)) {
  1799. return [];
  1800. }
  1801. // 如果没有配比要求,直接返回
  1802. if (empty($questionTypeRatio)) {
  1803. return array_slice($questions, 0, $totalNeeded);
  1804. }
  1805. $selected = [];
  1806. $usedIndices = [];
  1807. // 按题型配比选择
  1808. if (!empty($questionTypeRatio)) {
  1809. foreach ($questionTypeRatio as $type => $ratio) {
  1810. $count = (int) round(($ratio / 100) * $totalNeeded);
  1811. if ($count <= 0) continue;
  1812. $typeQuestions = [];
  1813. foreach ($questions as $idx => $q) {
  1814. if (in_array($idx, $usedIndices)) continue;
  1815. $qType = $q['question_type'] ?? '';
  1816. $label = $this->getQuestionTypeLabel($qType);
  1817. if ($label === $type) {
  1818. $typeQuestions[] = ['idx' => $idx, 'question' => $q];
  1819. }
  1820. }
  1821. // 随机选择
  1822. shuffle($typeQuestions);
  1823. $selectedCount = min($count, count($typeQuestions));
  1824. for ($i = 0; $i < $selectedCount; $i++) {
  1825. $selected[] = $typeQuestions[$i]['question'];
  1826. $usedIndices[] = $typeQuestions[$i]['idx'];
  1827. }
  1828. }
  1829. }
  1830. // 如果还有空缺,补充剩余题目
  1831. // 注意: 难度配比调整由 QuestionLocalService 处理
  1832. if (count($selected) < $totalNeeded) {
  1833. foreach ($questions as $idx => $q) {
  1834. if (count($selected) >= $totalNeeded) break;
  1835. if (!in_array($idx, $usedIndices)) {
  1836. $selected[] = $q;
  1837. $usedIndices[] = $idx;
  1838. }
  1839. }
  1840. }
  1841. return array_slice($selected, 0, $totalNeeded);
  1842. }
  1843. /**
  1844. * 根据学生掌握度筛选题目
  1845. */
  1846. private function selectQuestionsByMastery(
  1847. array $questions,
  1848. ?string $studentId,
  1849. int $totalQuestions,
  1850. array $questionTypeRatio,
  1851. array $difficultyLevels,
  1852. array $weaknessFilter,
  1853. int $assembleType // 新增assembleType参数
  1854. ): array {
  1855. // 【修复】题目数量处理逻辑:无论题目数量多少,都要进行权重分配和筛选
  1856. // 如果题目数量超过目标,则截取到目标数量
  1857. // 如果题目数量不足,则使用所有题目,并记录警告
  1858. if (count($questions) > $totalQuestions) {
  1859. Log::debug('selectQuestionsByMastery: 题目数量超过目标,进行截取', [
  1860. 'question_count' => count($questions),
  1861. 'total_questions' => $totalQuestions
  1862. ]);
  1863. } else {
  1864. Log::warning('题目数量不足,将使用所有可用题目', [
  1865. 'available_count' => count($questions),
  1866. 'requested_count' => $totalQuestions,
  1867. 'note' => '可能需要补充题库或放宽筛选条件'
  1868. ]);
  1869. }
  1870. // 【移除】删除多余的难度筛选逻辑
  1871. // 题目本身就有难度系数,QuestionLocalService的难度分布系统会处理题目分布
  1872. // 不需要额外的难度筛选,让题目保持原始的难度分布
  1873. // 1. 按知识点分组
  1874. $groupStartTime = microtime(true);
  1875. $questionsByKp = [];
  1876. foreach ($questions as $question) {
  1877. $kpCode = $question['kp_code'] ?? '';
  1878. if (!isset($questionsByKp[$kpCode])) {
  1879. $questionsByKp[$kpCode] = [];
  1880. }
  1881. $questionsByKp[$kpCode][] = $question;
  1882. }
  1883. $groupTime = (microtime(true) - $groupStartTime) * 1000;
  1884. // 2. 为每个知识点计算权重(用于题型内的题目排序)
  1885. $kpWeights = [];
  1886. $kpCodes = array_keys($questionsByKp);
  1887. $startTime = microtime(true);
  1888. $allMastery = [];
  1889. if ($studentId) {
  1890. // 批量获取所有知识点的掌握度(一次查询)
  1891. $masteryStart = microtime(true);
  1892. try {
  1893. $masteryRecords = DB::table('student_mastery')
  1894. ->where('student_id', $studentId)
  1895. ->whereIn('kp', $kpCodes)
  1896. ->pluck('mastery', 'kp')
  1897. ->all();
  1898. Log::debug('批量获取掌握度', [
  1899. 'student_id' => $studentId,
  1900. 'kp_count' => count($kpCodes),
  1901. 'found_count' => count($masteryRecords),
  1902. 'time_ms' => round((microtime(true) - $masteryStart) * 1000, 2)
  1903. ]);
  1904. $allMastery = $masteryRecords;
  1905. } catch (\Exception $e) {
  1906. Log::warning('批量获取掌握度失败,将使用默认值', [
  1907. 'student_id' => $studentId,
  1908. 'error' => $e->getMessage()
  1909. ]);
  1910. }
  1911. }
  1912. foreach ($kpCodes as $kpCode) {
  1913. if ($studentId) {
  1914. $mastery = $allMastery[$kpCode] ?? 0.5; // 默认0.5(中等掌握度)
  1915. // 薄弱点权重更高
  1916. if (in_array($kpCode, $weaknessFilter)) {
  1917. $kpWeights[$kpCode] = 2.0; // 薄弱点权重翻倍
  1918. } else {
  1919. // 掌握度越低,权重越高
  1920. $kpWeights[$kpCode] = 1.0 + (1.0 - $mastery) * 1.5;
  1921. }
  1922. Log::debug('计算知识点权重', [
  1923. 'kp_code' => $kpCode,
  1924. 'mastery' => $mastery,
  1925. 'weight' => $kpWeights[$kpCode]
  1926. ]);
  1927. } else {
  1928. $kpWeights[$kpCode] = 1.0; // 未指定学生时平均分配
  1929. }
  1930. }
  1931. // 3. 按题型分配题目数量(权重用于题型内排序)
  1932. $selectedQuestions = [];
  1933. // 将所有题目合并
  1934. $weightedQuestions = [];
  1935. foreach ($questionsByKp as $kpCode => $kpQuestions) {
  1936. foreach ($kpQuestions as $q) {
  1937. $q['kp_code'] = $kpCode;
  1938. $weightedQuestions[] = $q;
  1939. }
  1940. }
  1941. // ========== 知识点优先选择机制 ==========
  1942. // 摸底测试的核心目标是最大化知识点覆盖
  1943. // 题型只是约束条件(每种至少1题)
  1944. // 首先按题型分组
  1945. $questionsByType = [
  1946. 'choice' => [],
  1947. 'fill' => [],
  1948. 'answer' => [],
  1949. ];
  1950. foreach ($weightedQuestions as $q) {
  1951. $qid = $q['id'] ?? $q['question_id'] ?? null;
  1952. if ($qid && isset($questionTypeCache[$qid])) {
  1953. $type = $questionTypeCache[$qid];
  1954. } else {
  1955. $type = $this->determineQuestionType($q);
  1956. if ($qid) {
  1957. $questionTypeCache[$qid] = $type;
  1958. }
  1959. }
  1960. if (!isset($questionsByType[$type])) {
  1961. $type = 'answer'; // 默认归类为answer
  1962. }
  1963. $questionsByType[$type][] = $q;
  1964. }
  1965. // ========== 步骤1:按题型分配题目 ==========
  1966. $selectedQuestions = [];
  1967. // 【区分】根据assembleType决定是否使用知识点优先机制
  1968. $useKnowledgePointPriority = ($assembleType === 0); // 摸底测试需要知识点优先
  1969. $kpSelected = []; // 已选知识点记录
  1970. // 【新增】非摸底类型:按比例计算每种题型的目标数量
  1971. $typeTargets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  1972. if (!$useKnowledgePointPriority) {
  1973. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  1974. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  1975. $allocated = 0;
  1976. $fractions = [];
  1977. foreach ($ratioMap as $type => $ratioKey) {
  1978. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  1979. $exact = $totalQuestions * $ratio / $totalRatio;
  1980. $typeTargets[$type] = (int) floor($exact);
  1981. $fractions[$type] = $exact - floor($exact);
  1982. $allocated += $typeTargets[$type];
  1983. }
  1984. // 余数分配给小数部分最大的题型
  1985. $remainder = $totalQuestions - $allocated;
  1986. arsort($fractions);
  1987. foreach ($fractions as $type => $frac) {
  1988. if ($remainder <= 0) break;
  1989. $typeTargets[$type]++;
  1990. $remainder--;
  1991. }
  1992. Log::debug('selectQuestionsByMastery: 题型目标分配', [
  1993. 'total_questions' => $totalQuestions,
  1994. 'targets' => $typeTargets,
  1995. ]);
  1996. }
  1997. // 确保每种题型至少选1题
  1998. foreach (['choice', 'fill', 'answer'] as $type) {
  1999. if (empty($questionsByType[$type])) {
  2000. Log::warning('题型分配:题型无题目', ['type' => $type]);
  2001. continue;
  2002. }
  2003. // 按权重排序该题型的题目
  2004. usort($questionsByType[$type], function ($a, $b) use ($kpWeights) {
  2005. $kpA = $a['kp_code'] ?? '';
  2006. $kpB = $b['kp_code'] ?? '';
  2007. $weightA = $kpWeights[$kpA] ?? 1.0;
  2008. $weightB = $kpWeights[$kpB] ?? 1.0;
  2009. return $weightB <=> $weightA;
  2010. });
  2011. // 【修复】摸底测试题型基础分配:记录每个题型的知识点分布
  2012. $typeKpDistribution = [];
  2013. foreach ($questionsByType[$type] as $q) {
  2014. $kpCode = $q['kp_code'] ?? '';
  2015. if (!isset($typeKpDistribution[$kpCode])) {
  2016. $typeKpDistribution[$kpCode] = 0;
  2017. }
  2018. $typeKpDistribution[$kpCode]++;
  2019. }
  2020. Log::debug('摸底测试题型基础分配', [
  2021. 'type' => $type,
  2022. 'total_in_type' => count($questionsByType[$type]),
  2023. 'kp_count' => count($typeKpDistribution)
  2024. ]);
  2025. // 根据策略选择题目
  2026. if ($useKnowledgePointPriority) {
  2027. // 摸底测试:选择第一个未选过知识点的题目
  2028. $selectedInThisType = 0;
  2029. foreach ($questionsByType[$type] as $q) {
  2030. $kpCode = $q['kp_code'] ?? '';
  2031. if (!isset($kpSelected[$kpCode])) {
  2032. $selectedQuestions[] = $q;
  2033. $kpSelected[$kpCode] = true;
  2034. $selectedInThisType++;
  2035. Log::debug('题型基础分配(知识点优先)', [
  2036. 'type' => $type,
  2037. 'kp' => $kpCode,
  2038. 'question_id' => $q['id'] ?? 'unknown',
  2039. 'selected_in_type' => $selectedInThisType
  2040. ]);
  2041. break; // 只选1题
  2042. }
  2043. }
  2044. Log::debug('摸底测试题型基础分配完成', [
  2045. 'type' => $type,
  2046. 'selected_count' => $selectedInThisType
  2047. ]);
  2048. } else {
  2049. // 非摸底:按目标数量从该题型池中选题
  2050. $target = $typeTargets[$type] ?? 0;
  2051. $selectedIds = array_column($selectedQuestions, 'id');
  2052. $taken = 0;
  2053. foreach ($questionsByType[$type] as $q) {
  2054. if ($taken >= $target) break;
  2055. $qid = $q['id'] ?? null;
  2056. if ($qid && !in_array($qid, $selectedIds)) {
  2057. $selectedQuestions[] = $q;
  2058. $selectedIds[] = $qid;
  2059. $taken++;
  2060. }
  2061. }
  2062. $typeTargets[$type . '_actual'] = $taken;
  2063. Log::debug('题型按比例分配', [
  2064. 'type' => $type,
  2065. 'target' => $target,
  2066. 'actual' => $taken
  2067. ]);
  2068. }
  2069. }
  2070. // ========== 步骤2:继续选题目,直到达到目标数量 ==========
  2071. $allQuestions = array_merge($questionsByType['choice'], $questionsByType['fill'], $questionsByType['answer']);
  2072. // 【重要】添加排序前的知识点分布日志
  2073. $preSortKpDistribution = [];
  2074. foreach ($allQuestions as $q) {
  2075. $kpCode = $q['kp_code'] ?? '';
  2076. if (!isset($preSortKpDistribution[$kpCode])) {
  2077. $preSortKpDistribution[$kpCode] = 0;
  2078. }
  2079. $preSortKpDistribution[$kpCode]++;
  2080. }
  2081. Log::debug('selectQuestionsByMastery: 排序前知识点分布', [
  2082. 'total_questions' => count($allQuestions),
  2083. 'kp_distribution' => $preSortKpDistribution
  2084. ]);
  2085. // 【修复】添加随机因子到排序中,避免因ID排序导致知识点分布不均
  2086. usort($allQuestions, function ($a, $b) use ($kpWeights) {
  2087. $kpA = $a['kp_code'] ?? '';
  2088. $kpB = $b['kp_code'] ?? '';
  2089. $weightA = $kpWeights[$kpA] ?? 1.0;
  2090. $weightB = $kpWeights[$kpB] ?? 1.0;
  2091. // 主要按权重排序
  2092. if ($weightA != $weightB) {
  2093. return $weightB <=> $weightA;
  2094. }
  2095. // 权重相同时,添加随机排序而不是按ID排序
  2096. // 使用随机因子确保相同权重的知识点有公平的选中机会
  2097. return mt_rand(-1, 1);
  2098. });
  2099. // 【重要】添加排序后的知识点分布日志
  2100. $postSortKpDistribution = [];
  2101. $postSortFirst50 = []; // 记录前50题的知识点分布
  2102. foreach ($allQuestions as $idx => $q) {
  2103. $kpCode = $q['kp_code'] ?? '';
  2104. if (!isset($postSortKpDistribution[$kpCode])) {
  2105. $postSortKpDistribution[$kpCode] = 0;
  2106. }
  2107. $postSortKpDistribution[$kpCode]++;
  2108. // 记录前50题的知识点
  2109. if ($idx < 50) {
  2110. $postSortFirst50[] = $kpCode;
  2111. }
  2112. }
  2113. Log::debug('selectQuestionsByMastery: 排序后知识点分布', [
  2114. 'total_questions' => count($allQuestions),
  2115. 'kp_distribution' => $postSortKpDistribution
  2116. ]);
  2117. // 【修复】摸底测试继续选择题目:记录详细的选题过程
  2118. Log::debug('摸底测试继续选择题目开始', [
  2119. 'selected_count_after_basic' => count($selectedQuestions),
  2120. 'total_questions' => $totalQuestions,
  2121. 'selected_kp_codes' => array_keys($kpSelected),
  2122. 'available_kp_count' => count($preSortKpDistribution),
  2123. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制'
  2124. ]);
  2125. if ($useKnowledgePointPriority) {
  2126. // 摸底测试:优先选择未选过知识点的题目
  2127. $initialSelectedCount = count($selectedQuestions);
  2128. $prioritySelectedCount = 0;
  2129. foreach ($allQuestions as $q) {
  2130. if (count($selectedQuestions) >= $totalQuestions) break;
  2131. $kpCode = $q['kp_code'] ?? '';
  2132. if (!isset($kpSelected[$kpCode])) {
  2133. $selectedQuestions[] = $q;
  2134. $kpSelected[$kpCode] = true;
  2135. $prioritySelectedCount++;
  2136. Log::debug('继续选择题目(知识点优先)', [
  2137. 'kp' => $kpCode,
  2138. 'id' => $q['id'] ?? 'unknown',
  2139. 'priority_selected_count' => $prioritySelectedCount,
  2140. 'total_selected' => count($selectedQuestions)
  2141. ]);
  2142. }
  2143. }
  2144. Log::debug('摸底测试优先阶段完成', [
  2145. 'priority_selected_count' => $prioritySelectedCount,
  2146. 'total_selected' => count($selectedQuestions),
  2147. 'unique_kp_count' => count($kpSelected),
  2148. 'note' => '优先选择未选过知识点的题目'
  2149. ]);
  2150. // 【修复】降级策略:如果仍未达到目标数量,允许重复选择知识点
  2151. if (count($selectedQuestions) < $totalQuestions) {
  2152. Log::warning('selectQuestionsByMastery: 知识点优先策略无法满足数量要求,启用降级策略', [
  2153. 'requested_count' => $totalQuestions,
  2154. 'selected_count' => count($selectedQuestions),
  2155. 'priority_selected_count' => $prioritySelectedCount,
  2156. 'unique_kp_count' => count($kpSelected),
  2157. 'available_kp_count' => count($preSortKpDistribution),
  2158. 'note' => '将允许重复选择知识点以达到目标数量'
  2159. ]);
  2160. $fallbackSelectedCount = 0;
  2161. $selectedIds = array_column($selectedQuestions, 'id');
  2162. foreach ($allQuestions as $q) {
  2163. if (count($selectedQuestions) >= $totalQuestions) break;
  2164. $qid = $q['id'] ?? null;
  2165. if ($qid && !in_array($qid, $selectedIds)) {
  2166. $selectedQuestions[] = $q;
  2167. $selectedIds[] = $qid;
  2168. $fallbackSelectedCount++;
  2169. Log::debug('降级选择题目(允许知识点重复)', [
  2170. 'kp' => $q['kp_code'] ?? 'unknown',
  2171. 'id' => $qid,
  2172. 'fallback_selected_count' => $fallbackSelectedCount,
  2173. 'current_count' => count($selectedQuestions)
  2174. ]);
  2175. }
  2176. }
  2177. Log::debug('摸底测试降级阶段完成', [
  2178. 'fallback_selected_count' => $fallbackSelectedCount,
  2179. 'total_selected' => count($selectedQuestions),
  2180. 'note' => '允许重复选择知识点补充数量'
  2181. ]);
  2182. }
  2183. } else {
  2184. // 非摸底:题型不足时,缺口按优先级补到其他题型
  2185. $totalSelected = count($selectedQuestions);
  2186. if ($totalSelected < $totalQuestions) {
  2187. $deficit = $totalQuestions - $totalSelected;
  2188. $selectedIds = array_column($selectedQuestions, 'id');
  2189. // 按补充优先级:填空 > 解答 > 选择(避免解答题独占缺口)
  2190. $supplementOrder = ['fill', 'answer', 'choice'];
  2191. Log::debug('题型缺口补充开始', [
  2192. 'deficit' => $deficit,
  2193. 'current_count' => $totalSelected,
  2194. 'target' => $totalQuestions,
  2195. 'supplement_order' => $supplementOrder,
  2196. ]);
  2197. foreach ($supplementOrder as $type) {
  2198. if ($deficit <= 0) break;
  2199. foreach ($questionsByType[$type] as $q) {
  2200. if ($deficit <= 0) break;
  2201. $qid = $q['id'] ?? null;
  2202. if ($qid && !in_array($qid, $selectedIds)) {
  2203. $selectedQuestions[] = $q;
  2204. $selectedIds[] = $qid;
  2205. $deficit--;
  2206. }
  2207. }
  2208. }
  2209. Log::debug('题型缺口补充完成', [
  2210. 'final_count' => count($selectedQuestions),
  2211. 'target' => $totalQuestions,
  2212. ]);
  2213. }
  2214. }
  2215. // 【移除】删除步骤3的多余逻辑
  2216. // 前面的逻辑已经能选够题目,不需要额外的补充步骤
  2217. Log::info('selectQuestionsByMastery 完成', [
  2218. 'total_questions' => $totalQuestions,
  2219. 'selected_count' => count($selectedQuestions),
  2220. 'success' => count($selectedQuestions) === $totalQuestions,
  2221. 'assemble_type' => $assembleType,
  2222. 'strategy' => $useKnowledgePointPriority ? '知识点优先' : '无知识点限制',
  2223. 'type_distribution' => array_count_values(array_map(function($q) {
  2224. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2225. if ($qid && isset($questionTypeCache[$qid])) {
  2226. return $questionTypeCache[$qid];
  2227. }
  2228. return $this->determineQuestionType($q);
  2229. }, $selectedQuestions)),
  2230. 'kp_distribution' => array_count_values(array_column($selectedQuestions, 'kp_code'))
  2231. ]);
  2232. // 【重要】最终截取到目标数量(如果超过)
  2233. if (count($selectedQuestions) > $totalQuestions) {
  2234. Log::info('题目数量超过目标,进行最终截取', [
  2235. 'before' => count($selectedQuestions),
  2236. 'after' => $totalQuestions
  2237. ]);
  2238. $selectedQuestions = array_slice($selectedQuestions, 0, $totalQuestions);
  2239. }
  2240. // 【重要】添加最终数量验证日志
  2241. Log::debug('selectQuestionsByMastery: 最终题目数量验证', [
  2242. 'before_final_check' => count($selectedQuestions),
  2243. 'target_count' => $totalQuestions,
  2244. 'is_array' => is_array($selectedQuestions)
  2245. ]);
  2246. // 【新增】最终知识点分布统计
  2247. $finalKpDistribution = array_count_values(array_column($selectedQuestions, 'kp_code'));
  2248. Log::debug('摸底测试最终知识点分布', [
  2249. 'final_total_count' => count($selectedQuestions),
  2250. 'target_count' => $totalQuestions,
  2251. 'final_kp_distribution' => $finalKpDistribution,
  2252. 'unique_kp_count' => count($finalKpDistribution),
  2253. 'success' => count($selectedQuestions) === $totalQuestions,
  2254. 'kp_coverage_rate' => count($finalKpDistribution) / max(count($preSortKpDistribution), 1) * 100
  2255. ]);
  2256. // ========== 最终排查:确保无重复题目且题型分布合理 ==========
  2257. $finalQuestions = [];
  2258. $seenQuestionIds = [];
  2259. $duplicateCount = 0;
  2260. $typeDistribution = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2261. foreach ($selectedQuestions as $question) {
  2262. $qbId = $question['question_bank_id'] ?? $question['id'];
  2263. if (!in_array($qbId, $seenQuestionIds)) {
  2264. $seenQuestionIds[] = $qbId;
  2265. $finalQuestions[] = $question;
  2266. // 统计题型分布
  2267. $qid = $question['id'] ?? $question['question_id'] ?? null;
  2268. $type = null;
  2269. if ($qid && isset($questionTypeCache[$qid])) {
  2270. $type = $questionTypeCache[$qid];
  2271. } else {
  2272. $type = $this->determineQuestionType($question);
  2273. if ($qid) {
  2274. $questionTypeCache[$qid] = $type;
  2275. }
  2276. }
  2277. if (isset($typeDistribution[$type])) {
  2278. $typeDistribution[$type]++;
  2279. }
  2280. } else {
  2281. $duplicateCount++;
  2282. Log::warning('发现重复题目(已自动移除)', [
  2283. 'question_id' => $qbId,
  2284. 'duplicate_count' => $duplicateCount
  2285. ]);
  2286. }
  2287. }
  2288. // 【重要】如果去重后数量不足,补充到目标数量
  2289. if (count($finalQuestions) < $totalQuestions) {
  2290. Log::warning('selectQuestionsByMastery: 去重后数量不足,尝试补充', [
  2291. 'final_count' => count($finalQuestions),
  2292. 'target_count' => $totalQuestions,
  2293. 'need_more' => $totalQuestions - count($finalQuestions)
  2294. ]);
  2295. // 从原始题目中选择未选过的题目补充
  2296. $usedIds = array_column($finalQuestions, 'id');
  2297. $supplementCount = 0;
  2298. foreach ($selectedQuestions as $question) {
  2299. if ($supplementCount >= ($totalQuestions - count($finalQuestions))) break;
  2300. $qid = $question['id'] ?? null;
  2301. if ($qid && !in_array($qid, $usedIds)) {
  2302. $finalQuestions[] = $question;
  2303. $usedIds[] = $qid;
  2304. $supplementCount++;
  2305. }
  2306. }
  2307. Log::debug('selectQuestionsByMastery: 补充完成', [
  2308. 'supplement_added' => $supplementCount,
  2309. 'final_count_after_supplement' => count($finalQuestions)
  2310. ]);
  2311. }
  2312. Log::debug('最终排查完成', [
  2313. 'original_count' => count($selectedQuestions),
  2314. 'final_count' => count($finalQuestions),
  2315. 'duplicate_removed' => $duplicateCount,
  2316. 'final_type_distribution' => $typeDistribution,
  2317. 'target_count' => $totalQuestions
  2318. ]);
  2319. // 【重要】确保返回的题目数量正确
  2320. $finalQuestions = array_slice($finalQuestions, 0, $totalQuestions);
  2321. Log::debug('selectQuestionsByMastery: 返回结果', [
  2322. 'return_count' => count($finalQuestions),
  2323. 'target_count' => $totalQuestions,
  2324. 'success' => count($finalQuestions) === $totalQuestions
  2325. ]);
  2326. // 注意:题型平衡已在上面完成,不需要再调用adjustQuestionsByRatio
  2327. // adjustQuestionsByRatio主要处理题型配比,但我们的题型平衡机制已经确保了题型分布符合要求
  2328. return $finalQuestions;
  2329. }
  2330. /**
  2331. * 获取学生对特定知识点的掌握度
  2332. */
  2333. private function getStudentKpMastery(string $studentId, string $kpCode): float
  2334. {
  2335. try {
  2336. $mastery = DB::table('student_mastery')
  2337. ->where('student_id', $studentId)
  2338. ->where('kp', $kpCode)
  2339. ->value('mastery');
  2340. return $mastery ? (float) $mastery : 0.5; // 默认0.5(中等掌握度)
  2341. } catch (\Exception $e) {
  2342. Log::error('Get Student Kp Mastery Error', [
  2343. 'student_id' => $studentId,
  2344. 'kp_code' => $kpCode,
  2345. 'error' => $e->getMessage()
  2346. ]);
  2347. return 0.5;
  2348. }
  2349. }
  2350. /**
  2351. * 根据题型和难度配比调整题目
  2352. */
  2353. private function adjustQuestionsByRatio(array $questions, array $typeRatio, int $targetCount): array
  2354. {
  2355. Log::debug('开始题型配比调整', [
  2356. 'input_questions' => count($questions),
  2357. 'target_count' => $targetCount,
  2358. 'type_ratio' => $typeRatio
  2359. ]);
  2360. // 缓存题目类型,避免重复计算
  2361. $questionTypeCache = [];
  2362. // 按题型分桶
  2363. $buckets = [
  2364. 'choice' => [],
  2365. 'fill' => [],
  2366. 'answer' => [],
  2367. ];
  2368. foreach ($questions as $q) {
  2369. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2370. if ($qid && isset($questionTypeCache[$qid])) {
  2371. $type = $questionTypeCache[$qid];
  2372. } else {
  2373. $type = $this->determineQuestionType($q);
  2374. if ($qid) {
  2375. $questionTypeCache[$qid] = $type;
  2376. }
  2377. }
  2378. if (!isset($buckets[$type])) {
  2379. $type = 'answer';
  2380. }
  2381. $buckets[$type][] = $q;
  2382. }
  2383. // 计算目标数(四舍五入,比例>0 则至少 1 道)
  2384. // 修复:不自动减少目标数量,确保达到用户要求
  2385. $availableCount = count($questions);
  2386. $targets = $this->computeTypeTargets($targetCount, $typeRatio);
  2387. Log::debug('题型配比调整前桶统计', [
  2388. 'target_count' => $targetCount,
  2389. 'available_count' => $availableCount,
  2390. 'targets' => $targets,
  2391. 'bucket_counts' => [
  2392. 'choice' => count($buckets['choice']),
  2393. 'fill' => count($buckets['fill']),
  2394. 'answer' => count($buckets['answer']),
  2395. ],
  2396. 'raw_ratio' => $typeRatio,
  2397. ]);
  2398. // 随机打乱桶
  2399. foreach ($buckets as $k => $v) {
  2400. if (!empty($v)) {
  2401. shuffle($v);
  2402. $buckets[$k] = $v;
  2403. }
  2404. }
  2405. $selected = [];
  2406. $selectedIds = [];
  2407. // 按目标数依次取题
  2408. foreach (['choice', 'fill', 'answer'] as $typeKey) {
  2409. $need = $targets[$typeKey] ?? 0;
  2410. if ($need <= 0 || empty($buckets[$typeKey])) {
  2411. continue;
  2412. }
  2413. $take = min($need, count($buckets[$typeKey]));
  2414. $slice = array_slice($buckets[$typeKey], 0, $take);
  2415. foreach ($slice as $q) {
  2416. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2417. if (isset($selectedIds[$id])) {
  2418. continue;
  2419. }
  2420. $selected[] = $q;
  2421. $selectedIds[$id] = true;
  2422. }
  2423. }
  2424. // 不足则从剩余题中补齐
  2425. if (count($selected) < $targetCount) {
  2426. $remaining = [];
  2427. foreach ($buckets as $v) {
  2428. foreach ($v as $q) {
  2429. $id = $q['id'] ?? $q['question_id'] ?? spl_object_id((object)$q);
  2430. if (!isset($selectedIds[$id])) {
  2431. $remaining[] = $q;
  2432. }
  2433. }
  2434. }
  2435. shuffle($remaining);
  2436. $needMore = $targetCount - count($selected);
  2437. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  2438. }
  2439. // 截断至目标数
  2440. $selected = array_slice($selected, 0, $targetCount);
  2441. // 使用缓存统计题型分布
  2442. $selectedCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2443. foreach ($selected as $q) {
  2444. $qid = $q['id'] ?? $q['question_id'] ?? null;
  2445. if ($qid && isset($questionTypeCache[$qid])) {
  2446. $type = $questionTypeCache[$qid];
  2447. } else {
  2448. $type = $this->determineQuestionType($q);
  2449. }
  2450. if (isset($selectedCounts[$type])) {
  2451. $selectedCounts[$type]++;
  2452. }
  2453. }
  2454. Log::debug('题型配比调整完成', [
  2455. 'target_count' => $targetCount,
  2456. 'targets' => $targets,
  2457. 'selected_counts' => $selectedCounts,
  2458. 'final_selected_count' => count($selected)
  2459. ]);
  2460. return $selected;
  2461. }
  2462. private function determineQuestionType(array $q): string
  2463. {
  2464. // 优先根据题目内容判断(而不是数据库字段)
  2465. $stem = $q['stem'] ?? $q['content'] ?? '';
  2466. // 处理 stem 可能是数组的情况
  2467. if (is_array($stem)) {
  2468. $stem = json_encode($stem, JSON_UNESCAPED_UNICODE);
  2469. }
  2470. $tags = $q['tags'] ?? '';
  2471. // 处理 tags 可能是数组的情况
  2472. if (is_array($tags)) {
  2473. $tags = json_encode($tags, JSON_UNESCAPED_UNICODE);
  2474. }
  2475. $skills = $q['skills'] ?? [];
  2476. // 1. 根据题干内容判断 - 选择题特征:必须包含 A. B. C. D. 选项(至少2个)
  2477. if (is_string($stem)) {
  2478. // 选择题特征:必须包含 A. B. C. D. 四个选项(至少2个)
  2479. $hasOptionA = preg_match('/\bA\s*[\.\、\:]/', $stem) || preg_match('/\(A\)/', $stem) || preg_match('/^A[\.\s]/', $stem);
  2480. $hasOptionB = preg_match('/\bB\s*[\.\、\:]/', $stem) || preg_match('/\(B\)/', $stem) || preg_match('/^B[\.\s]/', $stem);
  2481. $hasOptionC = preg_match('/\bC\s*[\.\、\:]/', $stem) || preg_match('/\(C\)/', $stem) || preg_match('/^C[\.\s]/', $stem);
  2482. $hasOptionD = preg_match('/\bD\s*[\.\、\:]/', $stem) || preg_match('/\(D\)/', $stem) || preg_match('/^D[\.\s]/', $stem);
  2483. $hasOptionE = preg_match('/\bE\s*[\.\、\:]/', $stem) || preg_match('/\(E\)/', $stem) || preg_match('/^E[\.\s]/', $stem);
  2484. // 至少有2个选项就认为是选择题(降低阈值)
  2485. $optionCount = ($hasOptionA ? 1 : 0) + ($hasOptionB ? 1 : 0) + ($hasOptionC ? 1 : 0) + ($hasOptionD ? 1 : 0) + ($hasOptionE ? 1 : 0);
  2486. if ($optionCount >= 2) {
  2487. return 'choice';
  2488. }
  2489. // 检查是否有"( )"或"( )"括号,这通常是选择题的标志
  2490. if (preg_match('/(\s*)|\(\s*\)/', $stem) && (strpos($stem, 'A.') !== false || strpos($stem, 'B.') !== false || strpos($stem, 'C.') !== false || strpos($stem, 'D.') !== false)) {
  2491. return 'choice';
  2492. }
  2493. }
  2494. // 2. 根据技能点判断
  2495. if (is_array($skills) && !empty($skills)) {
  2496. // 过滤非字符串元素,避免 implode 报错
  2497. $skillsFiltered = array_filter($skills, 'is_string');
  2498. if (!empty($skillsFiltered)) {
  2499. $skillsStr = implode(',', $skillsFiltered);
  2500. if (strpos($skillsStr, '选择题') !== false) return 'choice';
  2501. if (strpos($skillsStr, '填空题') !== false) return 'fill';
  2502. if (strpos($skillsStr, '解答题') !== false) return 'answer';
  2503. }
  2504. }
  2505. // 3. 根据题目已有类型字段判断(作为后备)
  2506. $typeField = $q['question_type'] ?? $q['type'] ?? '';
  2507. if (is_string($typeField)) {
  2508. $t = strtolower($typeField);
  2509. if (in_array($t, ['choice', 'single_choice', 'multiple_choice', '选择题', 'choice', 'single_choice', 'multiple_choice'])) {
  2510. return 'choice';
  2511. }
  2512. if (in_array($t, ['fill', 'blank', 'fill_blank', 'fill_in_the_blank', '填空题'])) {
  2513. return 'fill';
  2514. }
  2515. if (in_array($t, ['answer', 'calculation', 'word_problem', 'proof', '解答题'])) {
  2516. return 'answer';
  2517. }
  2518. }
  2519. // 4. 根据标签判断
  2520. if (is_string($tags)) {
  2521. if (strpos($tags, '选择') !== false || strpos($tags, '选择题') !== false) {
  2522. return 'choice';
  2523. }
  2524. if (strpos($tags, '填空') !== false || strpos($tags, '填空题') !== false) {
  2525. return 'fill';
  2526. }
  2527. if (strpos($tags, '解答') !== false || strpos($tags, '简答') !== false || strpos($tags, '证明') !== false) {
  2528. return 'answer';
  2529. }
  2530. }
  2531. // 5. 根据options字段判断
  2532. if (!empty($q['options']) && is_array($q['options'])) {
  2533. return 'choice';
  2534. }
  2535. // 6. 填空题特征:连续下划线或明显的填空括号
  2536. if (is_string($stem)) {
  2537. // 检查填空题特征:连续下划线
  2538. if (preg_match('/_{3,}/', $stem) || strpos($stem, '____') !== false) {
  2539. return 'fill';
  2540. }
  2541. // 空括号填空
  2542. if (preg_match('/(\s*)/', $stem) || preg_match('/\(\s*\)/', $stem)) {
  2543. return 'fill';
  2544. }
  2545. }
  2546. // 7. 根据题干内容关键词判断
  2547. if (is_string($stem)) {
  2548. // 有证明、解答、计算、求证等关键词的是解答题
  2549. if (preg_match('/(证明|求证|解方程|计算:|求解|推导|说明理由)/', $stem)) {
  2550. return 'answer';
  2551. }
  2552. }
  2553. // 默认是解答题(更安全的默认值)
  2554. return 'answer';
  2555. }
  2556. // 【移除】删除未使用的mapDifficultyLevel方法
  2557. // 难度分布由QuestionLocalService处理,不需要额外的难度映射
  2558. private function computeTypeTargets(int $targetCount, array $questionTypeRatio): array
  2559. {
  2560. $map = [
  2561. '选择题' => 'choice',
  2562. '填空题' => 'fill',
  2563. '解答题' => 'answer',
  2564. ];
  2565. $targets = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  2566. foreach ($questionTypeRatio as $label => $ratio) {
  2567. $key = $map[$label] ?? null;
  2568. if (!$key) {
  2569. continue;
  2570. }
  2571. $cnt = (int) round($targetCount * ($ratio / 100));
  2572. if ($ratio > 0 && $cnt < 1) {
  2573. $cnt = 1;
  2574. }
  2575. $targets[$key] = $cnt;
  2576. }
  2577. $sum = array_sum($targets);
  2578. if ($sum === 0) {
  2579. $targets['answer'] = $targetCount;
  2580. return $targets;
  2581. }
  2582. while ($sum > $targetCount) {
  2583. arsort($targets);
  2584. foreach ($targets as $k => $v) {
  2585. if ($v > 1) {
  2586. $targets[$k]--;
  2587. $sum--;
  2588. break;
  2589. }
  2590. }
  2591. }
  2592. if ($sum < $targetCount) {
  2593. $ratioByKey = [
  2594. 'choice' => $questionTypeRatio['选择题'] ?? 0,
  2595. 'fill' => $questionTypeRatio['填空题'] ?? 0,
  2596. 'answer' => $questionTypeRatio['解答题'] ?? 0,
  2597. ];
  2598. while ($sum < $targetCount) {
  2599. arsort($ratioByKey);
  2600. $k = array_key_first($ratioByKey);
  2601. $targets[$k]++;
  2602. $sum++;
  2603. }
  2604. }
  2605. return $targets;
  2606. }
  2607. /**
  2608. * 提交手动评分结果到 LearningAnalytics
  2609. *
  2610. * @param array $data 包含 student_id, paper_id, grades 的数组
  2611. * @return array
  2612. */
  2613. public function submitManualGrading(array $data): array
  2614. {
  2615. try {
  2616. $response = Http::timeout($this->timeout)
  2617. ->post($this->baseUrl . '/api/ocr/analyze', [
  2618. 'student_id' => $data['student_id'],
  2619. 'paper_id' => $data['paper_id'],
  2620. 'answers' => $data['grades'],
  2621. ]);
  2622. if ($response->successful()) {
  2623. Log::info('Manual grading submitted successfully', [
  2624. 'student_id' => $data['student_id'],
  2625. 'paper_id' => $data['paper_id'],
  2626. 'question_count' => count($data['grades'])
  2627. ]);
  2628. return $response->json();
  2629. }
  2630. Log::error('Submit Manual Grading Error', [
  2631. 'data' => $data,
  2632. 'status' => $response->status(),
  2633. 'response' => $response->body()
  2634. ]);
  2635. return [
  2636. 'error' => true,
  2637. 'message' => 'Failed to submit manual grading'
  2638. ];
  2639. } catch (\Exception $e) {
  2640. Log::error('Submit Manual Grading Exception', [
  2641. 'error' => $e->getMessage(),
  2642. 'data' => $data
  2643. ]);
  2644. return [
  2645. 'error' => true,
  2646. 'message' => $e->getMessage()
  2647. ];
  2648. }
  2649. }
  2650. /**
  2651. * 分析学生作答结果
  2652. *
  2653. * @param array $data 包含 paper_id, student_id, answers 等
  2654. * @return array
  2655. */
  2656. public function analyzeStudentAnswers(array $data): array
  2657. {
  2658. Log::warning('analyzeStudentAnswers 已停用:分析项目已下线', [
  2659. 'student_id' => $data['student_id'] ?? null,
  2660. 'paper_id' => $data['paper_id'] ?? null,
  2661. ]);
  2662. return [
  2663. 'success' => false,
  2664. 'message' => 'analysis_api_disabled',
  2665. ];
  2666. }
  2667. /**
  2668. * 智能补充题目(当指定知识点的题目不足时)
  2669. *
  2670. * @param int $grade 年级
  2671. * @param array $existingKpCodes 已有的知识点代码(用于排除)
  2672. * @param int $needCount 需要补充的题目数量
  2673. * @param int $difficultyCategory 难度类别
  2674. * @param int|null $textbookId 教材ID(用于限制补充范围,避免超纲)
  2675. * @param array $excludeQuestionIds 排除的题目ID(学生已做过,避免重复)
  2676. * @param array|null $textbookCatalogNodeIds 当前选中的章节节点ID;与 textbookId 同时传入时,仅从同教材的前章节补充(未学章节不补充)
  2677. * @param string|null $studentId 学生ID(无教材时用于获取「已学知识点」,仅从已学内容补充,避免未学章节)
  2678. * @return array 补充的题目列表
  2679. */
  2680. private function getSupplementaryQuestionsForGrade(
  2681. int $grade,
  2682. array $existingKpCodes,
  2683. int $needCount,
  2684. int $difficultyCategory,
  2685. ?int $textbookId = null,
  2686. array $excludeQuestionIds = [],
  2687. ?array $textbookCatalogNodeIds = null,
  2688. ?string $studentId = null
  2689. ): array {
  2690. try {
  2691. Log::info('getSupplementaryQuestionsForGrade: 开始智能补充', [
  2692. 'grade' => $grade,
  2693. 'existing_kp_count' => count($existingKpCodes),
  2694. 'need_count' => $needCount,
  2695. 'difficulty_category' => $difficultyCategory,
  2696. 'textbook_id' => $textbookId,
  2697. 'student_id' => $studentId ? '(有)' : '(无)',
  2698. 'exclude_count' => count($excludeQuestionIds),
  2699. 'has_chapter_scope' => !empty($textbookCatalogNodeIds),
  2700. ]);
  2701. // 【核心】补充范围:只从「学过的」内容补充,不能从未学知识点或年级对应章节中选
  2702. // - 有 textbookId:从 getGradeKnowledgePoints(grade, textbookId) + 前章节(若有 textbookCatalogNodeIds)
  2703. // - 无 textbookId 且有 studentId:从学生做过的题目对应知识点(getStudentLearnedKpCodes)补充
  2704. // - 无 textbookId 且无 studentId:无法确定学过的内容,不补充
  2705. $gradeKpCodes = [];
  2706. if ($textbookId) {
  2707. $gradeKpCodes = $this->getGradeKnowledgePoints($grade, $textbookId);
  2708. Log::info('getSupplementaryQuestionsForGrade: 教材模式,使用教材知识点', [
  2709. 'kp_count' => count($gradeKpCodes),
  2710. 'textbook_id' => $textbookId,
  2711. ]);
  2712. } elseif ($studentId) {
  2713. $learnedKps = $this->getStudentLearnedKpCodes($studentId);
  2714. $gradeKpCodes = array_values(array_diff($learnedKps, $existingKpCodes));
  2715. Log::info('getSupplementaryQuestionsForGrade: 无教材模式,使用学生已学知识点', [
  2716. 'learned_count' => count($learnedKps),
  2717. 'after_exclude_existing' => count($gradeKpCodes),
  2718. ]);
  2719. } else {
  2720. Log::warning('getSupplementaryQuestionsForGrade: 无教材且无学生ID,无法确定学过的内容,不补充');
  2721. return [];
  2722. }
  2723. if (empty($gradeKpCodes)) {
  2724. Log::warning('getSupplementaryQuestionsForGrade: 无可用知识点,跳过补充', [
  2725. 'grade' => $grade,
  2726. 'textbook_id' => $textbookId,
  2727. 'note' => $textbookId ? '教材知识点不足' : '学生已学知识点不足或与当前选题重复',
  2728. ]);
  2729. return [];
  2730. }
  2731. // 有教材且带章节:用 textbook_chapter_knowledge_relation 由「前章节」解析知识点,再按 kp_code 选题(不用 questions.textbook_catalog_nodes_id)
  2732. $effectiveKpCodes = $gradeKpCodes;
  2733. if ($textbookId && ! empty($textbookCatalogNodeIds)) {
  2734. $allowedNodeIds = $this->getEarlierChapterNodeIds((int) $textbookId, $textbookCatalogNodeIds);
  2735. if (empty($allowedNodeIds)) {
  2736. Log::warning('getSupplementaryQuestionsForGrade: 未找到前章节节点,跳过补充');
  2737. return [];
  2738. }
  2739. $chapterKpCodes = $this->getKpCodesForCatalogChapterIds($allowedNodeIds);
  2740. if (empty($chapterKpCodes)) {
  2741. Log::warning('getSupplementaryQuestionsForGrade: 前章节在 textbook_chapter_knowledge_relation 中无知识点', [
  2742. 'allowed_node_ids' => $allowedNodeIds,
  2743. ]);
  2744. return [];
  2745. }
  2746. $effectiveKpCodes = array_values(array_intersect($gradeKpCodes, $chapterKpCodes));
  2747. if (empty($effectiveKpCodes)) {
  2748. Log::warning('getSupplementaryQuestionsForGrade: 教材年级知识点与章节关联知识点无交集', [
  2749. 'grade_kp_count' => count($gradeKpCodes),
  2750. 'chapter_kp_count' => count($chapterKpCodes),
  2751. ]);
  2752. return [];
  2753. }
  2754. Log::info('getSupplementaryQuestionsForGrade: 按章节关联知识点缩小补充范围', [
  2755. 'allowed_chapter_nodes' => count($allowedNodeIds),
  2756. 'chapter_kp_count' => count($chapterKpCodes),
  2757. 'effective_kp_count' => count($effectiveKpCodes),
  2758. ]);
  2759. }
  2760. // 查询同年级其他知识点的题目
  2761. $query = \App\Models\Question::query();
  2762. // 只获取审核通过的题目
  2763. $query->where('audit_status', 0);
  2764. // 【新增】排除学生已做过的题目
  2765. if (!empty($excludeQuestionIds)) {
  2766. $query->whereNotIn('id', $excludeQuestionIds);
  2767. }
  2768. $stageGrade = $this->normalizeQuestionStageGrade($grade);
  2769. if ($stageGrade !== null) {
  2770. $query->where('grade', $stageGrade);
  2771. Log::info('getSupplementaryQuestionsForGrade: 应用学段筛选', [
  2772. 'input_grade' => $grade,
  2773. 'stage_grade' => $stageGrade
  2774. ]);
  2775. }
  2776. // 排除已选知识点
  2777. if (!empty($existingKpCodes)) {
  2778. $query->whereNotIn('kp_code', $existingKpCodes);
  2779. }
  2780. $query->whereIn('kp_code', $effectiveKpCodes);
  2781. // 筛选有解题思路的题目
  2782. $query->whereNotNull('solution')
  2783. ->where('solution', '!=', '')
  2784. ->where('solution', '!=', '[]');
  2785. // 【重要】移除题目分类限制,允许补充其他分类的题目
  2786. // $query->where('question_category', 1); // 移除这行
  2787. // 根据难度类别调整查询
  2788. $difficultyRanges = $this->getDifficultyRangesForCategory($difficultyCategory);
  2789. $query->where(function ($q) use ($difficultyRanges) {
  2790. foreach ($difficultyRanges as $range) {
  2791. $q->orWhereBetween('difficulty', [$range['min'], $range['max']]);
  2792. }
  2793. });
  2794. // 随机排序,增加多样性
  2795. $query->inRandomOrder()
  2796. ->limit($needCount * 2); // 多取一些,后续筛选
  2797. $supplementaryQuestions = $query->get();
  2798. Log::info('getSupplementaryQuestionsForGrade: 查询完成', [
  2799. 'found_count' => $supplementaryQuestions->count(),
  2800. 'need_count' => $needCount
  2801. ]);
  2802. // 格式化题目
  2803. $formatted = [];
  2804. foreach ($supplementaryQuestions as $question) {
  2805. // 优先使用题库原始题型
  2806. $stem = $question->stem ?? '';
  2807. $options = is_array($question->options) ? $question->options : (json_decode($question->options ?? '[]', true) ?: []);
  2808. $correctAnswer = $question->correct_answer ?? '';
  2809. $questionType = $question->question_type ?? 'answer';
  2810. $formatted[] = [
  2811. 'id' => $question->id,
  2812. 'question_bank_id' => $question->id,
  2813. 'question_type' => $questionType,
  2814. 'kp_code' => $question->kp_code,
  2815. 'difficulty' => $question->difficulty !== null ? (float) $question->difficulty : 0.5,
  2816. 'stem' => $stem,
  2817. 'options' => $options,
  2818. 'correct_answer' => $correctAnswer,
  2819. 'solution' => $question->solution,
  2820. 'score' => $question->score ?? 4,
  2821. 'estimated_time' => $question->estimated_time ?? 300,
  2822. 'metadata' => [
  2823. 'question_type_label' => $questionType === 'choice' ? '选择题' : ($questionType === 'fill' ? '填空题' : '解答题'),
  2824. 'difficulty_label' => $this->getDifficultyLabelFromObject($question->difficulty ?? 0.5),
  2825. 'is_supplementary' => true
  2826. ]
  2827. ];
  2828. }
  2829. // 随机选择需要的数量
  2830. shuffle($formatted);
  2831. $selected = array_slice($formatted, 0, $needCount);
  2832. Log::info('getSupplementaryQuestionsForGrade: 补充完成', [
  2833. 'supplementary_count' => count($selected),
  2834. 'kp_distribution' => array_count_values(array_column($selected, 'kp_code'))
  2835. ]);
  2836. return $selected;
  2837. } catch (\Exception $e) {
  2838. Log::error('getSupplementaryQuestionsForGrade: 补充失败', [
  2839. 'grade' => $grade,
  2840. 'need_count' => $needCount,
  2841. 'error' => $e->getMessage()
  2842. ]);
  2843. return [];
  2844. }
  2845. }
  2846. /**
  2847. * 获取同教材中「当前选中章节及之前」的节点 ID 列表(用于前章节补充,避免未学章节)
  2848. *
  2849. * @param int $textbookId 教材ID
  2850. * @param array $chapterNodeIds 当前选中的章节节点ID
  2851. * @return array 允许的节点ID列表(sort_order <= 选中章节的最大 sort_order)
  2852. */
  2853. private function getEarlierChapterNodeIds(int $textbookId, array $chapterNodeIds): array
  2854. {
  2855. if (empty($chapterNodeIds)) {
  2856. return [];
  2857. }
  2858. try {
  2859. $maxSortOrder = DB::table('textbook_catalog_nodes')
  2860. ->where('textbook_id', $textbookId)
  2861. ->whereIn('id', $chapterNodeIds)
  2862. ->max('sort_order');
  2863. if ($maxSortOrder === null) {
  2864. Log::warning('getEarlierChapterNodeIds: 未找到选中章节的 sort_order', [
  2865. 'textbook_id' => $textbookId,
  2866. 'chapter_node_ids' => $chapterNodeIds
  2867. ]);
  2868. return [];
  2869. }
  2870. $allowedNodeIds = DB::table('textbook_catalog_nodes')
  2871. ->where('textbook_id', $textbookId)
  2872. ->where('sort_order', '<=', $maxSortOrder)
  2873. ->pluck('id')
  2874. ->toArray();
  2875. Log::info('getEarlierChapterNodeIds: 前章节节点', [
  2876. 'textbook_id' => $textbookId,
  2877. 'max_sort_order' => $maxSortOrder,
  2878. 'allowed_node_count' => count($allowedNodeIds)
  2879. ]);
  2880. return $allowedNodeIds;
  2881. } catch (\Exception $e) {
  2882. Log::error('getEarlierChapterNodeIds: 查询失败', [
  2883. 'textbook_id' => $textbookId,
  2884. 'error' => $e->getMessage()
  2885. ]);
  2886. return [];
  2887. }
  2888. }
  2889. /**
  2890. * 获取指定年级的知识点列表
  2891. *
  2892. * @param int $grade 年级
  2893. * @param int|null $textbookId 教材ID(可选,用于限制在特定教材范围内,避免超纲)
  2894. * @return array 知识点代码列表
  2895. */
  2896. /**
  2897. * 获取学生「已学知识点」:通过该学生做过的题目(paper_questions)对应的 kp_code 推断
  2898. * 用于无教材信息时,智能补充仅从已学知识点中选,避免出现未学内容
  2899. *
  2900. * @param string|null $studentId 学生ID
  2901. * @return array 知识点代码列表(去重、非空)
  2902. */
  2903. private function getStudentLearnedKpCodes(?string $studentId): array
  2904. {
  2905. if (empty($studentId)) {
  2906. return [];
  2907. }
  2908. try {
  2909. $questionBankIds = \App\Models\PaperQuestion::query()
  2910. ->whereHas('paper', fn($q) => $q->where('student_id', $studentId))
  2911. ->pluck('question_bank_id')
  2912. ->unique()
  2913. ->filter()
  2914. ->values()
  2915. ->toArray();
  2916. if (empty($questionBankIds)) {
  2917. Log::info('getStudentLearnedKpCodes: 学生暂无做题记录', ['student_id' => $studentId]);
  2918. return [];
  2919. }
  2920. $kpCodes = \App\Models\Question::query()
  2921. ->whereIn('id', $questionBankIds)
  2922. ->whereNotNull('kp_code')
  2923. ->where('kp_code', '!=', '')
  2924. ->pluck('kp_code')
  2925. ->unique()
  2926. ->values()
  2927. ->toArray();
  2928. Log::info('getStudentLearnedKpCodes: 已学知识点', [
  2929. 'student_id' => $studentId,
  2930. 'kp_count' => count($kpCodes),
  2931. ]);
  2932. return $kpCodes;
  2933. } catch (\Exception $e) {
  2934. Log::error('getStudentLearnedKpCodes: 查询失败', [
  2935. 'student_id' => $studentId,
  2936. 'error' => $e->getMessage(),
  2937. ]);
  2938. return [];
  2939. }
  2940. }
  2941. /**
  2942. * 由 catalog 章节节点 ID 列表,从 textbook_chapter_knowledge_relation 取关联的知识点编码(用于选题,而非题目表上的章节字段)。
  2943. *
  2944. * @param array<int> $catalogChapterIds textbook_catalog_nodes.id
  2945. * @return list<string>
  2946. */
  2947. private function getKpCodesForCatalogChapterIds(array $catalogChapterIds): array
  2948. {
  2949. $ids = array_values(array_unique(array_filter(array_map(
  2950. static fn ($id) => (int) $id,
  2951. $catalogChapterIds
  2952. ), static fn (int $id) => $id > 0)));
  2953. if ($ids === []) {
  2954. return [];
  2955. }
  2956. return array_values(array_filter(array_unique(DB::table('textbook_chapter_knowledge_relation')
  2957. ->whereIn('catalog_chapter_id', $ids)
  2958. ->where(function ($q) {
  2959. $q->where('is_deleted', 0)->orWhereNull('is_deleted');
  2960. })
  2961. ->pluck('kp_code')
  2962. ->toArray())));
  2963. }
  2964. private function getGradeKnowledgePoints(int $grade, ?int $textbookId = null): array
  2965. {
  2966. try {
  2967. $query = DB::table('textbook_chapter_knowledge_relation as tckr')
  2968. ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
  2969. ->join('textbooks as t', 'tcn.textbook_id', '=', 't.id')
  2970. ->where('t.grade', $grade)
  2971. ->where(function ($q) {
  2972. $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
  2973. });
  2974. // 【修复超纲问题】如果有 textbook_id,严格限制在该教材范围内
  2975. // 避免七年级上册学生拿到七年级下册的知识点
  2976. if ($textbookId) {
  2977. $query->where('t.id', $textbookId);
  2978. Log::info('getGradeKnowledgePoints: 限制在指定教材范围内', [
  2979. 'grade' => $grade,
  2980. 'textbook_id' => $textbookId
  2981. ]);
  2982. }
  2983. $kpCodes = $query->distinct()
  2984. ->pluck('tckr.kp_code')
  2985. ->toArray();
  2986. Log::info('getGradeKnowledgePoints: 获取知识点完成', [
  2987. 'grade' => $grade,
  2988. 'textbook_id' => $textbookId,
  2989. 'kp_count' => count($kpCodes)
  2990. ]);
  2991. return array_filter($kpCodes);
  2992. } catch (\Exception $e) {
  2993. Log::error('getGradeKnowledgePoints: 查询失败', [
  2994. 'grade' => $grade,
  2995. 'textbook_id' => $textbookId,
  2996. 'error' => $e->getMessage()
  2997. ]);
  2998. return [];
  2999. }
  3000. }
  3001. /**
  3002. * 【新增】根据难度类别获取难度范围
  3003. */
  3004. private function getDifficultyRangesForCategory(int $difficultyCategory): array
  3005. {
  3006. return match($difficultyCategory) {
  3007. 1 => [
  3008. ['min' => 0.0, 'max' => 0.5], // 基础型:偏向低难度
  3009. ['min' => 0.5, 'max' => 1.0],
  3010. ],
  3011. 2 => [
  3012. ['min' => 0.0, 'max' => 0.5], // 进阶型:均衡分布
  3013. ['min' => 0.5, 'max' => 1.0],
  3014. ],
  3015. 3 => [
  3016. ['min' => 0.25, 'max' => 0.75], // 中等型:偏向中等难度
  3017. ['min' => 0.0, 'max' => 1.0],
  3018. ],
  3019. 4 => [
  3020. ['min' => 0.5, 'max' => 1.0], // 拔高型:偏向高难度
  3021. ['min' => 0.0, 'max' => 0.5],
  3022. ],
  3023. default => [
  3024. ['min' => 0.0, 'max' => 1.0],
  3025. ]
  3026. };
  3027. }
  3028. private function normalizeQuestionStageGrade(int $grade): ?int
  3029. {
  3030. if ($grade <= 0) {
  3031. return null;
  3032. }
  3033. // 年级转学段 todo:下一步需要视频小学
  3034. return $grade <= 9 ? 2 : 3;
  3035. }
  3036. /**
  3037. * 【新增】获取难度标签(重载版本)
  3038. */
  3039. private function getDifficultyLabelFromObject(?float $difficulty): string
  3040. {
  3041. if ($difficulty === null) return '未知';
  3042. if ($difficulty < 0.3) return '基础';
  3043. if ($difficulty < 0.7) return '中等';
  3044. return '拔高';
  3045. }
  3046. private function buildDifficultyDistributionStats(array $questions, int $difficultyCategory): array
  3047. {
  3048. if (empty($questions)) {
  3049. return [];
  3050. }
  3051. $service = app(DifficultyDistributionService::class);
  3052. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3053. $total = max(1, count($questions));
  3054. return array_map(static function ($bucket) use ($total) {
  3055. $count = count($bucket);
  3056. return [
  3057. 'count' => $count,
  3058. 'ratio' => round(($count / $total) * 100, 2),
  3059. ];
  3060. }, $buckets);
  3061. }
  3062. private function buildDifficultyDistributionShortage(array $questions, int $difficultyCategory, int $totalQuestions): array
  3063. {
  3064. $service = app(DifficultyDistributionService::class);
  3065. $distribution = $service->calculateDistribution($difficultyCategory, $totalQuestions);
  3066. $buckets = $service->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  3067. $expected = [
  3068. 'primary_low' => 0,
  3069. 'primary_medium' => 0,
  3070. 'primary_high' => 0,
  3071. 'secondary' => 0,
  3072. 'other' => 0,
  3073. ];
  3074. foreach ($distribution as $level => $config) {
  3075. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3076. $expected[$bucketKey] += (int) ($config['count'] ?? 0);
  3077. }
  3078. $actual = array_map(static fn($bucket) => count($bucket), $buckets);
  3079. $shortage = [];
  3080. foreach ($expected as $bucketKey => $count) {
  3081. $actualCount = $actual[$bucketKey] ?? 0;
  3082. $shortage[$bucketKey] = [
  3083. 'expected' => $count,
  3084. 'actual' => $actualCount,
  3085. 'short' => max(0, $count - $actualCount),
  3086. ];
  3087. }
  3088. return $shortage;
  3089. }
  3090. /**
  3091. * 题型感知的难度分布选题
  3092. * 在每种题型内部应用难度分布,确保题型比例和难度分布同时被满足
  3093. */
  3094. private function applyTypeAwareDifficultyDistribution(
  3095. array $allQuestions,
  3096. array $selectedQuestions,
  3097. int $totalQuestions,
  3098. int $difficultyCategory,
  3099. array $questionTypeRatio
  3100. ): array {
  3101. $diffService = app(DifficultyDistributionService::class);
  3102. $distribution = $diffService->calculateDistribution($difficultyCategory, $totalQuestions);
  3103. // 1. 计算每种题型的目标数量
  3104. $ratioMap = ['choice' => '选择题', 'fill' => '填空题', 'answer' => '解答题'];
  3105. $totalRatio = array_sum($questionTypeRatio) ?: 100;
  3106. $typeTargets = [];
  3107. $fractions = [];
  3108. $allocated = 0;
  3109. foreach ($ratioMap as $type => $ratioKey) {
  3110. $ratio = $questionTypeRatio[$ratioKey] ?? 0;
  3111. $exact = $totalQuestions * $ratio / $totalRatio;
  3112. $typeTargets[$type] = (int) floor($exact);
  3113. $fractions[$type] = $exact - floor($exact);
  3114. $allocated += $typeTargets[$type];
  3115. }
  3116. $remainder = $totalQuestions - $allocated;
  3117. arsort($fractions);
  3118. foreach ($fractions as $type => $frac) {
  3119. if ($remainder <= 0) break;
  3120. $typeTargets[$type]++;
  3121. $remainder--;
  3122. }
  3123. // 2. 构建候选题池(合并 allQuestions + selectedQuestions 去重)
  3124. $candidatePool = [];
  3125. $seen = [];
  3126. foreach (array_merge($allQuestions, $selectedQuestions) as $q) {
  3127. $id = $q['id'] ?? null;
  3128. if ($id && !isset($seen[$id])) {
  3129. $seen[$id] = true;
  3130. $candidatePool[] = $q;
  3131. }
  3132. }
  3133. // 3. 按题型分组候选题
  3134. $candidatesByType = ['choice' => [], 'fill' => [], 'answer' => []];
  3135. foreach ($candidatePool as $q) {
  3136. $qType = $q['question_type'] ?? '';
  3137. if (isset($candidatesByType[$qType])) {
  3138. $candidatesByType[$qType][] = $q;
  3139. }
  3140. }
  3141. // 4. 在每种题型内按难度分桶选题
  3142. $result = [];
  3143. $usedIds = [];
  3144. $typeActual = [];
  3145. foreach ($ratioMap as $type => $ratioKey) {
  3146. $target = $typeTargets[$type];
  3147. if ($target <= 0) {
  3148. $typeActual[$type] = 0;
  3149. continue;
  3150. }
  3151. $typeCandidates = $candidatesByType[$type];
  3152. $buckets = $diffService->groupQuestionsByDifficultyRange($typeCandidates, $difficultyCategory);
  3153. // 按 distribution 比例在该题型内选题
  3154. $typeSelected = [];
  3155. foreach ($distribution as $level => $config) {
  3156. $levelRatio = $config['percentage'];
  3157. $levelTarget = max(0, (int) round($target * $levelRatio / 100));
  3158. if ($levelTarget <= 0) continue;
  3159. $rangeKey = $diffService->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3160. $bucket = $buckets[$rangeKey] ?? [];
  3161. shuffle($bucket);
  3162. $taken = 0;
  3163. foreach ($bucket as $q) {
  3164. if ($taken >= $levelTarget) break;
  3165. $qid = $q['id'] ?? null;
  3166. if ($qid && !isset($usedIds[$qid])) {
  3167. $typeSelected[] = $q;
  3168. $usedIds[$qid] = true;
  3169. $taken++;
  3170. }
  3171. }
  3172. }
  3173. // 如果难度分布不满足目标数,从该题型剩余题目补充
  3174. if (count($typeSelected) < $target) {
  3175. $allTypeBuckets = array_merge(
  3176. $buckets['primary_medium'] ?? [],
  3177. $buckets['primary_low'] ?? [],
  3178. $buckets['primary_high'] ?? [],
  3179. $buckets['secondary'] ?? [],
  3180. $buckets['other'] ?? []
  3181. );
  3182. shuffle($allTypeBuckets);
  3183. foreach ($allTypeBuckets as $q) {
  3184. if (count($typeSelected) >= $target) break;
  3185. $qid = $q['id'] ?? null;
  3186. if ($qid && !isset($usedIds[$qid])) {
  3187. $typeSelected[] = $q;
  3188. $usedIds[$qid] = true;
  3189. }
  3190. }
  3191. }
  3192. $typeActual[$type] = count($typeSelected);
  3193. $result = array_merge($result, $typeSelected);
  3194. }
  3195. // 5. 如果总数不足(某题型候选不够),跨题型补充
  3196. if (count($result) < $totalQuestions) {
  3197. $deficit = $totalQuestions - count($result);
  3198. // 按 fill > choice > answer 优先级补充
  3199. $supplementOrder = ['fill', 'choice', 'answer'];
  3200. foreach ($supplementOrder as $type) {
  3201. if ($deficit <= 0) break;
  3202. $bucket = $candidatesByType[$type];
  3203. shuffle($bucket);
  3204. foreach ($bucket as $q) {
  3205. if ($deficit <= 0) break;
  3206. $qid = $q['id'] ?? null;
  3207. if ($qid && !isset($usedIds[$qid])) {
  3208. $result[] = $q;
  3209. $usedIds[$qid] = true;
  3210. $deficit--;
  3211. }
  3212. }
  3213. }
  3214. }
  3215. Log::info('LearningAnalyticsService: 题型感知难度分布详情', [
  3216. 'type_targets' => $typeTargets,
  3217. 'type_actual' => $typeActual,
  3218. 'total_result' => count($result),
  3219. 'difficulty_category' => $difficultyCategory,
  3220. 'candidates_by_type' => array_map('count', $candidatesByType),
  3221. ]);
  3222. return array_slice($result, 0, $totalQuestions);
  3223. }
  3224. /**
  3225. * 统计题目列表中各题型的数量
  3226. */
  3227. private function countByType(array $questions): array
  3228. {
  3229. $counts = ['choice' => 0, 'fill' => 0, 'answer' => 0];
  3230. foreach ($questions as $q) {
  3231. $type = $q['question_type'] ?? '';
  3232. if (isset($counts[$type])) {
  3233. $counts[$type]++;
  3234. }
  3235. }
  3236. return $counts;
  3237. }
  3238. private function buildDistributionCandidates(array $allQuestions, array $selectedQuestions, int $difficultyCategory): array
  3239. {
  3240. if (empty($allQuestions)) {
  3241. return $selectedQuestions;
  3242. }
  3243. $service = app(DifficultyDistributionService::class);
  3244. $distribution = $service->calculateDistribution($difficultyCategory, max(1, count($selectedQuestions)));
  3245. $buckets = $service->groupQuestionsByDifficultyRange($allQuestions, $difficultyCategory);
  3246. $preferredBuckets = [];
  3247. foreach ($distribution as $level => $config) {
  3248. $bucketKey = $service->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  3249. $preferredBuckets[$bucketKey] = true;
  3250. }
  3251. $candidates = [];
  3252. foreach (array_keys($preferredBuckets) as $bucketKey) {
  3253. foreach ($buckets[$bucketKey] ?? [] as $q) {
  3254. $candidates[] = $q;
  3255. }
  3256. }
  3257. foreach ($selectedQuestions as $q) {
  3258. $candidates[] = $q;
  3259. }
  3260. $seen = [];
  3261. $unique = [];
  3262. foreach ($candidates as $q) {
  3263. $id = $q['id'] ?? null;
  3264. if (!$id || isset($seen[$id])) {
  3265. continue;
  3266. }
  3267. $seen[$id] = true;
  3268. $unique[] = $q;
  3269. }
  3270. return $unique;
  3271. }
  3272. }