dao = $dao; } public function importFromExcel(string $filePath): array { $sheet = IOFactory::load($filePath)->getActiveSheet(); $rows = $sheet->toArray('', true, true, false); if (count($rows) < 2) { throw new \InvalidArgumentException('导入文件至少应包含表头和一条硬件故障描述数据'); } $headers = array_map(static fn ($value) => trim((string) $value), $rows[0]); $indexes = array_flip($headers); foreach (['分类', '描述'] as $header) { if (!array_key_exists($header, $indexes)) { throw new \InvalidArgumentException('导入表头必须包含:分类、描述'); } } return $this->transaction(function () use ($rows, $indexes) { $created = 0; $updated = 0; $categories = []; foreach (array_slice($rows, 1) as $rowNumber => $row) { $categoryName = trim((string) ($row[$indexes['分类']] ?? '')); $description = trim((string) ($row[$indexes['描述']] ?? '')); if ($categoryName === '' && $description === '') { continue; } if ($categoryName === '' || $description === '') { throw new \InvalidArgumentException('第 ' . ($rowNumber + 2) . ' 行的分类、描述均不能为空'); } $category = $categories[$categoryName] ?? null; if (!$category) { $category = MaterialCategory::query()->withTrashed()->where('category_name', $categoryName)->first(); if ($category?->trashed()) { $category->restore(); } $category ??= MaterialCategory::query()->create(['category_name' => $categoryName]); $categories[$categoryName] = $category; } $faultDescription = HardwareFaultDescription::query() ->withTrashed() ->where('category_id', $category->id) ->where('description', $description) ->first(); if ($faultDescription) { if ($faultDescription->trashed()) { $faultDescription->restore(); } $updated++; continue; } HardwareFaultDescription::query()->create([ 'category_id' => $category->id, 'description' => $description, ]); $created++; } return ['created' => $created, 'updated' => $updated]; }); } }