TextbookApiService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. * 获取教材系列列表
  18. */
  19. public function getTextbookSeries(array $params = []): array
  20. {
  21. try {
  22. $response = Http::timeout(30)->get($this->baseUrl . '/textbooks/series', $params);
  23. if ($response->successful()) {
  24. return $response->json();
  25. }
  26. Log::error('Failed to fetch textbook series', [
  27. 'status' => $response->status(),
  28. 'body' => $response->body()
  29. ]);
  30. return ['data' => [], 'meta' => []];
  31. } catch (\Exception $e) {
  32. Log::error('Error fetching textbook series', ['error' => $e->getMessage()]);
  33. return ['data' => [], 'meta' => []];
  34. }
  35. }
  36. /**
  37. * 根据ID获取单个教材系列
  38. */
  39. public function getTextbookSeriesById(int $seriesId): ?array
  40. {
  41. try {
  42. $response = Http::timeout(30)->get($this->baseUrl . "/textbooks/series/{$seriesId}");
  43. if ($response->successful()) {
  44. return $response->json('data');
  45. }
  46. Log::warning('Series not found', [
  47. 'series_id' => $seriesId,
  48. 'status' => $response->status(),
  49. ]);
  50. return null;
  51. } catch (\Exception $e) {
  52. Log::error('Error fetching textbook series', ['error' => $e->getMessage(), 'series_id' => $seriesId]);
  53. return null;
  54. }
  55. }
  56. /**
  57. * 创建教材系列
  58. */
  59. public function createTextbookSeries(array $data): array
  60. {
  61. try {
  62. $response = Http::timeout(30)->post($this->baseUrl . '/textbooks/series', $data);
  63. if ($response->successful()) {
  64. return $response->json();
  65. }
  66. $responseBody = $response->body();
  67. $status = $response->status();
  68. Log::error('Failed to create textbook series', [
  69. 'status' => $status,
  70. 'body' => $responseBody
  71. ]);
  72. throw new \Exception('Failed to create textbook series: ' . $responseBody);
  73. } catch (\Exception $e) {
  74. Log::error('Error creating textbook series', ['error' => $e->getMessage()]);
  75. throw $e;
  76. }
  77. }
  78. /**
  79. * 更新教材系列
  80. */
  81. public function updateTextbookSeries(int $seriesId, array $data): array
  82. {
  83. try {
  84. $response = Http::timeout(30)->put($this->baseUrl . "/textbooks/series/{$seriesId}", $data);
  85. if ($response->successful()) {
  86. return $response->json();
  87. }
  88. Log::error('Failed to update textbook series', [
  89. 'status' => $response->status(),
  90. 'body' => $response->body()
  91. ]);
  92. throw new \Exception('Failed to update textbook series');
  93. } catch (\Exception $e) {
  94. Log::error('Error updating textbook series', ['error' => $e->getMessage()]);
  95. throw $e;
  96. }
  97. }
  98. /**
  99. * 删除教材系列
  100. */
  101. public function deleteTextbookSeries(int $seriesId): bool
  102. {
  103. try {
  104. $response = Http::timeout(30)->delete($this->baseUrl . "/textbooks/series/{$seriesId}");
  105. if ($response->successful()) {
  106. return true;
  107. }
  108. Log::error('Failed to delete textbook series', [
  109. 'status' => $response->status(),
  110. 'body' => $response->body()
  111. ]);
  112. return false;
  113. } catch (\Exception $e) {
  114. Log::error('Error deleting textbook series', ['error' => $e->getMessage()]);
  115. return false;
  116. }
  117. }
  118. /**
  119. * 删除教材
  120. */
  121. public function deleteTextbook(int $textbookId): bool
  122. {
  123. try {
  124. $response = Http::timeout(30)->delete($this->baseUrl . "/textbooks/{$textbookId}");
  125. if ($response->successful()) {
  126. return true;
  127. }
  128. Log::error('Failed to delete textbook', [
  129. 'textbook_id' => $textbookId,
  130. 'status' => $response->status(),
  131. 'body' => $response->body()
  132. ]);
  133. return false;
  134. } catch (\Exception $e) {
  135. Log::error('Error deleting textbook', ['error' => $e->getMessage(), 'textbook_id' => $textbookId]);
  136. return false;
  137. }
  138. }
  139. /**
  140. * 获取教材列表
  141. */
  142. public function getTextbooks(array $params = []): array
  143. {
  144. try {
  145. $response = Http::timeout(30)->get($this->baseUrl . '/textbooks', $params);
  146. if ($response->successful()) {
  147. return $response->json();
  148. }
  149. Log::error('Failed to fetch textbooks', [
  150. 'status' => $response->status(),
  151. 'body' => $response->body()
  152. ]);
  153. return ['data' => [], 'meta' => []];
  154. } catch (\Exception $e) {
  155. Log::error('Error fetching textbooks', ['error' => $e->getMessage()]);
  156. return ['data' => [], 'meta' => []];
  157. }
  158. }
  159. /**
  160. * 获取单个教材
  161. */
  162. public function getTextbook(int $textbookId): ?array
  163. {
  164. try {
  165. $response = Http::timeout(30)->get($this->baseUrl . "/textbooks/{$textbookId}");
  166. if ($response->successful()) {
  167. return $response->json('data');
  168. }
  169. Log::error('Failed to fetch textbook', [
  170. 'status' => $response->status(),
  171. 'body' => $response->body()
  172. ]);
  173. return null;
  174. } catch (\Exception $e) {
  175. Log::error('Error fetching textbook', ['error' => $e->getMessage()]);
  176. return null;
  177. }
  178. }
  179. /**
  180. * 创建教材
  181. */
  182. public function createTextbook(array $data): array
  183. {
  184. try {
  185. $response = Http::timeout(30)->post($this->baseUrl . '/textbooks', $data);
  186. if ($response->successful()) {
  187. return $response->json();
  188. }
  189. $responseBody = $response->body();
  190. $status = $response->status();
  191. Log::error('Failed to create textbook', [
  192. 'status' => $status,
  193. 'body' => $responseBody
  194. ]);
  195. // 检查是否是series不存在的错误
  196. if ($status === 404 && strpos($responseBody, 'Series not found') !== false) {
  197. $seriesId = $data['series_id'] ?? 'unknown';
  198. throw new \Exception("系列ID {$seriesId} 不存在,请先创建教材系列或检查ID是否正确");
  199. }
  200. throw new \Exception('Failed to create textbook: ' . $responseBody);
  201. } catch (\Exception $e) {
  202. Log::error('Error creating textbook', ['error' => $e->getMessage()]);
  203. throw $e;
  204. }
  205. }
  206. /**
  207. * 更新教材
  208. */
  209. public function updateTextbook(int $textbookId, array $data): array
  210. {
  211. try {
  212. $response = Http::timeout(30)->put($this->baseUrl . "/textbooks/{$textbookId}", $data);
  213. if ($response->successful()) {
  214. return $response->json();
  215. }
  216. Log::error('Failed to update textbook', [
  217. 'status' => $response->status(),
  218. 'body' => $response->body()
  219. ]);
  220. throw new \Exception('Failed to update textbook');
  221. } catch (\Exception $e) {
  222. Log::error('Error updating textbook', ['error' => $e->getMessage()]);
  223. throw $e;
  224. }
  225. }
  226. /**
  227. * 创建或更新教材(upsert模式)
  228. * 根据系列、学段、年级、学期、官方书名判断是否已存在
  229. */
  230. public function createOrUpdateTextbook(array $data): array
  231. {
  232. try {
  233. $response = Http::timeout(30)->post($this->baseUrl . '/textbooks/upsert', $data);
  234. if ($response->successful()) {
  235. return $response->json();
  236. }
  237. $responseBody = $response->body();
  238. $status = $response->status();
  239. Log::error('Failed to create or update textbook', [
  240. 'status' => $status,
  241. 'body' => $responseBody
  242. ]);
  243. // 检查是否是series不存在的错误
  244. if ($status === 404 && strpos($responseBody, 'Series not found') !== false) {
  245. $seriesId = $data['series_id'] ?? 'unknown';
  246. throw new \Exception("系列ID {$seriesId} 不存在,请先创建教材系列或检查ID是否正确");
  247. }
  248. throw new \Exception('Failed to create or update textbook: ' . $responseBody);
  249. } catch (\Exception $e) {
  250. Log::error('Error creating or updating textbook', ['error' => $e->getMessage()]);
  251. throw $e;
  252. }
  253. }
  254. /**
  255. * 删除教材目录节点
  256. */
  257. public function deleteTextbookCatalog(int $catalogId): bool
  258. {
  259. try {
  260. $response = Http::timeout(30)->delete($this->baseUrl . "/textbooks/catalog/{$catalogId}");
  261. if ($response->successful()) {
  262. return true;
  263. }
  264. Log::error('Failed to delete textbook catalog', [
  265. 'catalog_id' => $catalogId,
  266. 'status' => $response->status(),
  267. 'body' => $response->body()
  268. ]);
  269. return false;
  270. } catch (\Exception $e) {
  271. Log::error('Error deleting textbook catalog', ['error' => $e->getMessage(), 'catalog_id' => $catalogId]);
  272. return false;
  273. }
  274. }
  275. /**
  276. * 获取教材目录树
  277. */
  278. public function getTextbookCatalog(int $textbookId, string $format = 'tree'): array
  279. {
  280. try {
  281. $response = Http::timeout(30)->get($this->baseUrl . "/textbooks/{$textbookId}/catalog", [
  282. 'format' => $format
  283. ]);
  284. if ($response->successful()) {
  285. return $response->json('data');
  286. }
  287. Log::error('Failed to fetch textbook catalog', [
  288. 'status' => $response->status(),
  289. 'body' => $response->body()
  290. ]);
  291. return [];
  292. } catch (\Exception $e) {
  293. Log::error('Error fetching textbook catalog', ['error' => $e->getMessage()]);
  294. return [];
  295. }
  296. }
  297. /**
  298. * 预览教材命名
  299. */
  300. public function previewTextbookNaming(array $textbookData, array $seriesData): array
  301. {
  302. try {
  303. $response = Http::timeout(30)->post($this->baseUrl . '/textbooks/naming-preview', [
  304. 'textbook' => $textbookData,
  305. 'series' => $seriesData
  306. ]);
  307. if ($response->successful()) {
  308. return $response->json('data');
  309. }
  310. Log::error('Failed to preview textbook naming', [
  311. 'status' => $response->status(),
  312. 'body' => $response->body()
  313. ]);
  314. return [];
  315. } catch (\Exception $e) {
  316. Log::error('Error previewing textbook naming', ['error' => $e->getMessage()]);
  317. return [];
  318. }
  319. }
  320. /**
  321. * 导入教材元信息
  322. */
  323. public function importTextbookMetadata($file, string $commitMode = 'overwrite'): array
  324. {
  325. try {
  326. $response = Http::timeout(300)
  327. ->attach('file', file_get_contents($file->getPathname()), $file->getClientOriginalName())
  328. ->post($this->baseUrl . '/textbooks/import/meta', [
  329. 'commit_mode' => $commitMode
  330. ]);
  331. if ($response->successful()) {
  332. return $response->json();
  333. }
  334. Log::error('Failed to import textbook metadata', [
  335. 'status' => $response->status(),
  336. 'body' => $response->body()
  337. ]);
  338. throw new \Exception('Failed to import textbook metadata');
  339. } catch (\Exception $e) {
  340. Log::error('Error importing textbook metadata', ['error' => $e->getMessage()]);
  341. throw $e;
  342. }
  343. }
  344. /**
  345. * 导入教材目录
  346. */
  347. public function importTextbookCatalog(int $textbookId, $file, string $commitMode = 'overwrite'): array
  348. {
  349. try {
  350. $response = Http::timeout(300)
  351. ->attach('file', file_get_contents($file->getPathname()), $file->getClientOriginalName())
  352. ->post($this->baseUrl . '/textbooks/import/catalog', [
  353. 'textbook_id' => $textbookId,
  354. 'commit_mode' => $commitMode
  355. ]);
  356. if ($response->successful()) {
  357. return $response->json();
  358. }
  359. Log::error('Failed to import textbook catalog', [
  360. 'status' => $response->status(),
  361. 'body' => $response->body()
  362. ]);
  363. throw new \Exception('Failed to import textbook catalog');
  364. } catch (\Exception $e) {
  365. Log::error('Error importing textbook catalog', ['error' => $e->getMessage()]);
  366. throw $e;
  367. }
  368. }
  369. /**
  370. * 提交导入任务
  371. */
  372. public function commitImportJob(int $jobId): array
  373. {
  374. try {
  375. $response = Http::timeout(300)->post($this->baseUrl . "/api/textbooks/import/{$jobId}/commit");
  376. if ($response->successful()) {
  377. return $response->json();
  378. }
  379. Log::error('Failed to commit import job', [
  380. 'status' => $response->status(),
  381. 'body' => $response->body()
  382. ]);
  383. throw new \Exception('Failed to commit import job');
  384. } catch (\Exception $e) {
  385. Log::error('Error committing import job', ['error' => $e->getMessage()]);
  386. throw $e;
  387. }
  388. }
  389. /**
  390. * 获取导入任务列表
  391. */
  392. public function getImportJobs(array $params = []): array
  393. {
  394. try {
  395. $response = Http::timeout(30)->get($this->baseUrl . '/textbooks/import/jobs', $params);
  396. if ($response->successful()) {
  397. return $response->json();
  398. }
  399. Log::error('Failed to fetch import jobs', [
  400. 'status' => $response->status(),
  401. 'body' => $response->body()
  402. ]);
  403. return ['data' => [], 'meta' => []];
  404. } catch (\Exception $e) {
  405. Log::error('Error fetching import jobs', ['error' => $e->getMessage()]);
  406. return ['data' => [], 'meta' => []];
  407. }
  408. }
  409. /**
  410. * 获取单个导入任务
  411. */
  412. public function getImportJob(int $jobId): ?array
  413. {
  414. try {
  415. $response = Http::timeout(30)->get($this->baseUrl . "/api/textbooks/import/jobs/{$jobId}");
  416. if ($response->successful()) {
  417. return $response->json('data');
  418. }
  419. Log::error('Failed to fetch import job', [
  420. 'status' => $response->status(),
  421. 'body' => $response->body()
  422. ]);
  423. return null;
  424. } catch (\Exception $e) {
  425. Log::error('Error fetching import job', ['error' => $e->getMessage()]);
  426. return null;
  427. }
  428. }
  429. /**
  430. * 完全同步教材系列到题库服务(清空+重新插入)
  431. */
  432. public function syncTextbookSeriesToQuestionBank(): array
  433. {
  434. try {
  435. // 获取MySQL中的所有系列
  436. $mysqlSeries = DB::connection('mysql')
  437. ->table('textbook_series')
  438. ->orderBy('id')
  439. ->get();
  440. if ($mysqlSeries->isEmpty()) {
  441. return [
  442. 'success' => false,
  443. 'message' => 'MySQL中没有找到教材系列数据'
  444. ];
  445. }
  446. // 准备数据
  447. $seriesData = [];
  448. foreach ($mysqlSeries as $series) {
  449. $seriesData[] = [
  450. 'id' => $series->id,
  451. 'name' => $series->name,
  452. 'slug' => $series->slug,
  453. 'publisher' => $series->publisher,
  454. 'region' => $series->region,
  455. 'stages' => json_decode($series->stages, true),
  456. 'is_active' => (bool)$series->is_active,
  457. 'sort_order' => (int)$series->sort_order,
  458. 'meta' => json_decode($series->meta, true),
  459. ];
  460. }
  461. // 调用API进行完全同步
  462. $response = Http::timeout(300)->post($this->baseUrl . '/textbooks/series/sync-all', [
  463. 'series' => $seriesData
  464. ]);
  465. if ($response->successful()) {
  466. $result = $response->json();
  467. return [
  468. 'success' => true,
  469. 'synced_count' => count($seriesData),
  470. 'data' => $result
  471. ];
  472. }
  473. $responseBody = $response->body();
  474. $status = $response->status();
  475. Log::error('Failed to sync textbook series', [
  476. 'status' => $status,
  477. 'body' => $responseBody
  478. ]);
  479. return [
  480. 'success' => false,
  481. 'message' => "同步失败: HTTP {$status} - {$responseBody}"
  482. ];
  483. } catch (\Exception $e) {
  484. Log::error('Error syncing textbook series', ['error' => $e->getMessage()]);
  485. return [
  486. 'success' => false,
  487. 'message' => '同步失败: ' . $e->getMessage()
  488. ];
  489. }
  490. }
  491. }