$row) { $region = $row[0] ?? null; if (!is_string($region) || blank($region)) continue; foreach ($row as $column => $value) { if ($column === 0 || !is_numeric($value) || filled($source['formulas'][$rowIndex][$column] ?? null)) continue; $priceColumns[$column] ??= $rowIndex; $regions[$rowIndex] = $region; } } ksort($priceColumns); $columns = []; foreach ($priceColumns as $column => $firstPriceRow) { $columns[$column] = '价格列 ' . $column; for ($row = $firstPriceRow - 1; $row >= 0; $row--) { $label = $values[$row][$column] ?? null; if (!is_string($label) || blank($label) || isset($regions[$row])) continue; $columns[$column] = trim($label); break; } } $remarks = null; $firstRegionRow = array_key_first($regions) ?? 0; for ($row = $firstRegionRow - 1; $row >= 0 && $remarks === null; $row--) { foreach ($values[$row] ?? [] as $column => $label) { if ($column > 0 && !isset($columns[$column]) && is_string($label) && preg_match('/^(报价备注|备注|说明)[::]?$/u', trim($label))) { $remarks = $column; break; } } } return [$columns, $remarks, array_values($regions), array_keys($regions)]; } public static function apply(array $source, array $additions): array { if ($additions === []) return $source; [$columns, $remarks, $regions, $rowKeys] = self::fields($source); $normalize = static fn ($name) => preg_replace('/(?:壮族自治区|回族自治区|维吾尔自治区|自治区|特别行政区|省|市)$/u', '', trim($name)); $existing = array_map($normalize, preg_split('/[、,,\/\s;;++]+/u', implode('、', $regions), -1, PREG_SPLIT_NO_EMPTY)); $rows = []; foreach ($additions as $index => $addition) { $region = $normalize($addition['region']); if ($region === '' || in_array($region, $existing, true)) { throw ValidationException::withMessages(["province_additions.$index.region" => '省份已存在,请直接编辑原报价行。']); } if ($columns === [] || array_keys($columns) !== array_keys(array_intersect_key($columns, $addition['prices'])) || array_diff_key($addition['prices'], $columns)) { throw ValidationException::withMessages(["province_additions.$index.prices" => '请填写该省份的全部价格列。']); } $existing[] = $region; $row = array_fill(0, max(array_keys($columns)) + 1, null); $row[0] = $addition['region']; foreach ($columns as $column => $label) { $row[$column] = (float) $addition['prices'][$column]; } if ($remarks !== null) $row[$remarks] = $addition['note'] ?? null; ksort($row); $rows[] = array_replace(array_fill(0, max(array_keys($row)) + 1, null), $row); } $offset = (int) end($rowKeys) + 1; $formulas = array_replace(array_fill(0, count($source['values']), []), $source['formulas']); array_splice($source['values'], $offset, 0, $rows); array_splice($formulas, $offset, 0, array_fill(0, count($rows), [])); $source['formulas'] = $formulas; return $source; } }