TextbookApiService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Http;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\DB;
  6. class TextbookApiService
  7. {
  8. protected string $baseUrl;
  9. public function __construct()
  10. {
  11. // QuestionBankService API 地址
  12. $baseUrl = config('services.question_bank.base_url', 'http://localhost:5015/api');
  13. // 移除末尾的 /,保持 baseUrl 以 /api 结尾
  14. $this->baseUrl = rtrim($baseUrl, '/');
  15. }
  16. /**
  17. * 通用HTTP请求方法 - 减少重复代码,无缓存
  18. */
  19. protected function request(string $method, string $endpoint, array $data = []): array
  20. {
  21. try {
  22. $httpMethod = strtolower($method);
  23. $response = match($httpMethod) {
  24. 'get' => Http::timeout(30)->get($this->baseUrl . $endpoint, $data),
  25. 'post' => Http::timeout(300)->post($this->baseUrl . $endpoint, $data),
  26. 'put' => Http::timeout(30)->put($this->baseUrl . $endpoint, $data),
  27. 'delete' => Http::timeout(30)->delete($this->baseUrl . $endpoint, $data),
  28. default => throw new \InvalidArgumentException("Unsupported HTTP method: {$method}")
  29. };
  30. // 处理文件上传
  31. if (isset($data['file']) && $data['file'] instanceof \Illuminate\Http\UploadedFile) {
  32. $response = Http::timeout(300)
  33. ->attach('file', file_get_contents($data['file']->getPathname()), $data['file']->getClientOriginalName())
  34. ->{$httpMethod}($this->baseUrl . $endpoint, $data);
  35. }
  36. if ($response->successful()) {
  37. return $response->json();
  38. }
  39. // 记录错误并抛出异常
  40. $error = $this->handleErrorResponse($response, $endpoint);
  41. throw new \Exception($error);
  42. } catch (\Exception $e) {
  43. Log::error("API request failed: {$method} {$endpoint}", [
  44. 'error' => $e->getMessage(),
  45. 'data' => $data
  46. ]);
  47. throw $e;
  48. }
  49. }
  50. /**
  51. * 处理错误响应
  52. */
  53. private function handleErrorResponse($response, string $endpoint): string
  54. {
  55. $status = $response->status();
  56. $body = $response->body();
  57. // 常见错误类型的友好提示
  58. return match($status) {
  59. 404 => "未找到资源: {$endpoint}",
  60. 422 => "数据验证失败: {$body}",
  61. 500 => "服务器内部错误: {$body}",
  62. default => "HTTP {$status}: {$body}"
  63. };
  64. }
  65. /**
  66. * 获取教材系列列表
  67. */
  68. public function getTextbookSeries(array $params = []): array
  69. {
  70. try {
  71. return $this->request('GET', '/textbooks/series', $params);
  72. } catch (\Exception $e) {
  73. // 失败时返回空数据而不是抛出异常,保持向后兼容
  74. Log::warning('Failed to fetch textbook series, returning empty result', ['error' => $e->getMessage()]);
  75. return ['data' => [], 'meta' => []];
  76. }
  77. }
  78. /**
  79. * 根据ID获取单个教材系列
  80. */
  81. public function getTextbookSeriesById(int $seriesId): ?array
  82. {
  83. try {
  84. $result = $this->request('GET', "/textbooks/series/{$seriesId}");
  85. return $result['data'] ?? null;
  86. } catch (\Exception $e) {
  87. Log::warning('Series not found or error occurred', [
  88. 'series_id' => $seriesId,
  89. 'error' => $e->getMessage()
  90. ]);
  91. return null;
  92. }
  93. }
  94. /**
  95. * 创建教材系列
  96. */
  97. public function createTextbookSeries(array $data): array
  98. {
  99. try {
  100. return $this->request('POST', '/textbooks/series', $data);
  101. } catch (\Exception $e) {
  102. // 检查是否是series不存在的错误(虽然这里不太可能,但保持向后兼容)
  103. if (strpos($e->getMessage(), 'Series not found') !== false) {
  104. $seriesId = $data['id'] ?? 'unknown';
  105. throw new \Exception("系列ID {$seriesId} 不存在");
  106. }
  107. throw $e;
  108. }
  109. }
  110. /**
  111. * 更新教材系列
  112. */
  113. public function updateTextbookSeries(int $seriesId, array $data): array
  114. {
  115. try {
  116. return $this->request('PUT', "/textbooks/series/{$seriesId}", $data);
  117. } catch (\Exception $e) {
  118. Log::error('Error updating textbook series', ['error' => $e->getMessage()]);
  119. throw $e;
  120. }
  121. }
  122. /**
  123. * 删除教材系列
  124. */
  125. public function deleteTextbookSeries(int $seriesId): bool
  126. {
  127. try {
  128. $this->request('DELETE', "/textbooks/series/{$seriesId}");
  129. return true;
  130. } catch (\Exception $e) {
  131. Log::error('Error deleting textbook series', ['error' => $e->getMessage()]);
  132. return false;
  133. }
  134. }
  135. /**
  136. * 删除教材
  137. */
  138. public function deleteTextbook(int $textbookId): bool
  139. {
  140. try {
  141. $this->request('DELETE', "/textbooks/by-id/{$textbookId}");
  142. return true;
  143. } catch (\Exception $e) {
  144. Log::error('Error deleting textbook', ['error' => $e->getMessage(), 'textbook_id' => $textbookId]);
  145. return false;
  146. }
  147. }
  148. /**
  149. * 获取教材列表
  150. */
  151. public function getTextbooks(array $params = []): array
  152. {
  153. try {
  154. return $this->request('GET', '/textbooks', $params);
  155. } catch (\Exception $e) {
  156. Log::warning('Failed to fetch textbooks, returning empty result', ['error' => $e->getMessage()]);
  157. return ['data' => [], 'meta' => []];
  158. }
  159. }
  160. /**
  161. * 获取单个教材
  162. */
  163. public function getTextbook(int $textbookId): ?array
  164. {
  165. try {
  166. $result = $this->request('GET', "/textbooks/by-id/{$textbookId}");
  167. return $result['data'] ?? null;
  168. } catch (\Exception $e) {
  169. Log::warning('Textbook not found or error occurred', [
  170. 'textbook_id' => $textbookId,
  171. 'error' => $e->getMessage()
  172. ]);
  173. return null;
  174. }
  175. }
  176. /**
  177. * 创建教材
  178. */
  179. public function createTextbook(array $data): array
  180. {
  181. try {
  182. return $this->request('POST', '/textbooks', $data);
  183. } catch (\Exception $e) {
  184. // 检查是否是series不存在的错误
  185. if (strpos($e->getMessage(), 'Series not found') !== false) {
  186. $seriesId = $data['series_id'] ?? 'unknown';
  187. throw new \Exception("系列ID {$seriesId} 不存在,请先创建教材系列或检查ID是否正确");
  188. }
  189. throw $e;
  190. }
  191. }
  192. /**
  193. * 更新教材
  194. */
  195. public function updateTextbook(int $textbookId, array $data): array
  196. {
  197. try {
  198. return $this->request('PUT', "/textbooks/by-id/{$textbookId}", $data);
  199. } catch (\Exception $e) {
  200. Log::error('Error updating textbook', ['error' => $e->getMessage()]);
  201. throw $e;
  202. }
  203. }
  204. /**
  205. * 创建或更新教材(upsert模式)
  206. * 根据系列、学段、年级、学期、官方书名判断是否已存在
  207. */
  208. public function createOrUpdateTextbook(array $data): array
  209. {
  210. try {
  211. return $this->request('POST', '/textbooks/upsert', $data);
  212. } catch (\Exception $e) {
  213. // 检查是否是series不存在的错误
  214. if (strpos($e->getMessage(), 'Series not found') !== false) {
  215. $seriesId = $data['series_id'] ?? 'unknown';
  216. throw new \Exception("系列ID {$seriesId} 不存在,请先创建教材系列或检查ID是否正确");
  217. }
  218. throw $e;
  219. }
  220. }
  221. /**
  222. * 删除教材目录节点
  223. */
  224. public function deleteTextbookCatalog(int $catalogId): bool
  225. {
  226. try {
  227. $this->request('DELETE', "/textbooks/catalog/{$catalogId}");
  228. return true;
  229. } catch (\Exception $e) {
  230. Log::error('Error deleting textbook catalog', ['error' => $e->getMessage(), 'catalog_id' => $catalogId]);
  231. return false;
  232. }
  233. }
  234. /**
  235. * 获取教材目录树
  236. */
  237. public function getTextbookCatalog(int $textbookId, string $format = 'tree'): array
  238. {
  239. try {
  240. $result = $this->request('GET', "/textbooks/by-id/{$textbookId}/catalog", ['format' => $format]);
  241. return $result['data'] ?? [];
  242. } catch (\Exception $e) {
  243. Log::warning('Failed to fetch textbook catalog, returning empty result', ['error' => $e->getMessage()]);
  244. return [];
  245. }
  246. }
  247. /**
  248. * 预览教材命名
  249. */
  250. public function previewTextbookNaming(array $textbookData, array $seriesData): array
  251. {
  252. try {
  253. $result = $this->request('POST', '/textbooks/naming-preview', [
  254. 'textbook' => $textbookData,
  255. 'series' => $seriesData
  256. ]);
  257. return $result['data'] ?? [];
  258. } catch (\Exception $e) {
  259. Log::warning('Failed to preview textbook naming, returning empty result', ['error' => $e->getMessage()]);
  260. return [];
  261. }
  262. }
  263. /**
  264. * 导入教材元信息
  265. */
  266. public function importTextbookMetadata($file, string $commitMode = 'overwrite'): array
  267. {
  268. try {
  269. return $this->request('POST', '/textbooks/import/meta', [
  270. 'file' => $file,
  271. 'commit_mode' => $commitMode
  272. ]);
  273. } catch (\Exception $e) {
  274. Log::error('Error importing textbook metadata', ['error' => $e->getMessage()]);
  275. throw $e;
  276. }
  277. }
  278. /**
  279. * 导入教材目录
  280. */
  281. public function importTextbookCatalog(int $textbookId, array $catalogData, string $commitMode = 'overwrite'): array
  282. {
  283. try {
  284. // 将数组转换为JSON字符串
  285. $jsonData = json_encode($catalogData, JSON_UNESCAPED_UNICODE);
  286. // 直接发送 JSON 数据
  287. return $this->request('POST', '/textbooks/import/catalog', [
  288. 'textbook_id' => $textbookId,
  289. 'data' => $jsonData,
  290. 'commit_mode' => $commitMode
  291. ]);
  292. } catch (\Exception $e) {
  293. Log::error('Error importing textbook catalog', ['error' => $e->getMessage()]);
  294. throw $e;
  295. }
  296. }
  297. /**
  298. * 提交导入任务
  299. */
  300. public function commitImportJob(int $jobId): array
  301. {
  302. try {
  303. return $this->request('POST', "/api/textbooks/import/{$jobId}/commit");
  304. } catch (\Exception $e) {
  305. Log::error('Error committing import job', ['error' => $e->getMessage()]);
  306. throw $e;
  307. }
  308. }
  309. /**
  310. * 获取导入任务列表
  311. */
  312. public function getImportJobs(array $params = []): array
  313. {
  314. try {
  315. return $this->request('GET', '/textbooks/import/jobs', $params);
  316. } catch (\Exception $e) {
  317. Log::warning('Failed to fetch import jobs, returning empty result', ['error' => $e->getMessage()]);
  318. return ['data' => [], 'meta' => []];
  319. }
  320. }
  321. /**
  322. * 获取单个导入任务
  323. */
  324. public function getImportJob(int $jobId): ?array
  325. {
  326. try {
  327. $result = $this->request('GET', "/api/textbooks/import/jobs/{$jobId}");
  328. return $result['data'] ?? null;
  329. } catch (\Exception $e) {
  330. Log::warning('Import job not found or error occurred', ['error' => $e->getMessage()]);
  331. return null;
  332. }
  333. }
  334. /**
  335. * 完全同步教材系列到题库服务(清空+重新插入)
  336. */
  337. public function syncTextbookSeriesToQuestionBank(): array
  338. {
  339. try {
  340. // 获取MySQL中的所有系列
  341. $mysqlSeries = DB::connection('mysql')
  342. ->table('textbook_series')
  343. ->orderBy('id')
  344. ->get();
  345. if ($mysqlSeries->isEmpty()) {
  346. return [
  347. 'success' => false,
  348. 'message' => 'MySQL中没有找到教材系列数据'
  349. ];
  350. }
  351. // 准备数据
  352. $seriesData = [];
  353. foreach ($mysqlSeries as $series) {
  354. $seriesData[] = [
  355. 'id' => $series->id,
  356. 'name' => $series->name,
  357. 'slug' => $series->slug,
  358. 'publisher' => $series->publisher,
  359. 'region' => $series->region,
  360. 'stages' => json_decode($series->stages, true),
  361. 'is_active' => (bool)$series->is_active,
  362. 'sort_order' => (int)$series->sort_order,
  363. 'meta' => json_decode($series->meta, true),
  364. ];
  365. }
  366. // 调用API进行完全同步
  367. $result = $this->request('POST', '/textbooks/series/sync-all', [
  368. 'series' => $seriesData
  369. ]);
  370. return [
  371. 'success' => true,
  372. 'synced_count' => count($seriesData),
  373. 'data' => $result
  374. ];
  375. } catch (\Exception $e) {
  376. Log::error('Error syncing textbook series', ['error' => $e->getMessage()]);
  377. return [
  378. 'success' => false,
  379. 'message' => '同步失败: ' . $e->getMessage()
  380. ];
  381. }
  382. }
  383. }