// // CreateTravelAlbumSheetViewController.swift // suixinkan // import SnapKit import UIKit /// 新建相册任务底部 Sheet,对齐 Android `CreateTravelAlbumModal`。 final class CreateTravelAlbumSheetViewController: BaseViewController { private let viewModel: TravelAlbumEntryViewModel private let api: any TravelAlbumServing private let scrollView = UIScrollView() private let contentView = UIView() private let titleLabel = UILabel() private let preShootCard = TravelAlbumModeOptionView() private let preOrderCard = TravelAlbumModeOptionView() private let orderPicker = UIButton(type: .system) private let fieldsStack = UIStackView() private let freeCountField = UITextField() private let singlePriceField = UITextField() private let packagePriceField = UITextField() private let autoRetouchSectionView = UIView() private let autoRetouchTitleLabel = UILabel() private let autoRetouchDetailLabel = UILabel() private let noRetouchOption = TravelAlbumModeOptionView() private let aiRetouchOption = TravelAlbumModeOptionView() private let cancelButton = UIButton(type: .system) private let confirmButton = UIButton(type: .system) private var renderedMode: TravelAlbumEntryViewModel.CreateMode? init(viewModel: TravelAlbumEntryViewModel, api: any TravelAlbumServing) { self.viewModel = viewModel self.api = api super.init(nibName: nil, bundle: nil) modalPresentationStyle = .pageSheet if let sheetPresentationController { let formDetent = UISheetPresentationController.Detent.Identifier("createTravelAlbumForm") sheetPresentationController.detents = [ .custom(identifier: formDetent) { min(650, $0.maximumDetentValue) }, .large(), ] sheetPresentationController.selectedDetentIdentifier = formDetent sheetPresentationController.prefersGrabberVisible = false sheetPresentationController.preferredCornerRadius = 22 } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setupNavigationBar() {} override func setupUI() { view.backgroundColor = .white titleLabel.text = "新建相册任务" titleLabel.font = .systemFont(ofSize: 18, weight: .semibold) titleLabel.textColor = AppColor.textPrimary titleLabel.textAlignment = .center fieldsStack.axis = .vertical fieldsStack.spacing = 14 configurePicker(orderPicker, accessibilityIdentifier: "travelAlbum.create.order") configureTextField(freeCountField, placeholder: "请输入免费张数", keyboardType: .numberPad) configureTextField(singlePriceField, placeholder: "请输入单张照片价格", keyboardType: .decimalPad) configureTextField(packagePriceField, placeholder: "请输入打包价格", keyboardType: .decimalPad) configureAutoRetouchSection() configureActionButton(cancelButton, title: "取消", backgroundColor: UIColor(hex: 0xF4F4F4), titleColor: AppColor.textSecondary) configureActionButton(confirmButton, title: "确定", backgroundColor: AppColor.primary, titleColor: .white) view.addSubview(scrollView) scrollView.addSubview(contentView) [titleLabel, preShootCard, preOrderCard, fieldsStack, cancelButton, confirmButton].forEach(contentView.addSubview) applyCreateState() } override func setupConstraints() { scrollView.snp.makeConstraints { make in make.edges.equalTo(view.safeAreaLayoutGuide) } contentView.snp.makeConstraints { make in make.edges.equalToSuperview() make.width.equalToSuperview() } titleLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(18) make.leading.trailing.equalToSuperview().inset(20) } preShootCard.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(18) make.leading.trailing.equalToSuperview().inset(16) } preOrderCard.snp.makeConstraints { make in make.top.equalTo(preShootCard.snp.bottom).offset(10) make.leading.trailing.equalTo(preShootCard) } fieldsStack.snp.makeConstraints { make in make.top.equalTo(preOrderCard.snp.bottom).offset(18) make.leading.trailing.equalTo(preShootCard) } cancelButton.snp.makeConstraints { make in make.top.equalTo(fieldsStack.snp.bottom).offset(22) make.leading.equalToSuperview().offset(16) make.height.equalTo(48) make.width.equalTo(confirmButton) make.bottom.equalToSuperview().offset(-16) } confirmButton.snp.makeConstraints { make in make.top.height.width.equalTo(cancelButton) make.leading.equalTo(cancelButton.snp.trailing).offset(12) make.trailing.equalToSuperview().offset(-16) } } override func bindActions() { preShootCard.addTarget(self, action: #selector(preShootTapped), for: .touchUpInside) preOrderCard.addTarget(self, action: #selector(preOrderTapped), for: .touchUpInside) orderPicker.addTarget(self, action: #selector(retryOrdersTapped), for: .touchUpInside) cancelButton.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside) confirmButton.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside) [freeCountField, singlePriceField, packagePriceField].forEach { $0.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged) } noRetouchOption.addTarget(self, action: #selector(noRetouchTapped), for: .touchUpInside) aiRetouchOption.addTarget(self, action: #selector(aiRetouchTapped), for: .touchUpInside) sheetPresentationController?.delegate = self viewModel.onCreateStateChange = { [weak self] in Task { @MainActor in self?.applyCreateState() } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if isBeingDismissed { viewModel.dismissCreateSheet() } } private func configureTextField(_ field: UITextField, placeholder: String, keyboardType: UIKeyboardType) { field.placeholder = placeholder field.keyboardType = keyboardType field.font = .systemFont(ofSize: 14) field.layer.cornerRadius = 8 field.layer.borderWidth = 1 field.layer.borderColor = AppColor.border.cgColor field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1)) field.leftViewMode = .always field.snp.makeConstraints { make in make.height.equalTo(44) } } private func configureActionButton(_ button: UIButton, title: String, backgroundColor: UIColor, titleColor: UIColor) { button.setTitle(title, for: .normal) button.setTitleColor(titleColor, for: .normal) button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) button.backgroundColor = backgroundColor button.layer.cornerRadius = 10 } private func configurePicker(_ button: UIButton, accessibilityIdentifier: String) { var configuration = UIButton.Configuration.plain() configuration.contentInsets = .init(top: 8, leading: 12, bottom: 8, trailing: 12) configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { var attributes = $0 attributes.font = .systemFont(ofSize: 14) return attributes } button.configuration = configuration button.contentHorizontalAlignment = .leading button.layer.cornerRadius = 8 button.layer.borderWidth = 1 button.layer.borderColor = AppColor.border.cgColor button.accessibilityIdentifier = accessibilityIdentifier button.snp.makeConstraints { $0.height.equalTo(44) } } private func rebuildFields() { renderedMode = viewModel.createMode fieldsStack.arrangedSubviews.forEach { $0.removeFromSuperview() } switch viewModel.createMode { case .preShoot: fieldsStack.addArrangedSubview(makeFieldGroup(title: "免费张数", required: false, field: freeCountField)) fieldsStack.addArrangedSubview(makeFieldGroup(title: "单张照片价格(元)", required: true, field: singlePriceField)) fieldsStack.addArrangedSubview(makeFieldGroup(title: "打包价格(元)", required: false, field: packagePriceField)) case .preOrder: fieldsStack.addArrangedSubview(makeFieldGroup(title: "绑定订单", required: true, field: orderPicker)) } fieldsStack.addArrangedSubview(autoRetouchSectionView) } private func applyCreateState() { guard viewModel.isCreateSheetVisible else { if !isBeingDismissed { presentingViewController?.dismiss(animated: true) } return } if renderedMode != viewModel.createMode { rebuildFields() } preShootCard.apply( title: "先拍后买", desc: "拍完后分享给用户,用户在小程序上选择性购买", selected: viewModel.createMode == .preShoot ) preOrderCard.apply( title: "先买后拍", desc: "关联当前景区的已购订单,再开始拍摄", selected: viewModel.createMode == .preOrder ) applyOrderPicker() updateAutoRetouchSection() let isCreating = viewModel.isCreating isModalInPresentation = isCreating preShootCard.isEnabled = !isCreating preOrderCard.isEnabled = !isCreating noRetouchOption.isEnabled = !isCreating aiRetouchOption.isEnabled = !isCreating aiRetouchOption.alpha = aiRetouchOption.isEnabled ? 1 : 0.5 cancelButton.isEnabled = !isCreating [freeCountField, singlePriceField, packagePriceField].forEach { $0.isEnabled = !isCreating } confirmButton.setTitle(isCreating ? "创建中…" : "确定", for: .normal) updateConfirmAvailability() } private func applyOrderPicker() { guard viewModel.createMode == .preOrder, let scenicId = viewModel.createScenicId else { return } switch viewModel.orderLoadState { case .idle, .loading: applyPicker(orderPicker, title: "正在加载订单…") case .failed(let message): applyPicker(orderPicker, title: "订单加载失败,点击重试", retryMessage: message) case .loaded: let actions = viewModel.availableOrders.map { order in UIAction( title: orderTitle(order), state: order == viewModel.selectedOrder ? .on : .off ) { [weak self] _ in self?.viewModel.selectCreateOrder(number: order.orderNumber, scenicId: scenicId) } } let title = viewModel.selectedOrder.map(orderTitle) ?? (actions.isEmpty ? "当前景区暂无可关联订单" : "请选择绑定订单") applyPicker(orderPicker, title: title, actions: actions) } } private func orderTitle(_ order: TravelAlbumAvailableOrder) -> String { order.projectName.isEmpty ? order.orderNumber : "\(order.projectName) · \(order.orderNumber)" } private func applyPicker(_ button: UIButton, title: String, actions: [UIAction] = [], retryMessage: String? = nil) { button.configuration?.title = title button.configuration?.image = actions.isEmpty ? nil : UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10)) button.configuration?.imagePlacement = .trailing button.configuration?.imagePadding = 8 button.menu = actions.isEmpty ? nil : UIMenu(children: actions) button.showsMenuAsPrimaryAction = !actions.isEmpty button.isEnabled = !viewModel.isCreating && (!actions.isEmpty || retryMessage != nil) button.configuration?.baseForegroundColor = button.isEnabled ? AppColor.textPrimary : AppColor.textSecondary button.accessibilityHint = retryMessage } private func updateConfirmAvailability() { let hasRequiredFields: Bool switch viewModel.createMode { case .preShoot: hasRequiredFields = Double(singlePriceField.text ?? "") != nil case .preOrder: hasRequiredFields = viewModel.orderLoadState == .loaded && viewModel.selectedOrder != nil } confirmButton.isEnabled = hasRequiredFields && !viewModel.isCreating confirmButton.alpha = confirmButton.isEnabled ? 1 : 0.45 } private func configureAutoRetouchSection() { autoRetouchSectionView.backgroundColor = .white autoRetouchSectionView.layer.cornerRadius = 10 autoRetouchSectionView.layer.borderWidth = 1 autoRetouchSectionView.layer.borderColor = AppColor.border.cgColor autoRetouchTitleLabel.text = "修图方式" autoRetouchTitleLabel.font = .systemFont(ofSize: 14, weight: .medium) autoRetouchTitleLabel.textColor = AppColor.textPrimary autoRetouchDetailLabel.text = "选择 AI 修图后,需要再选一个效果模板" autoRetouchDetailLabel.font = .systemFont(ofSize: 12) autoRetouchDetailLabel.textColor = AppColor.textSecondary let optionsStack = UIStackView(arrangedSubviews: [noRetouchOption, aiRetouchOption]) optionsStack.axis = .horizontal optionsStack.spacing = 10 optionsStack.distribution = .fillEqually autoRetouchSectionView.addSubview(autoRetouchTitleLabel) autoRetouchSectionView.addSubview(autoRetouchDetailLabel) autoRetouchSectionView.addSubview(optionsStack) autoRetouchTitleLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(12) make.leading.trailing.equalToSuperview().inset(14) } autoRetouchDetailLabel.snp.makeConstraints { make in make.top.equalTo(autoRetouchTitleLabel.snp.bottom).offset(4) make.leading.trailing.equalTo(autoRetouchTitleLabel) } optionsStack.snp.makeConstraints { make in make.top.equalTo(autoRetouchDetailLabel.snp.bottom).offset(12) make.leading.trailing.bottom.equalToSuperview().inset(12) make.height.equalTo(76) } updateAutoRetouchSection() } private func makeFieldGroup(title: String, required: Bool, field: UIView) -> UIView { let container = UIView() let label = UILabel() label.attributedText = fieldTitle(title, required: required) container.addSubview(label) container.addSubview(field) label.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() } field.snp.makeConstraints { make in make.top.equalTo(label.snp.bottom).offset(8) make.leading.trailing.bottom.equalToSuperview() } return container } private func fieldTitle(_ text: String, required: Bool) -> NSAttributedString { let result = NSMutableAttributedString( string: text, attributes: [.font: UIFont.systemFont(ofSize: 14, weight: .medium), .foregroundColor: AppColor.textPrimary] ) if required { result.append(NSAttributedString(string: " *", attributes: [.foregroundColor: UIColor.red])) } return result } @objc private func preShootTapped() { view.endEditing(true) Task { @MainActor in await viewModel.selectCreateMode(.preShoot, api: api) } } @objc private func preOrderTapped() { view.endEditing(true) Task { @MainActor in await viewModel.selectCreateMode(.preOrder, api: api) } } @objc private func retryOrdersTapped() { guard case .failed = viewModel.orderLoadState else { return } Task { @MainActor in await viewModel.loadAvailableOrders(api: api) } } @objc private func cancelTapped() { guard !viewModel.isCreating else { return } viewModel.dismissCreateSheet() dismiss(animated: true) } @objc private func confirmTapped() { view.endEditing(true) Task { @MainActor in await viewModel.confirmCreate( freeCount: freeCountField.text ?? "", singlePrice: singlePriceField.text ?? "", packagePrice: packagePriceField.text ?? "", api: api ) } } @objc private func noRetouchTapped() { guard let scenicId = viewModel.activeCreateScenicId() else { return } viewModel.setCreateRetouchConfiguration(.disabled, scenicId: scenicId) } @objc private func aiRetouchTapped() { guard presentedViewController == nil, !viewModel.isCreating, let scenicId = viewModel.activeCreateScenicId() else { return } let settingViewModel = TravelAlbumAutoRetouchSettingViewModel( scenicId: scenicId, configuration: viewModel.createRetouchConfiguration, allowsModeSelection: false ) let controller = TravelAlbumAutoRetouchSettingSheetViewController( viewModel: settingViewModel, api: api ) controller.onConfirm = { [weak self] configuration in self?.viewModel.setCreateRetouchConfiguration(configuration, scenicId: scenicId) } present(controller, animated: true) } private func updateAutoRetouchSection() { let isEnabled = viewModel.createRetouchConfiguration.enabled noRetouchOption.apply(title: "不修图", desc: "保留原图", selected: !isEnabled) aiRetouchOption.apply( title: "AI 修图", desc: isEnabled ? "已选择模板" : "点击选模板", selected: isEnabled ) } @objc private func textFieldEditingChanged(_ field: UITextField) { let text = field.text ?? "" if field === freeCountField { field.text = text.filter(\.isNumber) } else { field.text = sanitizeMoneyInput(text) } updateConfirmAvailability() } private func sanitizeMoneyInput(_ value: String) -> String { var result = "" var hasDot = false for char in value { if char.isNumber { result.append(char) } else if char == ".", !hasDot { result.append(char) hasDot = true } } guard !result.isEmpty else { return "" } if result.hasPrefix(".") { result = "0" + result } guard let dotIndex = result.firstIndex(of: ".") else { let trimmed = result.drop { $0 == "0" } return trimmed.isEmpty ? "0" : String(trimmed) } let integerPart = result[..