QuestionLocalService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. <?php
  2. namespace App\Services;
  3. use App\Models\KnowledgePoint;
  4. use App\Models\Question;
  5. use App\Services\KnowledgeServiceApi;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Facades\Cache;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Str;
  11. class QuestionLocalService
  12. {
  13. private DifficultyDistributionService $difficultyDistributionService;
  14. private QuestionDifficultyResolver $questionDifficultyResolver;
  15. public function __construct(
  16. ?DifficultyDistributionService $difficultyDistributionService = null,
  17. ?QuestionDifficultyResolver $questionDifficultyResolver = null
  18. )
  19. {
  20. $this->difficultyDistributionService = $difficultyDistributionService
  21. ?? app(DifficultyDistributionService::class);
  22. $this->questionDifficultyResolver = $questionDifficultyResolver
  23. ?? app(QuestionDifficultyResolver::class);
  24. }
  25. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  26. {
  27. $query = $this->applyFilters(Question::query(), $filters);
  28. $paginator = $query->orderByDesc('id')->paginate($perPage, ['*'], 'page', $page);
  29. $data = $this->mapQuestions(collect($paginator->items()));
  30. return [
  31. 'data' => $data,
  32. 'meta' => [
  33. 'page' => $paginator->currentPage(),
  34. 'per_page' => $paginator->perPage(),
  35. 'total' => $paginator->total(),
  36. 'total_pages' => $paginator->lastPage(),
  37. ],
  38. ];
  39. }
  40. public function getQuestionById(int $id): ?array
  41. {
  42. $question = Question::find($id);
  43. if (!$question) {
  44. return null;
  45. }
  46. return $this->mapQuestion($question);
  47. }
  48. public function getQuestionByCode(string $questionCode): ?array
  49. {
  50. $question = Question::where('question_code', $questionCode)->first();
  51. if (!$question) {
  52. return null;
  53. }
  54. return $this->mapQuestion($question);
  55. }
  56. public function updateQuestionByCode(string $questionCode, array $payload): bool
  57. {
  58. $question = Question::where('question_code', $questionCode)->first();
  59. if (!$question) {
  60. return false;
  61. }
  62. $question->fill($this->normalizePayload($payload));
  63. $question->save();
  64. return true;
  65. }
  66. public function deleteQuestionByCode(string $questionCode): bool
  67. {
  68. $question = Question::where('question_code', $questionCode)->first();
  69. if (!$question) {
  70. return false;
  71. }
  72. $question->delete();
  73. return true;
  74. }
  75. public function deleteQuestionById(int $id): bool
  76. {
  77. $question = Question::find($id);
  78. if (!$question) {
  79. return false;
  80. }
  81. $question->delete();
  82. return true;
  83. }
  84. public function searchQuestions(string $query, int $limit = 20): array
  85. {
  86. $questions = Question::query()
  87. ->search($query)
  88. ->orderByDesc('id')
  89. ->limit($limit)
  90. ->get();
  91. return [
  92. 'data' => $this->mapQuestions($questions),
  93. ];
  94. }
  95. public function getQuestionsByIds(array $ids): array
  96. {
  97. if (empty($ids)) {
  98. return ['data' => []];
  99. }
  100. $questions = Question::query()
  101. ->whereIn('id', $ids)
  102. ->orderByDesc('id')
  103. ->get();
  104. return [
  105. 'data' => $this->mapQuestions($questions),
  106. ];
  107. }
  108. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  109. {
  110. $questions = Question::query()
  111. ->where('kp_code', $kpCode)
  112. ->orderByDesc('id')
  113. ->limit($limit)
  114. ->get();
  115. return [
  116. 'data' => $this->mapQuestions($questions),
  117. ];
  118. }
  119. public function getStatistics(array $filters = []): array
  120. {
  121. $baseQuery = $this->applyFilters(Question::query(), $filters);
  122. $total = (clone $baseQuery)->count();
  123. $byDifficulty = (clone $baseQuery)
  124. ->selectRaw('difficulty, COUNT(*) as total')
  125. ->groupBy('difficulty')
  126. ->pluck('total', 'difficulty')
  127. ->toArray();
  128. $byTypeRaw = (clone $baseQuery)
  129. ->selectRaw('question_type, COUNT(*) as total')
  130. ->groupBy('question_type')
  131. ->pluck('total', 'question_type')
  132. ->toArray();
  133. $byType = [];
  134. foreach ($byTypeRaw as $type => $count) {
  135. $label = $this->mapQuestionTypeLabel((string) $type);
  136. $byType[$label] = ($byType[$label] ?? 0) + $count;
  137. }
  138. $byKp = (clone $baseQuery)
  139. ->selectRaw('kp_code, COUNT(*) as total')
  140. ->groupBy('kp_code')
  141. ->pluck('total', 'kp_code')
  142. ->toArray();
  143. $bySource = (clone $baseQuery)
  144. ->selectRaw('source, COUNT(*) as total')
  145. ->groupBy('source')
  146. ->pluck('total', 'source')
  147. ->toArray();
  148. return [
  149. 'total' => $total,
  150. 'by_difficulty' => $byDifficulty,
  151. 'by_type' => $byType,
  152. 'by_kp' => $byKp,
  153. 'by_source' => $bySource,
  154. ];
  155. }
  156. public function generateQuestions(array $params): array
  157. {
  158. $kpCode = $params['kp_code'] ?? null;
  159. // 允许 kp_code 为空,此时从所有可用题目中选择
  160. if (!$kpCode) {
  161. // 从 params 中获取 kp_codes 数组
  162. $kpCodes = $params['kp_codes'] ?? [];
  163. if (is_string($kpCodes)) {
  164. $kpCodes = array_map('trim', explode(',', $kpCodes));
  165. }
  166. if (is_array($kpCodes) && !empty($kpCodes)) {
  167. $kpCode = $kpCodes[0]; // 使用第一个知识点
  168. } else {
  169. // 如果没有指定知识点,从数据库中随机选择一个可用的知识点
  170. $availableKp = Question::query()
  171. ->whereNotNull('kp_code')
  172. ->where('kp_code', '!=', '')
  173. ->distinct()
  174. ->pluck('kp_code')
  175. ->first();
  176. if ($availableKp) {
  177. $kpCode = $availableKp;
  178. } else {
  179. return [
  180. 'success' => false,
  181. 'message' => '系统中没有可用的题目,请先添加题目数据',
  182. ];
  183. }
  184. }
  185. }
  186. $count = max(1, (int) ($params['count'] ?? 1));
  187. $keyword = (string) ($params['keyword'] ?? '');
  188. $type = $params['type'] ?? null;
  189. $difficulty = $params['difficulty'] ?? null;
  190. $skills = $params['skills'] ?? [];
  191. $solutionService = app(AiSolutionService::class);
  192. $created = [];
  193. DB::transaction(function () use (
  194. $count,
  195. $kpCode,
  196. $keyword,
  197. $type,
  198. $difficulty,
  199. $skills,
  200. $solutionService,
  201. &$created,
  202. $params
  203. ) {
  204. for ($i = 1; $i <= $count; $i++) {
  205. $questionCode = $this->generateQuestionCode();
  206. $stemSuffix = $keyword ? "({$keyword})" : '';
  207. $stem = "【AI生成】{$kpCode} 题目 {$i}{$stemSuffix}";
  208. $options = null;
  209. $answer = null;
  210. $questionType = $type ?? 'CALCULATION';
  211. if (in_array($questionType, ['CHOICE', 'MULTIPLE_CHOICE'], true)) {
  212. $options = [
  213. ['label' => 'A', 'text' => '选项 A'],
  214. ['label' => 'B', 'text' => '选项 B'],
  215. ['label' => 'C', 'text' => '选项 C'],
  216. ['label' => 'D', 'text' => '选项 D'],
  217. ];
  218. $answer = 'A';
  219. }
  220. $solution = $solutionService->generateSolution($stem, [
  221. 'kp_code' => $kpCode,
  222. 'difficulty' => $difficulty,
  223. 'question_type' => $questionType,
  224. ]);
  225. $question = Question::create([
  226. 'question_code' => $questionCode,
  227. 'kp_code' => $kpCode,
  228. 'stem' => $stem,
  229. 'options' => $options,
  230. 'answer' => $answer,
  231. 'solution' => $solution['solution'] ?? null,
  232. 'difficulty' => $difficulty,
  233. 'source' => 'ai::local',
  234. 'question_type' => $questionType,
  235. 'meta' => [
  236. 'skills' => $skills,
  237. 'prompt_template' => $params['prompt_template'] ?? null,
  238. 'strategy' => $params['strategy'] ?? null,
  239. 'generated_at' => now()->toDateTimeString(),
  240. 'solution_steps' => $solution['steps'] ?? [],
  241. ],
  242. ]);
  243. $created[] = $this->mapQuestion($question);
  244. }
  245. });
  246. return [
  247. 'success' => true,
  248. 'message' => '生成完成',
  249. 'count' => count($created),
  250. 'data' => $created,
  251. ];
  252. }
  253. public function importQuestions(array $questions): array
  254. {
  255. if (empty($questions)) {
  256. return [
  257. 'success' => false,
  258. 'message' => '题目为空',
  259. 'count' => 0,
  260. ];
  261. }
  262. $created = 0;
  263. DB::transaction(function () use ($questions, &$created) {
  264. foreach ($questions as $payload) {
  265. $questionCode = $payload['question_code'] ?? $this->generateQuestionCode();
  266. $question = Question::firstOrNew(['question_code' => $questionCode]);
  267. $question->fill($this->normalizePayload($payload));
  268. $question->save();
  269. $created++;
  270. }
  271. });
  272. return [
  273. 'success' => true,
  274. 'message' => '导入完成',
  275. 'count' => $created,
  276. ];
  277. }
  278. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  279. {
  280. $query = Question::query();
  281. // 【新增】只获取审核通过的题目(audit_status = 0 表示合格)
  282. $query->where('audit_status', 0);
  283. if (!empty($filters['kp_codes'])) {
  284. $query->whereIn('kp_code', $filters['kp_codes']);
  285. }
  286. if (!empty($filters['skills'])) {
  287. $skills = array_values(array_filter($filters['skills']));
  288. if (!empty($skills)) {
  289. $query->where(function ($q) use ($skills) {
  290. foreach ($skills as $skill) {
  291. $q->orWhereJsonContains('meta->skills', $skill);
  292. }
  293. });
  294. }
  295. }
  296. if (!empty($filters['grade'])) {
  297. $stageGrade = $this->normalizeStageGrade((int) $filters['grade']);
  298. if ($stageGrade !== null) {
  299. $query->where('grade', $stageGrade);
  300. }
  301. }
  302. $questions = $query->get();
  303. $selected = $this->applyRatioSelection($questions, $totalQuestions, $filters);
  304. return $this->mapQuestions(collect($selected));
  305. }
  306. public function getKnowledgePointOptions(): array
  307. {
  308. return KnowledgePoint::query()
  309. ->orderBy('kp_code')
  310. ->pluck('name', 'kp_code')
  311. ->toArray();
  312. }
  313. public function getSkillNameMapping(?string $kpCode = null): array
  314. {
  315. return [];
  316. }
  317. private function applyFilters($query, array $filters)
  318. {
  319. if (!empty($filters['kp_code'])) {
  320. $query->where('kp_code', $filters['kp_code']);
  321. }
  322. if (!empty($filters['difficulty'])) {
  323. $query->where('difficulty', $filters['difficulty']);
  324. }
  325. if (!empty($filters['type'])) {
  326. $query->where('question_type', $filters['type']);
  327. }
  328. if (!empty($filters['search'])) {
  329. $query->search($filters['search']);
  330. }
  331. if (!empty($filters['grade'])) {
  332. $stageGrade = $this->normalizeStageGrade((int) $filters['grade']);
  333. if ($stageGrade !== null) {
  334. $query->where('grade', $stageGrade);
  335. }
  336. }
  337. return $query;
  338. }
  339. private function normalizeStageGrade(int $grade): ?int
  340. {
  341. if ($grade <= 0) {
  342. return null;
  343. }
  344. return $grade <= 9 ? 2 : 3;
  345. }
  346. private function normalizePayload(array $payload): array
  347. {
  348. $normalized = [
  349. 'question_code' => $payload['question_code'] ?? null,
  350. 'kp_code' => $payload['kp_code'] ?? null,
  351. 'stem' => $payload['stem'] ?? ($payload['content'] ?? ''),
  352. 'options' => $payload['options'] ?? null,
  353. 'answer' => $payload['answer'] ?? null,
  354. 'solution' => $payload['solution'] ?? null,
  355. 'difficulty' => $payload['difficulty'] ?? null,
  356. 'source' => $payload['source'] ?? null,
  357. 'tags' => $payload['tags'] ?? null,
  358. 'question_type' => $payload['question_type'] ?? ($payload['type'] ?? null),
  359. 'meta' => $payload['meta'] ?? null,
  360. ];
  361. if (isset($payload['skills'])) {
  362. $meta = $normalized['meta'] ?? [];
  363. $meta['skills'] = is_array($payload['skills'])
  364. ? $payload['skills']
  365. : array_filter(array_map('trim', explode(',', (string) $payload['skills'])));
  366. $normalized['meta'] = $meta;
  367. }
  368. return array_filter($normalized, static fn ($value) => $value !== null);
  369. }
  370. private function mapQuestions(Collection $questions): array
  371. {
  372. $kpCodes = $questions->pluck('kp_code')->filter()->unique()->values();
  373. $kpMap = $this->resolveKnowledgePointNames($kpCodes->all());
  374. return $questions->map(function (Question $question) use ($kpMap) {
  375. $data = $this->mapQuestion($question);
  376. $data['kp_name'] = $kpMap[$question->kp_code] ?? null;
  377. return $data;
  378. })->values()->all();
  379. }
  380. private function mapQuestion(Question $question): array
  381. {
  382. $meta = $question->meta ?? [];
  383. $data = [
  384. 'id' => $question->id,
  385. 'question_code' => $question->question_code,
  386. 'kp_code' => $question->kp_code,
  387. 'stem' => $question->stem,
  388. 'options' => $question->options,
  389. 'answer' => $question->answer,
  390. 'solution' => $question->solution,
  391. 'difficulty' => $question->difficulty,
  392. 'source' => $question->source,
  393. 'tags' => $question->tags,
  394. 'type' => $question->question_type,
  395. 'question_type' => $question->question_type,
  396. 'skills' => $meta['skills'] ?? [],
  397. 'meta' => $meta,
  398. 'created_at' => $question->created_at?->toDateTimeString(),
  399. 'updated_at' => $question->updated_at?->toDateTimeString(),
  400. ];
  401. return MathFormulaProcessor::processQuestionData($data);
  402. }
  403. private function generateQuestionCode(): string
  404. {
  405. return 'Q' . Str::upper(Str::random(10));
  406. }
  407. private function mapQuestionTypeLabel(string $type): string
  408. {
  409. return match (strtoupper($type)) {
  410. 'CHOICE' => '选择题',
  411. 'MULTIPLE_CHOICE' => '多选题',
  412. 'FILL_IN_THE_BLANK', 'FILL' => '填空题',
  413. 'CALCULATION', 'WORD_PROBLEM', 'ANSWER' => '解答题',
  414. 'PROOF' => '证明题',
  415. default => '其他',
  416. };
  417. }
  418. private function applyRatioSelection(Collection $questions, int $totalQuestions, array $filters): array
  419. {
  420. $questionsByType = $questions->groupBy(fn (Question $q) => $q->question_type ?? 'CALCULATION');
  421. $questionsByDifficulty = $questions->groupBy(function (Question $q) {
  422. $difficulty = (float) ($q->difficulty ?? 0);
  423. if ($difficulty <= 0.4) {
  424. return 'easy';
  425. }
  426. if ($difficulty <= 0.7) {
  427. return 'medium';
  428. }
  429. return 'hard';
  430. });
  431. $typeRatio = $filters['question_type_ratio'] ?? [];
  432. $difficultyRatio = $filters['difficulty_ratio'] ?? [];
  433. $selected = collect();
  434. if (!empty($typeRatio)) {
  435. foreach ($typeRatio as $type => $ratio) {
  436. $bucket = $questionsByType->get($type, collect());
  437. $count = (int) round($totalQuestions * (float) $ratio);
  438. $selected = $selected->merge($bucket->shuffle()->take($count));
  439. }
  440. }
  441. if (!empty($difficultyRatio)) {
  442. foreach ($difficultyRatio as $key => $ratio) {
  443. $bucketKey = $this->normalizeDifficultyKey($key);
  444. $bucket = $questionsByDifficulty->get($bucketKey, collect());
  445. $count = (int) round($totalQuestions * (float) $ratio);
  446. $selected = $selected->merge($bucket->shuffle()->take($count));
  447. }
  448. }
  449. if ($selected->isEmpty()) {
  450. return $questions->shuffle()->take($totalQuestions)->values()->all();
  451. }
  452. if ($selected->count() < $totalQuestions) {
  453. $missing = $totalQuestions - $selected->count();
  454. $fill = $questions->diff($selected)->shuffle()->take($missing);
  455. $selected = $selected->merge($fill);
  456. }
  457. return $selected->values()->all();
  458. }
  459. private function normalizeDifficultyKey(string $key): string
  460. {
  461. if (in_array($key, ['easy', 'medium', 'hard'], true)) {
  462. return $key;
  463. }
  464. $value = (float) $key;
  465. if ($value <= 0.4) {
  466. return 'easy';
  467. }
  468. if ($value <= 0.7) {
  469. return 'medium';
  470. }
  471. return 'hard';
  472. }
  473. private function resolveKnowledgePointNames(array $kpCodes): array
  474. {
  475. $kpCodes = array_values(array_filter(array_unique($kpCodes)));
  476. if (empty($kpCodes)) {
  477. return [];
  478. }
  479. $cacheKey = 'kp-name-map-' . md5(implode('|', $kpCodes));
  480. return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($kpCodes) {
  481. $kpMap = KnowledgePoint::query()
  482. ->whereIn('kp_code', $kpCodes)
  483. ->pluck('name', 'kp_code')
  484. ->toArray();
  485. $missing = array_values(array_filter($kpCodes, fn ($code) => empty($kpMap[$code])));
  486. if (empty($missing)) {
  487. return $kpMap;
  488. }
  489. try {
  490. $api = app(KnowledgeServiceApi::class);
  491. $all = $api->listKnowledgePoints();
  492. foreach ($all as $kp) {
  493. $code = $kp['kp_code'] ?? null;
  494. $name = $kp['cn_name'] ?? $kp['name'] ?? null;
  495. if ($code && $name && in_array($code, $missing, true)) {
  496. $kpMap[$code] = $name;
  497. }
  498. }
  499. } catch (\Throwable $e) {
  500. // Fallback: keep existing mapping
  501. }
  502. return $kpMap;
  503. });
  504. }
  505. /**
  506. * 根据难度系数分布选择题目
  507. *
  508. * @param array $questions 候选题目数组
  509. * @param int $totalQuestions 总题目数
  510. * @param int $difficultyCategory 难度类别 (0-4)
  511. * - 0: 0-0.1占90%,0.1-0.25占10%
  512. * - 1: 0-0.25占90%,0.25-1占10%
  513. * - 2: 0.25-0.5范围占50%,<0.25占25%,>0.5占25%
  514. * - 3: 0.5-0.75范围占50%,<0.5占25%,>0.75占25%
  515. * - 4: 0.75-1范围占50%,其他占50%
  516. * @param array $filters 其他筛选条件
  517. * @return array 分布后的题目
  518. */
  519. public function selectQuestionsByDifficultyDistribution(array $questions, int $totalQuestions, int $difficultyCategory = 1, array $filters = []): array
  520. {
  521. Log::info('QuestionLocalService: 根据难度系数分布选择题目', [
  522. 'total_questions' => $totalQuestions,
  523. 'difficulty_category' => $difficultyCategory,
  524. ]);
  525. if (empty($questions)) {
  526. Log::warning('QuestionLocalService: 输入题目为空');
  527. return [];
  528. }
  529. $questions = $this->questionDifficultyResolver->applyCalibratedDifficulty($questions);
  530. $calibratedCount = count(array_filter($questions, fn ($q) => ($q['difficulty_source'] ?? null) === 'calibrated'));
  531. Log::info('QuestionLocalService: 组卷前应用校准难度', [
  532. 'total_candidates' => count($questions),
  533. 'calibrated_candidates' => $calibratedCount,
  534. ]);
  535. $resolveQuestionId = static function (array $question): string {
  536. return (string) ($question['id'] ?? $question['question_id'] ?? $question['question_bank_id'] ?? '');
  537. };
  538. // 【恢复】简化逻辑,避免复杂处理
  539. $distribution = $this->difficultyDistributionService->calculateDistribution($difficultyCategory, $totalQuestions);
  540. // 按难度范围分桶
  541. $buckets = $this->difficultyDistributionService->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  542. Log::info('QuestionLocalService: 题目分桶', [
  543. 'buckets' => array_map(fn($bucket) => count($bucket), $buckets),
  544. 'total_input' => count($questions),
  545. 'distribution' => $distribution
  546. ]);
  547. // 根据分布选择题目
  548. $selected = [];
  549. $usedIds = [];
  550. foreach ($distribution as $level => $config) {
  551. $targetCount = $config['count'];
  552. if ($targetCount <= 0) {
  553. Log::debug('QuestionLocalService: 跳过难度层级', [
  554. 'level' => $level,
  555. 'target_count' => $targetCount
  556. ]);
  557. continue;
  558. }
  559. $rangeKey = $this->difficultyDistributionService->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  560. $bucket = $buckets[$rangeKey] ?? [];
  561. // 随机打乱
  562. shuffle($bucket);
  563. // 选择题目
  564. $taken = 0;
  565. foreach ($bucket as $question) {
  566. if ($taken >= $targetCount) break;
  567. $questionId = $resolveQuestionId($question);
  568. if ($questionId !== '' && !in_array($questionId, $usedIds, true)) {
  569. $selected[] = $question;
  570. $usedIds[] = $questionId;
  571. $taken++;
  572. }
  573. }
  574. // 【修复】如果某个难度范围题目不足,记录日志但不截断
  575. if ($taken < $targetCount) {
  576. Log::warning('QuestionLocalService: 难度范围题目不足,允许后续补充', [
  577. 'level' => $level,
  578. 'range_key' => $rangeKey,
  579. 'target' => $targetCount,
  580. 'actual' => $taken,
  581. 'bucket_size' => count($bucket)
  582. ]);
  583. }
  584. }
  585. // 如果数量不足,从剩余题目中补充
  586. if (count($selected) < $totalQuestions) {
  587. Log::warning('QuestionLocalService: 开始补充题目(难度分布无法满足要求)', [
  588. 'need_more' => $totalQuestions - count($selected),
  589. 'selected_count' => count($selected),
  590. 'difficulty_category' => $difficultyCategory,
  591. 'note' => '优先从次级桶补充,不足再放宽'
  592. ]);
  593. $needMore = $totalQuestions - count($selected);
  594. $supplemented = 0;
  595. $supplementOrder = $this->difficultyDistributionService->getSupplementOrder($difficultyCategory);
  596. foreach ($supplementOrder as $bucketKey) {
  597. if ($supplemented >= $needMore) {
  598. break;
  599. }
  600. $bucket = $buckets[$bucketKey] ?? [];
  601. if (empty($bucket)) {
  602. continue;
  603. }
  604. shuffle($bucket);
  605. foreach ($bucket as $q) {
  606. if ($supplemented >= $needMore) {
  607. break;
  608. }
  609. $id = $resolveQuestionId($q);
  610. if ($id !== '' && !in_array($id, $usedIds, true)) {
  611. $selected[] = $q;
  612. $usedIds[] = $id;
  613. $supplemented++;
  614. }
  615. }
  616. }
  617. if ($supplemented < $needMore) {
  618. $remaining = [];
  619. foreach ($questions as $q) {
  620. $id = $resolveQuestionId($q);
  621. if ($id !== '' && !in_array($id, $usedIds, true)) {
  622. $remaining[] = $q;
  623. }
  624. }
  625. shuffle($remaining);
  626. $supplementCount = min($needMore - $supplemented, count($remaining));
  627. $selected = array_merge($selected, array_slice($remaining, 0, $supplementCount));
  628. $supplemented += $supplementCount;
  629. }
  630. Log::warning('QuestionLocalService: 补充完成', [
  631. 'supplement_added' => $supplemented,
  632. 'final_count_before_truncate' => count($selected),
  633. 'remaining_unused' => max(0, count($questions) - count($selected))
  634. ]);
  635. }
  636. // 截断至目标数量
  637. $selected = array_slice($selected, 0, $totalQuestions);
  638. $finalBuckets = $this->difficultyDistributionService->groupQuestionsByDifficultyRange($selected, $difficultyCategory);
  639. $finalTotal = max(1, count($selected));
  640. $distributionStats = array_map(static function ($bucket) use ($finalTotal) {
  641. $count = count($bucket);
  642. return [
  643. 'count' => $count,
  644. 'ratio' => round(($count / $finalTotal) * 100, 2),
  645. ];
  646. }, $finalBuckets);
  647. Log::info('QuestionLocalService: 难度分布选择完成', [
  648. 'final_count' => count($selected),
  649. 'target_count' => $totalQuestions,
  650. 'success' => count($selected) === $totalQuestions,
  651. 'input_count' => count($questions),
  652. 'distribution_applied' => true,
  653. 'final_distribution' => $distributionStats
  654. ]);
  655. return $selected;
  656. }
  657. }