| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082 |
- <?php
- namespace App\Services;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Log;
- class QuestionBankService
- {
- protected string $baseUrl;
- public function __construct()
- {
- // 从配置文件读取base_url
- $this->baseUrl = config('services.question_bank.base_url', env('QUESTION_BANK_API_BASE', 'http://localhost:5015'));
- $this->baseUrl = rtrim($this->baseUrl, '/');
- }
- /**
- * 从题目内容中提取选项
- */
- private function extractOptions(string $content): array
- {
- // 匹配 A. B. C. D. 格式的选项
- if (preg_match_all('/([A-D])\.\s*(.+?)(?=[A-D]\.|$)/s', $content, $matches, PREG_SET_ORDER)) {
- $options = [];
- foreach ($matches as $match) {
- $optionText = trim($match[2]);
- // 移除末尾的换行和空白
- $optionText = preg_replace('/\s+$/', '', $optionText);
- $options[] = $optionText;
- }
- return $options;
- }
- return [];
- }
- /**
- * 分离题干内容和选项
- */
- private function separateStemAndOptions(string $content): array
- {
- // 如果没有选项,直接返回
- if (!preg_match('/[A-D]\.\s+/m', $content)) {
- return [$content, []];
- }
- // 提取选项
- $options = $this->extractOptions($content);
- // 提取题干(选项前的部分)
- $stem = preg_replace('/[A-D]\.\s+.+?(?=[A-D]\.|$)/s', '', $content);
- $stem = trim($stem);
- // 移除末尾的括号或空白
- $stem = preg_replace('/()\s*$/', '', $stem);
- $stem = trim($stem);
- return [$stem, $options];
- }
- /**
- * 获取题目列表
- */
- public function listQuestions(int $page = 1, int $perPage = 50, array $filters = []): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions', [
- 'page' => $page,
- 'per_page' => $perPage,
- ...$filters
- ]);
- if ($response->successful()) {
- info("QuestionBankService::listQuestions", [$response->json()]);
- return $response->json();
- }
- Log::warning('题库API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目列表失败', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取题目详情
- */
- public function getQuestion(string $questionCode): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . "/questions/{$questionCode}");
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取题目详情失败', [
- 'code' => $questionCode,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目详情异常', [
- 'code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 更新题目
- */
- public function updateQuestion(string $questionCode, array $payload): bool
- {
- try {
- $response = Http::timeout(10)
- ->patch($this->baseUrl . "/questions/{$questionCode}", $payload);
- if ($response->successful()) {
- return true;
- }
- Log::warning('更新题目失败', [
- 'code' => $questionCode,
- 'status' => $response->status(),
- 'body' => $response->json(),
- ]);
- } catch (\Exception $e) {
- Log::error('更新题目异常', [
- 'code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- }
- return false;
- }
- /**
- * 筛选题目 (支持 kp_codes, skills 等高级筛选)
- */
- public function filterQuestions(array $params): array
- {
- try {
- $response = Http::timeout(30)
- ->get($this->baseUrl . '/questions', $params);
- if ($response->successful()) {
- info("QuestionBankService::filterQuestions", [$response->json()]);
- return $response->json();
- }
- Log::warning('筛选题目API调用失败', [
- 'status' => $response->status(),
- 'params' => $params
- ]);
- } catch (\Exception $e) {
- Log::error('筛选题目异常', [
- 'error' => $e->getMessage(),
- 'params' => $params
- ]);
- }
- return ['data' => []];
- }
- /**
- * 批量获取题目详情(根据题目 ID 列表)
- */
- public function getQuestionsByIds(array $ids): array
- {
- if (empty($ids)) {
- return ['data' => []];
- }
- try {
- $response = Http::timeout(15)
- ->get($this->baseUrl . '/questions', [
- 'ids' => implode(',', $ids),
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('批量获取题目失败', [
- 'ids' => $ids,
- 'status' => $response->status(),
- ]);
- } catch (\Exception $e) {
- Log::error('批量获取题目异常', [
- 'ids' => $ids,
- 'error' => $e->getMessage(),
- ]);
- }
- return ['data' => []];
- }
- /**
- * 智能生成题目(异步模式)
- */
- public function generateIntelligentQuestions(array $params, ?string $callbackUrl = null): array
- {
- try {
- // 添加回调 URL
- if ($callbackUrl) {
- $params['callback_url'] = $callbackUrl;
- }
- // 增加超时时间到60秒,确保有足够时间启动异步任务
- // 注意:API是异步的,只需等待任务启动(1-2秒),不需要等待AI生成完成
- $response = Http::timeout(60)
- ->post($this->baseUrl . '/generate-intelligent-questions', $params);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('题目生成API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('题目生成异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['success' => false, 'message' => '生成失败'];
- }
- /**
- * 获取任务状态
- */
- public function getTaskStatus(string $taskId): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/tasks/' . $taskId);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取任务状态失败', [
- 'task_id' => $taskId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取任务状态异常', [
- 'task_id' => $taskId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 获取任务列表
- */
- public function listTasks(?string $status = null, int $page = 1, int $perPage = 10): array
- {
- try {
- $params = [
- 'page' => $page,
- 'per_page' => $perPage
- ];
- if ($status) {
- $params['status'] = $status;
- }
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/tasks', $params);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取任务列表失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取任务列表异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取题目统计信息
- */
- public function getStatistics(): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions/statistics');
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取题目统计失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取题目统计异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return [
- 'total' => 0,
- 'by_difficulty' => [],
- 'by_kp' => [],
- 'by_source' => []
- ];
- }
- /**
- * 根据知识点获取题目
- */
- public function getQuestionsByKpCode(string $kpCode, int $limit = 100): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/questions', [
- 'kp_code' => $kpCode,
- 'limit' => $limit
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- } catch (\Exception $e) {
- Log::error('根据知识点获取题目失败', [
- 'kp_code' => $kpCode,
- 'error' => $e->getMessage()
- ]);
- }
- return [];
- }
- /**
- * 删除题目
- */
- public function deleteQuestion(string $questionCode): bool
- {
- try {
- $response = Http::timeout(10)
- ->delete($this->baseUrl . "/questions/{$questionCode}");
- // 只有返回204(删除成功)才返回true,404(不存在)返回false
- if ($response->status() === 204) {
- return true;
- }
- if ($response->status() === 404) {
- Log::warning('尝试删除不存在的题目', ['question_code' => $questionCode]);
- return false;
- }
- return false;
- } catch (\Exception $e) {
- Log::error('删除题目失败', [
- 'question_code' => $questionCode,
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 智能选择试卷题目
- */
- public function selectQuestionsForExam(int $totalQuestions, array $filters): array
- {
- try {
- $response = Http::timeout(30)
- ->post($this->baseUrl . '/exam/select-questions', [
- 'total_questions' => $totalQuestions,
- 'filters' => $filters
- ]);
- if ($response->successful()) {
- return $response->json('data', []);
- }
- Log::warning('智能选题API调用失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('智能选题异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return [];
- }
- /**
- * 保存试卷到数据库(本地 papers 表)
- */
- public function saveExamToDatabase(array $examData): ?string
- {
- // 数据完整性检查
- if (empty($examData['questions'])) {
- Log::warning('尝试保存没有题目的试卷', [
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'student_id' => $examData['student_id'] ?? 'unknown'
- ]);
- return null;
- }
- try {
- // 使用数据库事务确保数据一致性
- return \Illuminate\Support\Facades\DB::transaction(function () use ($examData) {
- // 生成试卷ID
- $paperId = 'paper_' . time() . '_' . bin2hex(random_bytes(4));
- Log::info('开始保存试卷到数据库', [
- 'paper_id' => $paperId,
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'question_count' => count($examData['questions'])
- ]);
- // 使用Laravel模型保存到 papers 表
- $paper = \App\Models\Paper::create([
- 'paper_id' => $paperId,
- 'student_id' => $examData['student_id'] ?? '',
- 'teacher_id' => $examData['teacher_id'] ?? '',
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'paper_type' => 'auto_generated',
- 'question_count' => count($examData['questions']), // 使用实际题目数量
- 'total_score' => $examData['total_score'] ?? 0,
- 'status' => 'draft',
- 'difficulty_category' => $examData['difficulty_category'] ?? '基础',
- ]);
- // 获取所有题目的正确答案
- $questionBankIds = array_filter(array_map(function($q) {
- return $q['id'] ?? $q['question_id'] ?? null;
- }, $examData['questions']));
- $correctAnswersMap = [];
- if (!empty($questionBankIds)) {
- Log::info('获取题目正确答案', [
- 'paper_id' => $paperId,
- 'question_bank_ids' => $questionBankIds
- ]);
- try {
- $response = Http::timeout(10)->post($this->baseUrl . '/questions/batch', [
- 'ids' => array_values($questionBankIds)
- ]);
- if ($response->successful()) {
- $questionsDetails = $response->json('data', []);
- foreach ($questionsDetails as $detail) {
- $correctAnswersMap[$detail['id']] = $detail['answer'] ?? $detail['correct_answer'] ?? '';
- }
- Log::info('获取到题目正确答案', [
- 'paper_id' => $paperId,
- 'answers_count' => count($correctAnswersMap)
- ]);
- }
- } catch (\Exception $e) {
- Log::warning('获取题目正确答案失败', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage()
- ]);
- }
- }
- // 准备题目数据
- $questionInsertData = [];
- foreach ($examData['questions'] as $index => $question) {
- // 验证题目基本数据
- if (empty($question['stem']) && empty($question['content'])) {
- Log::warning('跳过没有内容的题目', [
- 'paper_id' => $paperId,
- 'question_index' => $index
- ]);
- continue;
- }
- // 处理题目内容:分离题干和选项(如果存在)
- $rawContent = $question['stem'] ?? $question['content'] ?? '';
- list($stem, $options) = $this->separateStemAndOptions($rawContent);
- // 将选项以换行符形式附加到题干末尾,方便后续渲染
- if (!empty($options)) {
- $stemWithOptions = $stem . "\n" . implode("\n", array_map(function($opt, $idx) {
- return chr(65 + $idx) . '. ' . $opt;
- }, $options, array_keys($options)));
- $question['stem'] = $stemWithOptions;
- $question['options'] = $options;
- } else {
- $question['stem'] = $stem;
- }
- // 处理难度字段:如果是字符串则转换为数字
- $difficultyValue = $question['difficulty'] ?? 0.5;
- if (is_string($difficultyValue)) {
- // 将中文难度转换为数字
- if (strpos($difficultyValue, '基础') !== false || strpos($difficultyValue, '简单') !== false) {
- $difficultyValue = 0.3;
- } elseif (strpos($difficultyValue, '中等') !== false || strpos($difficultyValue, '一般') !== false) {
- $difficultyValue = 0.6;
- } elseif (strpos($difficultyValue, '拔高') !== false || strpos($difficultyValue, '困难') !== false) {
- $difficultyValue = 0.9;
- } else {
- $difficultyValue = 0.5;
- }
- }
- // 确保 knowledge_point 有值
- $knowledgePoint = $question['kp'] ?? $question['kp_code'] ?? $question['knowledge_point'] ?? $question['knowledge_point_code'] ?? '';
- if (empty($knowledgePoint) && isset($question['kp_code'])) {
- $knowledgePoint = $question['kp_code'];
- }
- // 获取题目类型
- $questionType = $question['question_type'] ?? 'answer';
- if (!$questionType) {
- // 如果没有类型,根据内容推断
- $content = $question['stem'] ?? $question['content'] ?? '';
- if (is_string($content)) {
- // 1. 优先检查填空题(下划线)
- if (strpos($content, '____') !== false || strpos($content, '______') !== false) {
- $questionType = 'fill';
- }
- // 2. 检查选择题(必须有选项 A. B. C. D.)
- elseif (preg_match('/[A-D]\s*\./', $content) || preg_match('/\([A-D]\)/', $content)) {
- if (preg_match('/A\./', $content) && preg_match('/B\./', $content)) {
- $questionType = 'choice';
- } else {
- // 只有括号没有选项,可能是填空
- if (strpos($content, '()') !== false || strpos($content, '()') !== false) {
- $questionType = 'fill';
- } else {
- $questionType = 'answer';
- }
- }
- }
- // 3. 检查纯括号填空
- elseif (strpos($content, '()') !== false || strpos($content, '()') !== false) {
- $questionType = 'fill';
- }
- else {
- $questionType = 'answer';
- }
- } else {
- $questionType = 'answer';
- }
- }
- // 获取正确答案
- $questionBankId = $question['id'] ?? $question['question_id'] ?? null;
- $correctAnswer = $correctAnswersMap[$questionBankId] ?? $question['answer'] ?? $question['correct_answer'] ?? '';
- $questionInsertData[] = [
- 'paper_id' => $paperId,
- 'question_id' => $question['question_code'] ?? $question['question_id'] ?? null,
- 'question_bank_id' => $question['id'] ?? $question['question_id'] ?? 0,
- 'knowledge_point' => $knowledgePoint,
- 'question_type' => $questionType,
- 'question_text' => $question['stem'] ?? $question['content'] ?? $question['question_text'] ?? '',
- 'correct_answer' => $correctAnswer, // 保存正确答案
- 'difficulty' => $difficultyValue,
- 'score' => $question['score'] ?? 5, // 默认5分
- 'estimated_time' => $question['estimated_time'] ?? 300,
- 'question_number' => $index + 1,
- ];
- }
- // 验证是否有有效的题目数据
- if (empty($questionInsertData)) {
- Log::error('没有有效的题目数据可以保存', ['paper_id' => $paperId]);
- throw new \Exception('没有有效的题目数据');
- }
- // 使用Laravel模型批量插入题目数据
- \App\Models\PaperQuestion::insert($questionInsertData);
- // 验证插入结果,使用关联关系
- $insertedQuestionCount = $paper->questions()->count();
- if ($insertedQuestionCount !== count($questionInsertData)) {
- throw new \Exception("题目插入数量不匹配:预期 {$insertedQuestionCount},实际 " . count($questionInsertData));
- }
- Log::info('试卷保存成功', [
- 'paper_id' => $paperId,
- 'expected_questions' => count($questionInsertData),
- 'actual_questions' => $insertedQuestionCount,
- 'paper_name' => $paper->paper_name
- ]);
- return $paperId;
- });
- } catch (\Exception $e) {
- Log::error('保存试卷到数据库失败', [
- 'error' => $e->getMessage(),
- 'paper_name' => $examData['paper_name'] ?? '未命名试卷',
- 'student_id' => $examData['student_id'] ?? 'unknown',
- 'question_count' => count($examData['questions'] ?? []),
- 'trace' => $e->getTraceAsString()
- ]);
- return null;
- }
- }
- /**
- * 检查数据完整性 - 发现没有题目的试卷
- */
- public function checkDataIntegrity(): array
- {
- try {
- // 使用Laravel模型查找显示有题目但实际没有题目的试卷
- $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
- ->whereDoesntHave('questions')
- ->get();
- Log::warning('发现数据不一致的试卷', [
- 'count' => $inconsistentPapers->count(),
- 'papers' => $inconsistentPapers->map(function($paper) {
- return [
- 'paper_id' => $paper->paper_id,
- 'paper_name' => $paper->paper_name,
- 'expected_questions' => $paper->question_count,
- 'student_id' => $paper->student_id,
- 'created_at' => $paper->created_at
- ];
- })->toArray()
- ]);
- return [
- 'inconsistent_count' => $inconsistentPapers->count(),
- 'papers' => $inconsistentPapers->toArray()
- ];
- } catch (\Exception $e) {
- Log::error('检查数据完整性失败', ['error' => $e->getMessage()]);
- return ['inconsistent_count' => 0, 'papers' => []];
- }
- }
- /**
- * 清理没有题目的试卷记录
- */
- public function cleanupInconsistentPapers(): int
- {
- try {
- return \Illuminate\Support\Facades\DB::transaction(function () {
- // 使用Laravel模型查找显示有题目但实际没有题目的试卷
- $inconsistentPapers = \App\Models\Paper::where('question_count', '>', 0)
- ->whereDoesntHave('questions')
- ->get();
- if ($inconsistentPapers->isEmpty()) {
- return 0;
- }
- // 获取要删除的试卷ID列表
- $deletedPaperIds = $inconsistentPapers->pluck('paper_id')->toArray();
- // 使用Laravel模型删除这些不一致的试卷记录
- $deletedCount = \App\Models\Paper::whereIn('paper_id', $deletedPaperIds)->delete();
- Log::info('清理不一致的试卷记录', [
- 'deleted_count' => $deletedCount,
- 'deleted_paper_ids' => $deletedPaperIds
- ]);
- return $deletedCount;
- });
- } catch (\Exception $e) {
- Log::error('清理不一致试卷失败', ['error' => $e->getMessage()]);
- return 0;
- }
- }
- /**
- * 修复试卷的题目数量统计
- */
- public function fixPaperQuestionCounts(): int
- {
- try {
- $fixedCount = 0;
- // 使用Laravel模型获取所有试卷
- $papers = \App\Models\Paper::all();
- foreach ($papers as $paper) {
- // 计算实际的题目数量,使用关联关系
- $actualQuestionCount = $paper->questions()->count();
- // 如果题目数量不匹配,更新试卷
- if ($paper->question_count !== $actualQuestionCount) {
- $paper->update([
- 'question_count' => $actualQuestionCount,
- 'updated_at' => now()
- ]);
- $fixedCount++;
- Log::info('修复试卷题目数量', [
- 'paper_id' => $paper->paper_id,
- 'old_count' => $paper->getOriginal('question_count'),
- 'new_count' => $actualQuestionCount
- ]);
- }
- }
- Log::info('试卷题目数量修复完成', ['fixed_count' => $fixedCount]);
- return $fixedCount;
- } catch (\Exception $e) {
- Log::error('修复试卷题目数量失败', ['error' => $e->getMessage()]);
- return 0;
- }
- }
- /**
- * 获取试卷列表
- */
- public function listExams(int $page = 1, int $perPage = 20): array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/exam/list', [
- 'page' => $page,
- 'per_page' => $perPage
- ]);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取试卷列表失败', [
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取试卷列表异常', [
- 'error' => $e->getMessage()
- ]);
- }
- return ['data' => [], 'meta' => ['total' => 0]];
- }
- /**
- * 获取试卷详情
- */
- public function getExamById(string $paperId): ?array
- {
- try {
- $response = Http::timeout(10)
- ->get($this->baseUrl . '/exam/' . $paperId);
- if ($response->successful()) {
- return $response->json();
- }
- Log::warning('获取试卷详情失败', [
- 'paper_id' => $paperId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('获取试卷详情异常', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 导出试卷为PDF
- */
- public function exportExamToPdf(string $paperId): ?string
- {
- try {
- $response = Http::timeout(60)
- ->get($this->baseUrl . '/exam/' . $paperId . '/export/pdf');
- if ($response->successful()) {
- // 返回PDF文件路径或URL
- return $response->json('pdf_url', null);
- }
- Log::warning('导出PDF失败', [
- 'paper_id' => $paperId,
- 'status' => $response->status()
- ]);
- } catch (\Exception $e) {
- Log::error('导出PDF异常', [
- 'paper_id' => $paperId,
- 'error' => $e->getMessage()
- ]);
- }
- return null;
- }
- /**
- * 检查服务健康状态
- */
- public function checkHealth(): bool
- {
- try {
- $response = Http::timeout(5)
- ->get($this->baseUrl . '/health');
- return $response->successful();
- } catch (\Exception $e) {
- Log::error('题库服务健康检查失败', [
- 'error' => $e->getMessage()
- ]);
- return false;
- }
- }
- /**
- * 根据OCR识别的题目生成完整题目并保存到题库(异步模拟版本)
- *
- * @param array $questions OCR识别的题目列表
- * @param string $gradeLevel 年级
- * @param string $subject 科目
- * @param int $ocrRecordId OCR记录ID,用于关联
- * @param string|null $callbackUrl 回调URL(可选,如果不提供则自动生成)
- * @param string|null $callbackRouteName 回调路由名称(用于动态生成URL)
- * @return array 任务ID和状态
- */
- public function generateQuestionsFromOcrAsync(
- array $questions,
- string $gradeLevel = '高一',
- string $subject = '数学',
- int $ocrRecordId = null,
- string $callbackUrl = null,
- string $callbackRouteName = 'api.ocr.callback'
- ): array {
- try {
- // 如果没有提供回调URL,但提供了OCR记录ID,则动态生成回调URL
- if (!$callbackUrl && $ocrRecordId) {
- $callbackUrl = $this->generateCallbackUrl($callbackRouteName);
- Log::info('动态生成回调URL', [
- 'route_name' => $callbackRouteName,
- 'generated_url' => $callbackUrl
- ]);
- }
- // 生成唯一的任务ID
- $taskId = 'ocr_' . $ocrRecordId . '_' . time() . '_' . substr(md5(uniqid()), 0, 8);
- // 更新OCR记录状态为生成中
- if ($ocrRecordId) {
- \DB::table('ocr_question_results')
- ->where('ocr_record_id', $ocrRecordId)
- ->where('question_bank_id', null) // 只更新未关联的题目
- ->update([
- 'generation_status' => 'generating',
- 'generation_task_id' => $taskId,
- 'generation_error' => null
- ]);
- }
- // 启动后台任务(使用Laravel的队列)
- if ($ocrRecordId && $callbackUrl) {
- // 使用Laravel队列异步处理
- $this->dispatchOcrGenerationJob($ocrRecordId, $questions, $gradeLevel, $subject, $callbackUrl, $taskId);
- } else {
- // 如果没有回调URL,使用同步方式
- $response = $this->generateQuestionsFromOcr($questions, $gradeLevel, $subject);
- return $response;
- }
- Log::info('OCR题目生成任务已提交到队列', [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'questions_count' => count($questions),
- 'callback_url' => $callbackUrl
- ]);
- return [
- 'status' => 'processing',
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'message' => '题目生成任务已启动,完成后将通过回调通知',
- 'estimated_time' => '约' . (count($questions) * 2) . '秒',
- 'callback_info' => [
- 'will_callback' => !empty($callbackUrl),
- 'callback_url' => $callbackUrl
- ]
- ];
- } catch (\Exception $e) {
- Log::error('OCR题目生成任务提交异常', [
- 'error' => $e->getMessage(),
- 'ocr_record_id' => $ocrRecordId
- ]);
- return [
- 'status' => 'error',
- 'message' => '任务提交失败: ' . $e->getMessage()
- ];
- }
- }
- /**
- * 分发OCR生成任务到队列
- */
- private function dispatchOcrGenerationJob(
- int $ocrRecordId,
- array $questions,
- string $gradeLevel,
- string $subject,
- string $callbackUrl,
- string $taskId
- ): void {
- try {
- // 转换题目数据格式
- $formattedQuestions = [];
- foreach ($questions as $q) {
- $formattedQuestions[] = [
- 'id' => $q['id'] ?? uniqid(),
- 'content' => $q['content'] ?? ''
- ];
- }
- // 直接调用QuestionBank API的异步端点,提供回调URL
- // 注意: baseUrl 已经包含 /api,所以这里只需要 /ocr/questions/generate-from-ocr
- $response = Http::timeout(60)
- ->post($this->baseUrl . '/ocr/questions/generate-from-ocr', [
- 'ocr_record_id' => $ocrRecordId,
- 'questions' => $formattedQuestions,
- 'grade_level' => $gradeLevel,
- 'subject' => $subject,
- 'callback_url' => $callbackUrl
- ]);
- if (!$response->successful()) {
- Log::error('提交OCR题目生成任务失败', [
- 'status' => $response->status(),
- 'body' => $response->body(),
- 'task_id' => $taskId
- ]);
- // 发送失败回调
- $callbackData = [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'status' => 'failed',
- 'error' => 'API调用失败: ' . $response->status(),
- 'timestamp' => now()->toISOString()
- ];
- Http::timeout(10)
- ->post($callbackUrl, $callbackData);
- return;
- }
- $result = $response->json();
- Log::info('OCR题目生成任务已提交到QuestionBank', [
- 'task_id' => $taskId,
- 'questionbank_task_id' => $result['task_id'] ?? 'unknown',
- 'status' => $result['status'] ?? 'unknown',
- 'callback_url' => $callbackUrl
- ]);
- // QuestionBank API会异步处理并通过回调通知,这里不需要立即触发回调
- // 回调会在题目生成完成后由QuestionBank API主动发送
- } catch (\Exception $e) {
- Log::error('OCR生成任务处理失败', [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'error' => $e->getMessage()
- ]);
- // 发送异常回调
- try {
- $callbackData = [
- 'task_id' => $taskId,
- 'ocr_record_id' => $ocrRecordId,
- 'status' => 'failed',
- 'error' => $e->getMessage(),
- 'timestamp' => now()->toISOString()
- ];
- Http::timeout(10)
- ->post($callbackUrl, $callbackData);
- } catch (\Exception $callbackException) {
- Log::error('发送异常回调失败', [
- 'error' => $callbackException->getMessage()
- ]);
- }
- }
- }
- /**
- * 动态生成回调URL
- *
- * @param string $routeName 路由名称
- * @return string 完整的回调URL
- */
- private function generateCallbackUrl(string $routeName): string
- {
- try {
- // 获取当前请求的域名
- $appUrl = config('app.url', 'http://localhost');
- // 如果是在命令行环境中运行,使用配置的域名
- if (app()->runningInConsole()) {
- $domain = config('services.question_bank.callback_domain', $appUrl);
- } else {
- $domain = request()->getSchemeAndHttpHost();
- }
- // 确保domain不为null
- $domain = $domain ?? $appUrl;
- // 移除末尾的斜杠
- $domain = rtrim($domain, '/');
- // 生成完整的URL
- $callbackUrl = $domain . route($routeName, [], false);
- Log::info('生成回调URL', [
- 'route_name' => $routeName,
- 'domain' => $domain,
- 'app_url' => $appUrl,
- 'callback_url' => $callbackUrl
- ]);
- return $callbackUrl;
- } catch (\Exception $e) {
- // 如果路由生成失败,使用默认URL
- Log::warning('路由生成失败,使用默认URL', [
- 'route_name' => $routeName,
- 'error' => $e->getMessage()
- ]);
- $fallbackUrl = config('app.url', 'http://localhost');
- if ($routeName === 'api.ocr.callback') {
- return $fallbackUrl . '/api/ocr-question-callback';
- }
- return $fallbackUrl;
- }
- }
- /**
- * 根据OCR识别的题目生成题库题目(同步版本,向后兼容)
- *
- * @param array $questions OCR题目数组 [['question_number' => 1, 'question_text' => '...']]
- * @param string $gradeLevel 年级
- * @param string $subject 科目
- * @return array 生成结果
- */
- public function generateQuestionsFromOcr(array $questions, string $gradeLevel = '高一', string $subject = '数学'): array
- {
- return $this->generateQuestionsFromOcrAsync($questions, $gradeLevel, $subject);
- }
- /**
- * 检查题目生成任务状态
- */
- public function checkGenerationTaskStatus(string $taskId): array
- {
- return $this->getTaskStatus($taskId) ?? ['status' => 'unknown'];
- }
- }
|