QuestionLocalService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. ]);
  501. // 按难度范围分桶
  502. $buckets = $this->groupQuestionsByDifficultyRange($questions, $difficultyCategory);
  503. Log::info('QuestionLocalService: 题目分桶', [
  504. 'buckets' => array_map(fn($bucket) => count($bucket), $buckets)
  505. ]);
  506. // 根据分布选择题目
  507. $selected = [];
  508. $usedIndices = [];
  509. foreach ($distribution as $level => $config) {
  510. $targetCount = $config['count'];
  511. if ($targetCount <= 0) {
  512. continue;
  513. }
  514. $rangeKey = $this->mapDifficultyLevelToRangeKey($level, $difficultyCategory);
  515. $bucket = $buckets[$rangeKey] ?? [];
  516. // 随机打乱
  517. shuffle($bucket);
  518. // 选择题目
  519. $takeCount = min($targetCount, count($bucket));
  520. for ($i = 0; $i < $takeCount; $i++) {
  521. if (isset($bucket[$i])) {
  522. $selected[] = $bucket[$i];
  523. $usedIndices[] = $bucket[$i]['id'] ?? $i;
  524. }
  525. }
  526. Log::debug('QuestionLocalService: 难度层级选择', [
  527. 'level' => $level,
  528. 'target' => $targetCount,
  529. 'actual' => $takeCount,
  530. 'bucket_size' => count($bucket)
  531. ]);
  532. }
  533. // 如果数量不足,从剩余题目中补充
  534. if (count($selected) < $totalQuestions) {
  535. $remaining = [];
  536. foreach ($questions as $q) {
  537. $id = $q['id'] ?? null;
  538. if ($id && !in_array($id, $usedIndices)) {
  539. $remaining[] = $q;
  540. }
  541. }
  542. shuffle($remaining);
  543. $needMore = $totalQuestions - count($selected);
  544. $selected = array_merge($selected, array_slice($remaining, 0, $needMore));
  545. }
  546. // 截断至目标数量
  547. $selected = array_slice($selected, 0, $totalQuestions);
  548. Log::info('QuestionLocalService: 难度分布选择完成', [
  549. 'final_count' => count($selected),
  550. 'target_count' => $totalQuestions
  551. ]);
  552. return $selected;
  553. }
  554. /**
  555. * 计算难度分布配置
  556. *
  557. * @param int $category 难度类别 (1-4)
  558. * @param int $totalQuestions 总题目数
  559. * @return array 分布配置
  560. */
  561. private function calculateDifficultyDistribution(int $category, int $totalQuestions): array
  562. {
  563. // 标准化:25% 低级,50% 基准,25% 拔高
  564. $lowPercentage = 25;
  565. $mediumPercentage = 50;
  566. $highPercentage = 25;
  567. // 根据难度类别调整分布
  568. switch ($category) {
  569. case 1:
  570. // 基础型:0-0.25占50%,其他占50%
  571. $mediumPercentage = 50; // 0-0.25作为基准
  572. $lowPercentage = 25; // 其他低难度
  573. $highPercentage = 25; // 其他高难度
  574. break;
  575. case 2:
  576. // 进阶型:0.25-0.5占50%,<0.25占25%,>0.5占25%
  577. $mediumPercentage = 50; // 0.25-0.5作为基准
  578. $lowPercentage = 25; // <0.25
  579. $highPercentage = 25; // >0.5
  580. break;
  581. case 3:
  582. // 中等型:0.5-0.75占50%,<0.5占25%,>0.75占25%
  583. $mediumPercentage = 50; // 0.5-0.75作为基准
  584. $lowPercentage = 25; // <0.5
  585. $highPercentage = 25; // >0.75
  586. break;
  587. case 4:
  588. // 拔高型:0.75-1占50%,其他占50%
  589. $mediumPercentage = 50; // 0.75-1作为基准
  590. $lowPercentage = 25; // 其他低难度
  591. $highPercentage = 25; // 其他高难度
  592. break;
  593. }
  594. // 计算题目数量
  595. $lowCount = (int) round($totalQuestions * $lowPercentage / 100);
  596. $mediumCount = (int) round($totalQuestions * $mediumPercentage / 100);
  597. $highCount = $totalQuestions - $lowCount - $mediumCount;
  598. return [
  599. 'low' => [
  600. 'percentage' => $lowPercentage,
  601. 'count' => $lowCount,
  602. 'label' => '低级难度'
  603. ],
  604. 'medium' => [
  605. 'percentage' => $mediumPercentage,
  606. 'count' => $mediumCount,
  607. 'label' => '基准难度'
  608. ],
  609. 'high' => [
  610. 'percentage' => $highPercentage,
  611. 'count' => $highCount,
  612. 'label' => '拔高难度'
  613. ]
  614. ];
  615. }
  616. /**
  617. * 将题目按难度范围分桶
  618. *
  619. * @param array $questions 题目数组
  620. * @param int $category 难度类别
  621. * @return array 分桶结果
  622. */
  623. private function groupQuestionsByDifficultyRange(array $questions, int $category): array
  624. {
  625. $buckets = [
  626. 'primary_low' => [], // 主要低难度范围
  627. 'primary_medium' => [], // 主要中等难度范围
  628. 'primary_high' => [], // 主要高难度范围
  629. 'secondary' => [], // 次要范围
  630. 'other' => [] // 其他
  631. ];
  632. foreach ($questions as $question) {
  633. $difficulty = (float) ($question['difficulty'] ?? 0);
  634. $rangeKey = $this->classifyQuestionByDifficulty($difficulty, $category);
  635. $buckets[$rangeKey][] = $question;
  636. }
  637. return $buckets;
  638. }
  639. /**
  640. * 根据难度值和类别分类题目
  641. *
  642. * @param float $difficulty 难度值 (0-1)
  643. * @param int $category 难度类别 (1-4)
  644. * @return string 范围键
  645. */
  646. private function classifyQuestionByDifficulty(float $difficulty, int $category): string
  647. {
  648. switch ($category) {
  649. case 1:
  650. // 基础型:0-0.25作为主要中等,0.25-1作为其他
  651. if ($difficulty >= 0 && $difficulty <= 0.25) {
  652. return 'primary_medium';
  653. }
  654. return 'other';
  655. case 2:
  656. // 进阶型:0.25-0.5作为主要中等,<0.25作为主要低,>0.5作为主要高
  657. if ($difficulty >= 0.25 && $difficulty <= 0.5) {
  658. return 'primary_medium';
  659. } elseif ($difficulty < 0.25) {
  660. return 'primary_low';
  661. }
  662. return 'primary_high';
  663. case 3:
  664. // 中等型:0.5-0.75作为主要中等,<0.5作为主要低,>0.75作为主要高
  665. if ($difficulty >= 0.5 && $difficulty <= 0.75) {
  666. return 'primary_medium';
  667. } elseif ($difficulty < 0.5) {
  668. return 'primary_low';
  669. }
  670. return 'primary_high';
  671. case 4:
  672. // 拔高型:0.75-1作为主要中等,0-0.75作为其他
  673. if ($difficulty >= 0.75 && $difficulty <= 1.0) {
  674. return 'primary_medium';
  675. }
  676. return 'other';
  677. default:
  678. return 'other';
  679. }
  680. }
  681. /**
  682. * 将难度层级映射到范围键
  683. *
  684. * @param string $level 难度层级 (low/medium/high)
  685. * @param int $category 难度类别
  686. * @return string 范围键
  687. */
  688. private function mapDifficultyLevelToRangeKey(string $level, int $category): string
  689. {
  690. // 根据类别和层级确定范围键
  691. switch ($category) {
  692. case 1:
  693. return match($level) {
  694. 'low' => 'other',
  695. 'medium' => 'primary_medium',
  696. 'high' => 'other',
  697. default => 'other'
  698. };
  699. case 2:
  700. return match($level) {
  701. 'low' => 'primary_low',
  702. 'medium' => 'primary_medium',
  703. 'high' => 'primary_high',
  704. default => 'other'
  705. };
  706. case 3:
  707. return match($level) {
  708. 'low' => 'primary_low',
  709. 'medium' => 'primary_medium',
  710. 'high' => 'primary_high',
  711. default => 'other'
  712. };
  713. case 4:
  714. return match($level) {
  715. 'low' => 'other',
  716. 'medium' => 'primary_medium',
  717. 'high' => 'other',
  718. default => 'other'
  719. };
  720. default:
  721. return 'other';
  722. }
  723. }
  724. }