importer = app(TextbookExcelImporter::class); $this->apiService = app(TextbookApiService::class); } public function mount() { $this->importer = app(TextbookExcelImporter::class); $this->apiService = app(TextbookApiService::class); // 检查URL参数,设置默认导入类型 $type = request()->get('type'); if (in_array($type, ['textbook_series', 'textbook', 'textbook_catalog'])) { $this->selectedType = $type; } } public function getHeaderActions(): array { return [ Action::make('downloadTemplate') ->label('下载模板') ->icon('heroicon-o-arrow-down-tray') ->color('primary') ->action('downloadTemplate'), Action::make('import') ->label('导入数据') ->icon('heroicon-o-cloud-arrow-up') ->color('success') ->action('importData') ->requiresConfirmation() ->modalHeading('确认导入') ->modalDescription('确定要导入Excel文件中的数据吗?此操作将同步到题库服务。') ->modalSubmitActionLabel('确认导入'), ]; } public function downloadTemplate() { try { $importer = app(TextbookExcelImporter::class); if ($this->selectedType === 'textbook_series') { $filePath = $importer->generateTextbookSeriesTemplate(); $fileName = '教材系列导入模板.xlsx'; } elseif ($this->selectedType === 'textbook') { $filePath = $importer->generateTextbookTemplate(); $fileName = '教材导入模板.xlsx'; } else { $filePath = $importer->generateTextbookCatalogTemplate(); $fileName = '教材目录导入模板.xlsx'; } return response()->download($filePath, $fileName)->deleteFileAfterSend(); } catch (\Exception $e) { Notification::make() ->title('模板生成失败') ->body($e->getMessage()) ->danger() ->send(); } } public function importData() { $this->validate(); try { $importer = app(TextbookExcelImporter::class); // 保存上传的文件 $path = $this->file->store('imports', 'local'); // 获取完整文件路径 $fullPath = storage_path('app/' . $path); // 执行导入 if ($this->selectedType === 'textbook_series') { $result = $importer->importTextbookSeries($fullPath); } elseif ($this->selectedType === 'textbook') { $result = $importer->importTextbook($fullPath); } else { // 教材目录导入 - 需要从Excel中获取textbook_id $spreadsheet = IOFactory::load($fullPath); $sheet = $spreadsheet->getActiveSheet(); $data = $sheet->toArray(); // 获取第一行数据中的教材ID $firstRow = $data[1] ?? []; $textbookId = (int)($firstRow[0] ?? 0); if ($textbookId <= 0) { throw new \Exception('Excel文件中未找到有效的教材ID,请确保第一列包含教材ID'); } $result = $importer->importTextbookCatalog($fullPath, $textbookId); } // 删除临时文件 Storage::disk('local')->delete($path); $this->importResult = $result; if ($result['success']) { $message = sprintf( '导入完成!成功: %d 条,失败: %d 条', $result['success_count'], $result['error_count'] ); Notification::make() ->title('导入成功') ->body($message) ->success() ->send(); } else { Notification::make() ->title('导入失败') ->body($result['message']) ->danger() ->send(); } } catch (\Exception $e) { Notification::make() ->title('导入失败') ->body($e->getMessage()) ->danger() ->send(); Log::error('Excel导入失败', ['error' => $e->getMessage()]); } } }