import SwiftUI enum LocationTemplate: String, CaseIterable, Codable, Identifiable { case livingRoom = "LIVING_ROOM", bedroom = "BEDROOM", study = "STUDY", kitchen = "KITCHEN" case bathroom = "BATHROOM", room = "ROOM", entry = "ENTRY", balcony = "BALCONY", area = "AREA" case sofa = "SOFA", bed = "BED", desk = "DESK", tvStand = "TV_STAND", wardrobe = "WARDROBE" case bookcase = "BOOKCASE", shelf = "SHELF", table = "TABLE", storageBox = "STORAGE_BOX" var id: String { rawValue } var name: String { switch self { case .livingRoom: "客厅" case .bedroom: "卧室" case .study: "书房" case .kitchen: "厨房" case .bathroom: "卫生间" case .room: "房间" case .entry: "玄关" case .balcony: "阳台" case .area: "开放区域" case .sofa: "转角沙发" case .bed: "床" case .desk: "书桌" case .tvStand: "电视柜" case .wardrobe: "衣柜" case .bookcase: "书架" case .shelf: "层架" case .table: "边几" case .storageBox: "收纳箱" } } enum Kind { case room, area, furniture } var kind: Kind { switch self { case .livingRoom, .bedroom, .study, .kitchen, .bathroom, .room: .room case .entry, .balcony, .area: .area default: .furniture } } var dimensions: (width: Int, depth: Int) { switch self { case .livingRoom: (4000, 3400) case .bedroom, .study, .room: (3000, 2800) case .kitchen: (2600, 2400) case .bathroom: (2100, 1900) case .entry, .balcony, .area: (2200, 1500) case .sofa: (2300, 1400) case .bed: (1600, 2100) case .desk, .tvStand: (1400, 620) case .wardrobe: (1600, 650) case .bookcase, .shelf: (1100, 450) case .table: (600, 600) case .storageBox: (500, 450) } } static func suggested(for slot: LayoutLocation, isRoot: Bool) -> Self { if slot.name.contains("沙发") { return .sofa } if let known = LocationTemplate(rawValue: slot.icon), isRoot || known.kind != .room { return known } return isRoot ? .room : .storageBox } } struct LocationGeometry: Codable, Equatable { var template: LocationTemplate var xMm: Int var yMm: Int var widthMm: Int var depthMm: Int var rotation = 0 var right: Int { xMm + widthMm } var bottom: Int { yMm + depthMm } func overlaps(_ other: Self) -> Bool { xMm < other.right && other.xMm < right && yMm < other.bottom && other.yMm < bottom } } struct LayoutLocation: Decodable, Identifiable, Equatable { let id: UUID let name: String let icon: String var geometry: LocationGeometry? } struct LocationLayoutSnapshot: Decodable { let version: UUID let widthMm: Int let depthMm: Int let locations: [LayoutLocation] } struct LocationPlacement: Encodable { let id: UUID let newName: String? let geometry: LocationGeometry } extension InventoryStore { func locationLayout(parent: UUID?, refresh: Bool = false) async throws -> LocationLayoutSnapshot { let query = parent.map { "?parentId=\($0)" } ?? "" return try await account.read(root + "/location-layout" + query, refresh: refresh) } func saveLocationLayout(parent: UUID?, version: UUID, placements: [LocationPlacement]) async throws -> LocationLayoutSnapshot { struct Input: Encodable { let parentId: UUID? let version: UUID let placements: [LocationPlacement] } let snapshot: LocationLayoutSnapshot = try await send(root + "/location-layout", method: "PUT", Input(parentId: parent, version: version, placements: placements)) changed() return snapshot } } struct LocationPlanSection: View { let store: InventoryStore let parent: Place? let refreshRequest: Int let open: (UUID) -> Void @State private var snapshot: LocationLayoutSnapshot? @State private var error: String? @State private var editing = false var body: some View { Section { if let snapshot { let placed = snapshot.locations.filter { $0.geometry != nil } if placed.isEmpty { ContentUnavailableView("还没有摆放位置", systemImage: "square.dashed", description: Text(store.canWrite ? "可以摆放已有位置,或用模板新建。" : "空间成员摆放后会显示在这里。")) } else { LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed, selected: nil, editing: false, open: open) DisclosureGroup("图上的位置") { ForEach(placed) { place in Button(place.name) { open(place.id) }.buttonStyle(.borderless) } } } let unplaced = snapshot.locations.filter { $0.geometry == nil } if !unplaced.isEmpty { DisclosureGroup("未摆放 \(unplaced.count) 处") { ForEach(unplaced) { place in Button(place.name) { open(place.id) }.buttonStyle(.borderless) } } } if store.canWrite { Button { editing = true } label: { Label("编辑平面图", systemImage: "square.and.pencil") } } } else if error == nil { ProgressView("正在读取平面图") } if let error { Text(error).font(.footnote).foregroundStyle(.secondary) Button("重新读取") { Task { await load(refresh: true) } } } } header: { LocationLevelHeading(level: parent == nil ? .room : .furniture) } .task(id: "\(store.revision):\(refreshRequest)") { await load(refresh: refreshRequest > 0) } .fullScreenCover(isPresented: $editing) { if let snapshot { LocationPlanEditor(store: store, parent: parent, snapshot: snapshot) { saved in self.snapshot = saved } } } } private func load(refresh: Bool = false) async { do { snapshot = try await store.locationLayout(parent: parent?.id, refresh: refresh) error = nil } catch where !Task.isCancelled { if (error as? AtlasError)?.resourceUnavailable == true { snapshot = nil } self.error = error.localizedDescription } catch {} } } struct LocationPlanHistory { struct Edit { var locations: [LayoutLocation] var selection: UUID? } private(set) var current: Edit private var past: [Edit] = [] private var future: [Edit] = [] init(_ locations: [LayoutLocation]) { current = Edit(locations: locations) } var canUndo: Bool { !past.isEmpty } var canRedo: Bool { !future.isEmpty } mutating func select(_ id: UUID?) { current.selection = id } mutating func apply(_ locations: [LayoutLocation], selected: UUID?) { if locations != current.locations { past.append(current) future.removeAll() } current = Edit(locations: locations, selection: selected) } mutating func undo() { guard let previous = past.popLast() else { return } future.append(current) current = previous } mutating func redo() { guard let next = future.popLast() else { return } past.append(current) current = next } } private struct LocationPlanEditor: View { let store: InventoryStore let parent: Place? let onSave: (LocationLayoutSnapshot) -> Void @Environment(\.dismiss) private var dismiss @State private var snapshot: LocationLayoutSnapshot @State private var history: LocationPlanHistory @State private var choosingTemplate = false @State private var showingProperties = false @State private var showingAI = false @State private var snapping = true @State private var saving = false @State private var error: String? @State private var conflicted = false @State private var confirmingReload = false @State private var confirmingDiscard = false init(store: InventoryStore, parent: Place?, snapshot: LocationLayoutSnapshot, onSave: @escaping (LocationLayoutSnapshot) -> Void) { self.store = store self.parent = parent self.onSave = onSave _snapshot = State(initialValue: snapshot) _history = State(initialValue: LocationPlanHistory(snapshot.locations)) } private var edit: LocationPlanHistory.Edit { history.current } private var placed: [LayoutLocation] { edit.locations.filter { $0.geometry != nil } } private var unplaced: [LayoutLocation] { edit.locations.filter { $0.geometry == nil } } private var selected: LayoutLocation? { placed.first { $0.id == edit.selection } } private var dirty: Bool { edit.locations != snapshot.locations } var body: some View { NavigationStack { VStack(spacing: 0) { tools .padding(.horizontal, 14) LocationPlanCanvas(width: snapshot.widthMm, depth: snapshot.depthMm, locations: placed, selected: edit.selection, editing: true, open: { history.select($0) }, change: change, expanded: true, snapping: snapping) .padding(.horizontal, 10) .padding(.bottom, 8) footer } .background(Color(uiColor: .systemGroupedBackground)) .disabled(saving) .navigationTitle("编辑平面图") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button(dirty ? "放弃" : "取消") { if dirty { confirmingDiscard = true } else { dismiss() } } .disabled(saving) } ToolbarItem(placement: .confirmationAction) { Button(saving ? "保存中" : "保存") { Task { await save() } } .disabled(saving || !dirty) } } .sheet(isPresented: $choosingTemplate) { LocationTemplatePicker(isRoot: parent == nil, names: Set(edit.locations.map(\.name)), add: add) } .sheet(isPresented: $showingProperties) { if let selected, let geometry = selected.geometry { LocationPropertiesEditor(place: selected, geometry: geometry, isRoot: parent == nil) { change(selected.id, $0) } } } .sheet(isPresented: $showingAI) { LocationPlanAssistant(store: store, parent: parent, snapshot: snapshot, locations: edit.locations) { accepted in record(accepted, selected: nil) } } .alert("放弃本次修改?", isPresented: $confirmingDiscard) { Button("继续编辑", role: .cancel) {} Button("放弃修改", role: .destructive) { dismiss() } } message: { Text("本次移动、尺寸调整和新增位置都会撤销。") } .confirmationDialog("加载最新平面图?", isPresented: $confirmingReload, titleVisibility: .visible) { Button("重新加载", role: .destructive) { Task { await reload() } } } message: { Text("重新加载会舍弃本次未保存的调整。") } } .interactiveDismissDisabled(dirty || saving) } private var tools: some View { HStack(spacing: 13) { if let parent { Text(parent.name).font(.subheadline.weight(.semibold)).lineLimit(1) } Spacer(minLength: 0) Button("撤回", systemImage: "arrow.uturn.backward", action: undo) .disabled(!history.canUndo) Button("重做", systemImage: "arrow.uturn.forward", action: redo) .disabled(!history.canRedo) Button { snapping.toggle() } label: { Label(snapping ? "吸附开启" : "吸附关闭", systemImage: "squareshape.split.3x3") .foregroundStyle(snapping ? Color.atlasBlue : Color.secondary) } .accessibilityAddTraits(snapping ? .isSelected : []) } .labelStyle(.titleAndIcon) .font(.subheadline.weight(.medium)) .buttonStyle(.borderless) .frame(minHeight: 45) } private var footer: some View { VStack(alignment: .leading, spacing: 8) { if let selected { HStack { Text(selected.name).font(.subheadline.weight(.semibold)).lineLimit(1) Spacer() Button("属性") { showingProperties = true } Menu { Button("旋转 90°", systemImage: "rotate.right") { rotate(selected) } Button("移出平面图", systemImage: "minus.square", role: .destructive) { remove(selected.id) } } label: { Label("位置操作", systemImage: "ellipsis.circle").labelStyle(.iconOnly) .frame(width: 36, height: 35) } } Divider() } if let error { Text(error).font(.footnote).foregroundStyle(.red) if conflicted { Button("加载最新平面图") { confirmingReload = true }.font(.subheadline) } } HStack(spacing: 10) { Menu { Button("添加模板", systemImage: "square.grid.2x2") { choosingTemplate = true } if !unplaced.isEmpty { Menu("摆放已有位置", systemImage: "square.dashed") { ForEach(unplaced) { place in Button(place.name) { placeExisting(place) } } } } } label: { Label("添加", systemImage: "plus") .frame(maxWidth: .infinity, minHeight: 33) } .buttonStyle(.bordered) Button { showingAI = true } label: { Label("AI 建模", systemImage: "sparkles") .frame(maxWidth: .infinity, minHeight: 33) } .buttonStyle(.borderedProminent) } } .padding(.horizontal, 14).padding(.vertical, 8) .background(.regularMaterial) } private func record(_ locations: [LayoutLocation], selected: UUID?) { history.apply(locations, selected: selected) if !conflicted { error = nil } } private func undo() { history.undo() if !conflicted { error = nil } } private func redo() { history.redo() if !conflicted { error = nil } } private func change(_ id: UUID, _ proposed: LocationGeometry) { guard let index = edit.locations.firstIndex(where: { $0.id == id }) else { return } var geometry = proposed geometry.widthMm = min(snapshot.widthMm, max(100, geometry.widthMm)) geometry.depthMm = min(snapshot.depthMm, max(100, geometry.depthMm)) geometry.xMm = min(snapshot.widthMm - geometry.widthMm, max(0, geometry.xMm)) geometry.yMm = min(snapshot.depthMm - geometry.depthMm, max(0, geometry.yMm)) var updated = edit.locations updated[index].geometry = geometry record(updated, selected: id) } private func rotate(_ place: LayoutLocation) { guard var shape = place.geometry else { return } let width = shape.depthMm let depth = shape.widthMm guard width <= snapshot.widthMm && depth <= snapshot.depthMm else { error = "旋转后超出画布。请先调整尺寸。" return } shape.widthMm = width shape.depthMm = depth shape.rotation = (shape.rotation + 90) % 360 change(place.id, shape) } private func placeExisting(_ place: LayoutLocation) { let template = LocationTemplate.suggested(for: place, isRoot: parent == nil) if let geometry = suggestedPlacement(template) { change(place.id, geometry) } } private func add(_ template: LocationTemplate, _ name: String) { guard let geometry = suggestedPlacement(template) else { return } let id = UUID() let added = LayoutLocation(id: id, name: name, icon: template.rawValue, geometry: geometry) record(edit.locations + [added], selected: id) } private func suggestedPlacement(_ template: LocationTemplate) -> LocationGeometry? { let preferred = template.dimensions let occupied = placed.compactMap(\.geometry).filter { $0.template.kind == template.kind } for divisor in [1, 2] { let width = min(snapshot.widthMm, max(100, preferred.width / divisor)) let depth = min(snapshot.depthMm, max(100, preferred.depth / divisor)) for y in stride(from: 0, through: snapshot.depthMm - depth, by: 200) { for x in stride(from: 0, through: snapshot.widthMm - width, by: 200) { let geometry = LocationGeometry(template: template, xMm: x, yMm: y, widthMm: width, depthMm: depth) if !occupied.contains(where: { geometry.overlaps($0) }) { return geometry } } } } error = "画布没有足够空位。请先调整已有的位置。" return nil } private func remove(_ id: UUID) { guard let index = edit.locations.firstIndex(where: { $0.id == id }) else { return } var updated = edit.locations if snapshot.locations.contains(where: { $0.id == id }) { updated[index].geometry = nil } else { updated.remove(at: index) } record(updated, selected: nil) } private func save() async { guard !saving else { return } saving = true error = nil defer { saving = false } let existing = Set(snapshot.locations.map(\.id)) let request = edit.locations.compactMap { place in place.geometry.map { LocationPlacement(id: place.id, newName: existing.contains(place.id) ? nil : place.name, geometry: $0) } } do { let updated = try await store.saveLocationLayout(parent: parent?.id, version: snapshot.version, placements: request) onSave(updated) dismiss() } catch { self.error = error.localizedDescription conflicted = (error as? AtlasError)?.status == 409 } } private func reload() async { saving = true defer { saving = false } do { let updated = try await store.locationLayout(parent: parent?.id, refresh: true) snapshot = updated history = LocationPlanHistory(updated.locations) error = nil conflicted = false } catch { self.error = error.localizedDescription } } } private struct LocationPropertiesEditor: View { let place: LayoutLocation let isRoot: Bool let apply: (LocationGeometry) -> Void @State private var geometry: LocationGeometry @Environment(\.dismiss) private var dismiss @FocusState private var field: String? init(place: LayoutLocation, geometry: LocationGeometry, isRoot: Bool, apply: @escaping (LocationGeometry) -> Void) { self.place = place self.isRoot = isRoot self.apply = apply _geometry = State(initialValue: geometry) } var body: some View { NavigationStack { Form { Section("尺寸与坐标") { measure("宽度", key: \.widthMm) measure("深度", key: \.depthMm) measure("距左边", key: \.xMm) measure("距上边", key: \.yMm) } Section { Picker("模板", selection: $geometry.template) { ForEach(LocationTemplate.allCases.filter { isRoot || $0.kind != .room }) { template in Text(template.name).tag(template) } } } } .dismissibleKeyboard(active: field != nil) { field = nil } .navigationTitle(place.name) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("应用") { field = nil apply(geometry) dismiss() } } } } } private func measure(_ label: String, key: WritableKeyPath) -> some View { LabeledContent(label) { TextField("厘米", value: Binding(get: { geometry[keyPath: key] / 10 }, set: { geometry[keyPath: key] = min(2400, max(0, $0)) * 10 }), format: .number.grouping(.never)) .keyboardType(.numberPad) .focused($field, equals: label) .multilineTextAlignment(.trailing) Text("厘米").foregroundStyle(.secondary) } } } private struct LocationTemplatePicker: View { let isRoot: Bool let names: Set let add: (LocationTemplate, String) -> Void @Environment(\.dismiss) private var dismiss @State private var template: LocationTemplate? @State private var name = "" @FocusState private var focused: Bool private var trimmed: String { name.trimmingCharacters(in: .whitespacesAndNewlines) } private var available: [LocationTemplate] { LocationTemplate.allCases.filter { isRoot || $0.kind != .room } } var body: some View { NavigationStack { ScrollView { VStack(alignment: .leading, spacing: 14) { if template != nil { TextField("位置名称", text: $name) .textFieldStyle(.roundedBorder) .focused($focused) if names.contains(trimmed) { Text("当前层级已有同名位置。").font(.footnote).foregroundStyle(.secondary) } } LazyVGrid(columns: [GridItem(.adaptive(minimum: 88), spacing: 8)], spacing: 8) { ForEach(available) { choice in Button { focused = false template = choice name = availableName(choice.name) } label: { VStack(spacing: 5) { LocationFloorArt(template: choice, rotation: 0) .frame(width: 57, height: 40) .accessibilityHidden(true) Text(choice.name).font(.subheadline).foregroundStyle(.primary) } .padding(8) .frame(maxWidth: .infinity, minHeight: 79) .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 10)) .overlay { if choice == template { RoundedRectangle(cornerRadius: 10).stroke(Color.atlasBlue, lineWidth: 2) } } } .buttonStyle(.plain) .accessibilityAddTraits(choice == template ? .isSelected : []) } } } .padding(16) } .background(Color(uiColor: .systemGroupedBackground)) .dismissibleKeyboard(active: focused) { focused = false } .navigationTitle("添加模板") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("摆放") { if let template { add(template, trimmed); dismiss() } } .disabled(template == nil || trimmed.isEmpty || trimmed.utf16.count > 100 || names.contains(trimmed)) } } } } private func availableName(_ title: String) -> String { var unique = title var suffix = 2 while names.contains(unique) { unique = "\(title) \(suffix)" suffix += 1 } return unique } }