QuestionBankService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. class QuestionBankService
  6. {
  7. protected string $baseUrl;
  8. public function __construct()
  9. {
  10. // 从配置文件读取base_url
  11. $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
  12. $this->baseUrl = rtrim($this->baseUrl, '/');
  13. }
  14. /**
  15. * 获取题目列表
  16. */
  17. public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
  18. {
  19. try {
  20. $response = Http::timeout(10)
  21. ->get($this->baseUrl . '/questions', [
  22. 'page' => $page,
  23. 'per_page' => $perPage,
  24. ...$filters
  25. ]);
  26. if ($response->successful()) {
  27. return $response->json();
  28. }
  29. Log::warning('题库API调用失败', [
  30. 'status' => $response->status()
  31. ]);
  32. } catch (\Exception $e) {
  33. Log::error('获取题目列表失败', [
  34. 'error' => $e->getMessage()
  35. ]);
  36. }
  37. return ['data' => [], 'meta' => ['total' => 0]];
  38. }
  39. /**
  40. * 筛选题目 (支持 kp_codes, skills 等高级筛选)
  41. */
  42. public function filterQuestions(array $params): array
  43. {
  44. try {
  45. $response = Http::timeout(30)
  46. ->get($this->baseUrl . '/questions', $params);
  47. if ($response->successful()) {
  48. return $response->json();
  49. }
  50. Log::warning('筛选题目API调用失败', [
  51. 'status' => $response->status(),
  52. 'params' => $params
  53. ]);
  54. } catch (\Exception $e) {
  55. Log::error('筛选题目异常', [
  56. 'error' => $e->getMessage(),
  57. 'params' => $params
  58. ]);
  59. }
  60. return ['data' => []];
  61. }
  62. /**
  63. * 批量获取题目详情(根据题目 ID 列表)
  64. */
  65. public function getQuestionsByIds(array $ids): array
  66. {
  67. if (empty($ids)) {
  68. return ['data' => []];
  69. }
  70. try {
  71. $response = Http::timeout(15)
  72. ->get($this->baseUrl . '/questions', [
  73. 'ids' => implode(',', $ids),
  74. ]);
  75. if ($response->successful()) {
  76. return $response->json();
  77. }
  78. Log::warning('批量获取题目失败', [
  79. 'ids' => $ids,
  80. 'status' => $response->status(),
  81. ]);
  82. } catch (\Exception $e) {
  83. Log::error('批量获取题目异常', [
  84. 'ids' => $ids,
  85. 'error' => $e->getMessage(),
  86. ]);
  87. }
  88. return ['data' => []];
  89. }
  90. /**
  91. * 智能生成题目(异步模式)
  92. */
  93. public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
  94. {
  95. try {
  96. // 添加回调 URL
  97. if ($callbackUrl) {
  98. $params['callback_url'] = $callbackUrl;
  99. }
  100. $response = Http::timeout(10)
  101. ->post($this->baseUrl . '/generate-intelligent-questions', $params);
  102. if ($response->successful()) {
  103. return $response->json();
  104. }
  105. Log::warning('题目生成API调用失败', [
  106. 'status' => $response->status()
  107. ]);
  108. } catch (\Exception $e) {
  109. Log::error('题目生成异常', [
  110. 'error' => $e->getMessage()
  111. ]);
  112. }
  113. return ['success' => false, 'message' => '生成失败'];
  114. }
  115. /**
  116. * 获取任务状态
  117. */
  118. public function getTaskStatus(string $taskId): ?array
  119. {
  120. try {
  121. $response = Http::timeout(10)
  122. ->get($this->baseUrl . '/tasks/' . $taskId);
  123. if ($response->successful()) {
  124. return $response->json();
  125. }
  126. Log::warning('获取任务状态失败', [
  127. 'task_id' => $taskId,
  128. 'status' => $response->status()
  129. ]);
  130. } catch (\Exception $e) {
  131. Log::error('获取任务状态异常', [
  132. 'task_id' => $taskId,
  133. 'error' => $e->getMessage()
  134. ]);
  135. }
  136. return null;
  137. }
  138. /**
  139. * 获取任务列表
  140. */
  141. public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
  142. {
  143. try {
  144. $params = [
  145. 'page' => $page,
  146. 'per_page' => $perPage
  147. ];
  148. if ($status) {
  149. $params['status'] = $status;
  150. }
  151. $response = Http::timeout(10)
  152. ->get($this->baseUrl . '/tasks', $params);
  153. if ($response->successful()) {
  154. return $response->json();
  155. }
  156. Log::warning('获取任务列表失败', [
  157. 'status' => $response->status()
  158. ]);
  159. } catch (\Exception $e) {
  160. Log::error('获取任务列表异常', [
  161. 'error' => $e->getMessage()
  162. ]);
  163. }
  164. return ['data' => [], 'meta' => ['total' => 0]];
  165. }
  166. /**
  167. * 获取题目统计信息
  168. */
  169. public function getStatistics(): array
  170. {
  171. try {
  172. $response = Http::timeout(10)
  173. ->get($this->baseUrl . '/questions/statistics');
  174. if ($response->successful()) {
  175. return $response->json();
  176. }
  177. Log::warning('获取题目统计失败', [
  178. 'status' => $response->status()
  179. ]);
  180. } catch (\Exception $e) {
  181. Log::error('获取题目统计异常', [
  182. 'error' => $e->getMessage()
  183. ]);
  184. }
  185. return [
  186. 'total' => 0,
  187. 'by_difficulty' => [],
  188. 'by_kp' => [],
  189. 'by_source' => []
  190. ];
  191. }
  192. /**
  193. * 根据知识点获取题目
  194. */
  195. public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
  196. {
  197. try {
  198. $response = Http::timeout(10)
  199. ->get($this->baseUrl . '/questions', [
  200. 'kp_code' => $kpCode,
  201. 'limit' => $limit
  202. ]);
  203. if ($response->successful()) {
  204. return $response->json();
  205. }
  206. } catch (\Exception $e) {
  207. Log::error('根据知识点获取题目失败', [
  208. 'kp_code' => $kpCode,
  209. 'error' => $e->getMessage()
  210. ]);
  211. }
  212. return [];
  213. }
  214. /**
  215. * 删除题目
  216. */
  217. public function deleteQuestion(string $questionCode): bool
  218. {
  219. try {
  220. $response = Http::timeout(10)
  221. ->delete($this->baseUrl . "/questions/{$questionCode}");
  222. // 只有返回204(删除成功)才返回true,404(不存在)返回false
  223. if ($response->status() === 204) {
  224. return true;
  225. }
  226. if ($response->status() === 404) {
  227. Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
  228. return false;
  229. }
  230. return false;
  231. } catch (\Exception $e) {
  232. Log::error('删除题目失败', [
  233. 'question_code' => $questionCode,
  234. 'error' => $e->getMessage()
  235. ]);
  236. return false;
  237. }
  238. }
  239. /**
  240. * 智能选择试卷题目
  241. */
  242. public function selectQuestionsForExam(int $totalQuestions, array $filters): array
  243. {
  244. try {
  245. $response = Http::timeout(30)
  246. ->post($this->baseUrl . '/exam/select-questions', [
  247. 'total_questions' => $totalQuestions,
  248. 'filters' => $filters
  249. ]);
  250. if ($response->successful()) {
  251. return $response->json('data', []);
  252. }
  253. Log::warning('智能选题API调用失败', [
  254. 'status' => $response->status()
  255. ]);
  256. } catch (\Exception $e) {
  257. Log::error('智能选题异常', [
  258. 'error' => $e->getMessage()
  259. ]);
  260. }
  261. return [];
  262. }
  263. /**
  264. * 保存试卷到数据库(本地 papers 表)
  265. */
  266. public function saveExamToDatabase(array $examData): ?string
  267. {
  268. try {
  269. // 生成试卷ID
  270. $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
  271. // 保存到 papers 表
  272. \Illuminate\Support\Facades\DB::table('papers')->insert([
  273. 'paper_id' => $paperId,
  274. 'student_id' => $examData['student_id'] ?? '',
  275. 'teacher_id' => $examData['teacher_id'] ?? '',
  276. 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
  277. 'paper_type' => 'auto_generated',
  278. 'question_count' => $examData['total_questions'] ?? 0,
  279. 'total_score' => $examData['total_score'] ?? 0,
  280. 'status' => 'draft',
  281. 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
  282. 'created_at' => now(),
  283. 'updated_at' => now(),
  284. ]);
  285. // 如果有题目列表,保存到 paper_questions 表
  286. if (!empty($examData['questions'])) {
  287. foreach ($examData['questions'] as $index => $question) {
  288. // 处理难度字段:如果是字符串则转换为数字
  289. $difficultyValue = $question['difficulty'] ?? 0.5;
  290. if (is_string($difficultyValue)) {
  291. // 将中文难度转换为数字
  292. if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
  293. $difficultyValue = 0.3;
  294. } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
  295. $difficultyValue = 0.6;
  296. } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
  297. $difficultyValue = 0.9;
  298. } else {
  299. $difficultyValue = 0.5;
  300. }
  301. }
  302. // 确保 knowledge_point 有值
  303. $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
  304. if (empty($knowledgePoint) && isset($question['kp_code'])) {
  305. $knowledgePoint = $question['kp_code'];
  306. }
  307. // 获取题目类型
  308. $questionType = $question['question_type'] ?? 'answer';
  309. if (!$questionType) {
  310. // 如果没有类型,根据内容推断
  311. $content = $question['stem'] ?? $question['content'] ?? '';
  312. if (is_string($content)) {
  313. // 检查全角括号
  314. if (strpos($content, '()') !== false) {
  315. $questionType = 'choice';
  316. }
  317. // 检查半角括号
  318. elseif (strpos($content, '()') !== false) {
  319. $questionType = 'choice';
  320. }
  321. // 检查选项格式 A. B. C. D.(支持跨行匹配)
  322. elseif (preg_match('/[A-D]\.\s/m', $content)) {
  323. $questionType = 'choice';
  324. }
  325. // 检查填空题
  326. elseif (strpos($content, '____') !== false || strpos($content, '______') !== false) {
  327. $questionType = 'fill';
  328. }
  329. else {
  330. $questionType = 'answer';
  331. }
  332. } else {
  333. $questionType = 'answer';
  334. }
  335. }
  336. \Illuminate\Support\Facades\DB::table('paper_questions')->insert([
  337. 'id' => $paperId . '_q' . ($index + 1),
  338. 'paper_id' => $paperId,
  339. 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
  340. 'knowledge_point' => $knowledgePoint,
  341. 'question_type' => $questionType,
  342. 'difficulty' => $difficultyValue,
  343. 'score' => $question['score'] ?? 5, // 默认5分
  344. 'estimated_time' => $question['estimated_time'] ?? 300,
  345. 'question_number' => $index + 1,
  346. ]);
  347. }
  348. }
  349. Log::info('试卷保存成功', ['paper_id' => $paperId, 'question_count' => count($examData['questions'] ?? [])]);
  350. return $paperId;
  351. } catch (\Exception $e) {
  352. Log::error('保存试卷到数据库失败', [
  353. 'error' => $e->getMessage(),
  354. 'trace' => $e->getTraceAsString()
  355. ]);
  356. return null;
  357. }
  358. }
  359. /**
  360. * 获取试卷列表
  361. */
  362. public function listExams(int $page = 1, int $perPage = 20): array
  363. {
  364. try {
  365. $response = Http::timeout(10)
  366. ->get($this->baseUrl . '/exam/list', [
  367. 'page' => $page,
  368. 'per_page' => $perPage
  369. ]);
  370. if ($response->successful()) {
  371. return $response->json();
  372. }
  373. Log::warning('获取试卷列表失败', [
  374. 'status' => $response->status()
  375. ]);
  376. } catch (\Exception $e) {
  377. Log::error('获取试卷列表异常', [
  378. 'error' => $e->getMessage()
  379. ]);
  380. }
  381. return ['data' => [], 'meta' => ['total' => 0]];
  382. }
  383. /**
  384. * 获取试卷详情
  385. */
  386. public function getExamById(string $paperId): ?array
  387. {
  388. try {
  389. $response = Http::timeout(10)
  390. ->get($this->baseUrl . '/exam/' . $paperId);
  391. if ($response->successful()) {
  392. return $response->json();
  393. }
  394. Log::warning('获取试卷详情失败', [
  395. 'paper_id' => $paperId,
  396. 'status' => $response->status()
  397. ]);
  398. } catch (\Exception $e) {
  399. Log::error('获取试卷详情异常', [
  400. 'paper_id' => $paperId,
  401. 'error' => $e->getMessage()
  402. ]);
  403. }
  404. return null;
  405. }
  406. /**
  407. * 导出试卷为PDF
  408. */
  409. public function exportExamToPdf(string $paperId): ?string
  410. {
  411. try {
  412. $response = Http::timeout(60)
  413. ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
  414. if ($response->successful()) {
  415. // 返回PDF文件路径或URL
  416. return $response->json('pdf_url', null);
  417. }
  418. Log::warning('导出PDF失败', [
  419. 'paper_id' => $paperId,
  420. 'status' => $response->status()
  421. ]);
  422. } catch (\Exception $e) {
  423. Log::error('导出PDF异常', [
  424. 'paper_id' => $paperId,
  425. 'error' => $e->getMessage()
  426. ]);
  427. }
  428. return null;
  429. }
  430. /**
  431. * 检查服务健康状态
  432. */
  433. public function checkHealth(): bool
  434. {
  435. try {
  436. $response = Http::timeout(5)
  437. ->get($this->baseUrl . '/health');
  438. return $response->successful();
  439. } catch (\Exception $e) {
  440. Log::error('题库服务健康检查失败', [
  441. 'error' => $e->getMessage()
  442. ]);
  443. return false;
  444. }
  445. }
  446. }