import SnapKit import UIKit /// 真实套餐收款记录页,展示接口汇总与分页明细,不进入拍摄订单或演示流程。 @MainActor final class DroneDockReceiptsViewController: BaseViewController { /// 当前页面的收款查询状态。 let viewModel: DroneDockReceiptsViewModel private let tableView = UITableView(frame: .zero, style: .plain) private var dataSource: UITableViewDiffableDataSource! private var loadTask: Task? private var operation: LoadAction? /// 汇总与收款记录使用独立分区,空态也由同一 Diffable 数据源管理。 private enum Section: Hashable { case summary, receipts } /// 订单号作为列表的稳定身份,金额更新不生成重复记录。 private enum Item: Hashable { case summary, receipt(String), message } /// 区分整页刷新与保留现有记录的分页请求。 private enum LoadAction: Equatable { case refresh, more } /// 注入当前景区及可选套餐范围的记录模型。 init(viewModel: DroneDockReceiptsViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { loadTask?.cancel() } override func setupNavigationBar() { title = "收款记录" navigationItem.backButtonDisplayMode = .minimal } override func setupUI() { view.backgroundColor = DroneDockStyle.background tableView.backgroundColor = .clear tableView.separatorStyle = .none tableView.allowsSelection = false tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 230 tableView.sectionHeaderTopPadding = 0 tableView.accessibilityIdentifier = "drone.receipts.list" tableView.register(DroneDockReceiptSummaryCell.self, forCellReuseIdentifier: "summary") tableView.register(DroneDockReceiptCell.self, forCellReuseIdentifier: "receipt") tableView.register(DroneDockReceiptsMessageCell.self, forCellReuseIdentifier: "message") let refresh = UIRefreshControl() refresh.tintColor = DroneDockStyle.primary refresh.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged) tableView.refreshControl = refresh view.addSubview(tableView) configureDataSource() applySnapshot(animated: false) } override func setupConstraints() { tableView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.bottom.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) load(.refresh) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) loadTask?.cancel() operation = nil viewModel.invalidate() } private func configureDataSource() { dataSource = UITableViewDiffableDataSource(tableView: tableView) { [weak self] table, path, item in guard let self else { return nil } switch item { case .summary: let cell = table.dequeueReusableCell(withIdentifier: "summary", for: path) as! DroneDockReceiptSummaryCell cell.apply(self.operation == .refresh ? nil : self.viewModel.summary) return cell case .receipt(let orderNumber): let cell = table.dequeueReusableCell(withIdentifier: "receipt", for: path) as! DroneDockReceiptCell if let receipt = self.viewModel.receipts.first(where: { $0.orderNumber == orderNumber }) { cell.apply(receipt) } return cell case .message: let cell = table.dequeueReusableCell(withIdentifier: "message", for: path) as! DroneDockReceiptsMessageCell let isLoading = self.operation != nil || self.viewModel.isLoading let error = self.viewModel.errorMessage if isLoading || (self.viewModel.summary == nil && error == nil) { cell.apply(title: "正在加载收款记录", detail: "正在获取最新数据", canRetry: false) } else if let error { cell.apply(title: "收款记录加载失败", detail: error, canRetry: true) } else { cell.apply(title: "暂无收款记录", detail: "近7天暂无收款数据", canRetry: false) } cell.onRetry = { [weak self] in self?.load(.refresh) } return cell } } } private func load(_ action: LoadAction) { if action == .more, operation != nil || !viewModel.hasMore { return } loadTask?.cancel() operation = action applySnapshot(animated: false) loadTask = Task { @MainActor [weak self] in guard let self else { return } if action == .refresh { await self.viewModel.refresh() } else { await self.viewModel.loadMore() } guard !Task.isCancelled else { return } self.operation = nil self.tableView.refreshControl?.endRefreshing() self.applySnapshot(animated: true) { [weak self] in #if DEBUG guard action == .refresh, self?.viewModel.errorMessage == nil else { return } Task { @MainActor [weak self] in await self?.captureIfRequested() } #endif } } } private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) { guard dataSource != nil else { return } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([.summary, .receipts]) snapshot.appendItems([.summary], toSection: .summary) let records = operation == .refresh ? [] : viewModel.receipts.map { Item.receipt($0.orderNumber) } snapshot.appendItems(records.isEmpty ? [.message] : records, toSection: .receipts) let previous = Set(dataSource.snapshot().itemIdentifiers) snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) }) updateFooter() dataSource.apply(snapshot, animatingDifferences: animated, completion: completion) } private func updateFooter() { guard operation != .refresh, !viewModel.receipts.isEmpty else { tableView.tableFooterView = nil return } let footer = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 84)) let label = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) label.numberOfLines = 2 label.textAlignment = .center let button = UIButton(type: .system) button.tintColor = DroneDockStyle.primary button.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium) button.accessibilityIdentifier = "drone.receipts.loadMore" button.addTarget(self, action: #selector(loadMoreTriggered), for: .touchUpInside) if operation != nil { label.text = operation == .more ? "正在加载更多…" : "正在刷新…" button.isHidden = true } else if let error = viewModel.errorMessage { label.text = error button.setTitle("重试加载", for: .normal) } else if viewModel.hasMore { label.text = "已显示 \(viewModel.receipts.count) 条记录" button.setTitle("加载更多", for: .normal) } else { label.text = "已显示全部收款记录" button.isHidden = true } let stack = UIStackView(arrangedSubviews: [label, button]) stack.axis = .vertical stack.alignment = .center stack.spacing = 4 footer.addSubview(stack) stack.snp.makeConstraints { make in make.centerY.equalToSuperview() make.leading.trailing.equalToSuperview().inset(24) } button.snp.makeConstraints { $0.height.equalTo(36).priority(999) } tableView.tableFooterView = footer } @objc private func refreshTriggered() { load(.refresh) } @objc private func loadMoreTriggered() { load(.more) } #if DEBUG /// 显式联调时保存当前 App 的记录页,待 Diffable 动画与屏幕提交后再截图。 private func captureIfRequested() async { guard ProcessInfo.processInfo.arguments.contains("--dock-payment-capture") else { return } try? await Task.sleep(nanoseconds: 400_000_000) guard !Task.isCancelled, operation == nil, viewModel.summary != nil, navigationController?.topViewController === self, let window = view.window, window.windowScene?.activationState == .foregroundActive else { return } window.layoutIfNeeded() let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) } do { let folder = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("DroneDockPaymentDiagnostics", isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) try image.pngData()?.write(to: folder.appendingPathComponent("receipts.png"), options: .atomic) print("[DroneDockPayment] Receipts window screenshot saved") } catch { print("[DroneDockPayment] Receipts screenshot failed: \(error.localizedDescription)") } } #endif } /// 顶部收款汇总卡;现金金额与积分始终使用分开的展示区域。 @MainActor private final class DroneDockReceiptSummaryCell: UITableViewCell { private let card = UIView() private let stack = UIStackView() /// 建立自适应高度的汇总卡片。 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = .clear selectionStyle = .none DroneDockStyle.applyCard(to: card) stack.axis = .vertical stack.spacing = 16 contentView.addSubview(card) card.addSubview(stack) card.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 16, left: 16, bottom: 12, right: 16)) } stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 使用服务端完整汇总,尚未成功读取时保留未知占位。 func apply(_ summary: DroneDockReceiptSummary?) { stack.arrangedSubviews.forEach { $0.removeFromSuperview() } let title = DroneDockStyle.label("近7天收款汇总", size: 16, weight: .semibold) let count = DroneDockStyle.label(summary.map { "共 \($0.count) 笔" } ?? "—", size: 12, color: DroneDockStyle.secondary) count.setContentHuggingPriority(.required, for: .horizontal) let heading = UIStackView(arrangedSubviews: [title, count]) stack.addArrangedSubview(heading) stack.addArrangedSubview(DroneDockReceiptFormatting.cashColumns( paid: summary?.cashPaid, refund: summary?.cashRefund, net: summary?.cashNet, large: true)) if let summary, summary.pointsPaid != 0 || summary.pointsRefund != 0 || summary.pointsNet != 0 || summary.pointAmount != 0 { stack.addArrangedSubview(DroneDockReceiptFormatting.pointsView( paid: summary.pointsPaid, refund: summary.pointsRefund, net: summary.pointsNet, amount: summary.pointAmount)) } } } /// 单笔收款卡片,仅展示套餐与支付字段,不推测拍摄次数或订单业务状态。 @MainActor private final class DroneDockReceiptCell: UITableViewCell { private let card = UIView() private let stack = UIStackView() /// 建立白底卡片与适应多行名称的纵向内容。 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = .clear selectionStyle = .none DroneDockStyle.applyCard(to: card) stack.axis = .vertical stack.spacing = 12 contentView.addSubview(card) card.addSubview(stack) card.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 16, bottom: 12, right: 16)) } stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(16) } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 重建本笔内容,避免复用后残留上一笔积分或付款人信息。 func apply(_ receipt: DroneDockReceipt) { accessibilityIdentifier = "drone.receipt.\(receipt.orderNumber)" stack.arrangedSubviews.forEach { $0.removeFromSuperview() } let name = DroneDockStyle.label(receipt.projectName.isEmpty ? "套餐名称未提供" : receipt.projectName, size: 16, weight: .semibold) name.numberOfLines = 0 stack.addArrangedSubview(name) let payer = DroneDockStyle.label("付款人 \(receipt.payer.isEmpty ? "—" : receipt.payer)", size: 12, color: DroneDockStyle.secondary) payer.numberOfLines = 0 stack.addArrangedSubview(payer) stack.addArrangedSubview(DroneDockReceiptFormatting.cashColumns( paid: receipt.cashPaid, refund: receipt.cashRefund, net: receipt.cashNet, large: false)) if receipt.pointsPaid != 0 || receipt.pointsRefund != 0 || receipt.pointsNet != 0 || receipt.pointAmount != 0 { stack.addArrangedSubview(DroneDockReceiptFormatting.pointsView( paid: receipt.pointsPaid, refund: receipt.pointsRefund, net: receipt.pointsNet, amount: receipt.pointAmount)) } let separator = UIView() separator.backgroundColor = DroneDockStyle.border separator.snp.makeConstraints { $0.height.equalTo(1 / UIScreen.main.scale) } stack.addArrangedSubview(separator) let time = DroneDockStyle.label("支付时间 \(DroneDockReceiptFormatting.time(receipt.payTime))", size: 12, color: DroneDockStyle.secondary) let order = DroneDockStyle.label("订单号 \(receipt.orderNumber)", size: 12, color: DroneDockStyle.secondary) time.numberOfLines = 0 order.numberOfLines = 0 stack.addArrangedSubview(time) stack.addArrangedSubview(order) } } /// 收款记录的加载、空数据和失败重试提示。 @MainActor private final class DroneDockReceiptsMessageCell: UITableViewCell { /// 用户请求重新读取第一页。 var onRetry: (() -> Void)? private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium) private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary) private let retryButton = UIButton(type: .system) /// 创建适合空记录列表的居中提示。 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = .clear selectionStyle = .none titleLabel.textAlignment = .center titleLabel.numberOfLines = 0 detailLabel.textAlignment = .center detailLabel.numberOfLines = 0 retryButton.setTitle("重新加载", for: .normal) retryButton.tintColor = DroneDockStyle.primary retryButton.accessibilityIdentifier = "drone.receipts.retry" retryButton.addTarget(self, action: #selector(retryTapped), for: .touchUpInside) let icon = UIImageView(image: UIImage(systemName: "doc.text.magnifyingglass")) icon.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6) icon.contentMode = .scaleAspectFit icon.snp.makeConstraints { $0.size.equalTo(38) } let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel, retryButton]) stack.axis = .vertical stack.alignment = .center stack.spacing = 12 contentView.addSubview(stack) stack.snp.makeConstraints { make in make.top.bottom.equalToSuperview().inset(48) make.leading.trailing.equalToSuperview().inset(24) } retryButton.snp.makeConstraints { $0.height.equalTo(36).priority(999) } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 失败与成功空态分开表达,只有失败时提供重试动作。 func apply(title: String, detail: String, canRetry: Bool) { titleLabel.text = title detailLabel.text = detail retryButton.isHidden = !canRetry } @objc private func retryTapped() { onRetry?() } } /// 收款记录的展示格式,不计算或混合现金与积分账目。 @MainActor private enum DroneDockReceiptFormatting { /// 十进制金额按人民币展示两位小数,未知金额保留占位。 static func money(_ amount: Decimal?) -> String { guard let amount else { return "—" } let formatter = NumberFormatter() formatter.locale = Locale(identifier: "zh_CN") formatter.numberStyle = .decimal formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 return formatter.string(from: NSDecimalNumber(decimal: amount)).map { "¥" + $0 } ?? "—" } /// 后端支付时间是 Unix 秒,缺失的零值不展示为 1970 年。 static func time(_ timestamp: TimeInterval) -> String { guard timestamp > 0 else { return "—" } let formatter = DateFormatter() formatter.locale = Locale(identifier: "zh_CN") formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter.string(from: Date(timeIntervalSince1970: timestamp)) } /// 三列明确区分现金实收、现金退款和现金净收。 static func cashColumns(paid: Decimal?, refund: Decimal?, net: Decimal?, large: Bool) -> UIView { let values = [("现金实收", paid), ("现金退款", refund), ("现金净收", net)] let columns = values.map { title, amount in let value = DroneDockStyle.label(money(amount), size: large ? 20 : 17, weight: .semibold, color: title == "现金净收" ? DroneDockStyle.primary : DroneDockStyle.text) value.adjustsFontSizeToFitWidth = true value.minimumScaleFactor = 0.6 let column = UIStackView(arrangedSubviews: [DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary), value]) column.axis = .vertical column.spacing = 8 return column } let row = UIStackView(arrangedSubviews: columns) row.distribution = .fillEqually row.spacing = 8 return row } /// 积分及其抵扣金额独立成行,绝不加到现金实收或净收中。 static func pointsView(paid: Int, refund: Int, net: Int, amount: Decimal) -> UIView { let label = DroneDockStyle.label("积分实收 \(paid) · 积分退款 \(refund) · 积分净收 \(net)", size: 12, color: DroneDockStyle.secondary) label.numberOfLines = 0 let stack = UIStackView(arrangedSubviews: [label]) stack.axis = .vertical stack.spacing = 6 if amount != 0 { let amountLabel = DroneDockStyle.label("积分抵扣金额 \(money(amount))", size: 12, color: DroneDockStyle.secondary) amountLabel.numberOfLines = 0 stack.addArrangedSubview(amountLabel) } return stack } }