QuestionLocalService.php 29 KB

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