Files
suixinkan_uikit/suixinkan/UI/Training/TrainingCenterViewController.swift
han xin 74c451c5e5 feat(training): 新增培训中心学习答题演示及成绩回顾
新增首页和个人页培训入口,支持课程阅读、答题卡、未交卷答案恢复、成绩记录及重考。
对齐小程序的培训首页与成绩页,答案解析默认收起并提供返回对应课程的入口。

开发版使用隔离的本机演示数据,正式培训服务尚未接入。
2026-10-10 11:36:49 +08:00

299 lines
16 KiB
Swift

import SnapKit
import UIKit
/// 培训首页、完整任务列表和考试记录共用一个页面,与小程序入口保持一致。
@MainActor
final class TrainingCenterViewController: TrainingBaseViewController {
private enum Item: Hashable { case task(String), attempt(taskID: String, attemptID: String) }
private let service: any TrainingServing
private let viewModel = TrainingCenterViewModel()
private let tableView = UITableView(frame: .zero, style: .plain)
private let refreshControl = UIRefreshControl()
private let header = UIStackView()
private let hero = UIStackView()
private let greetingLabel = TrainingUI.text(size: 14, color: .white)
private let titleLabel = TrainingUI.text("我的培训中心", size: 18, weight: .bold, color: .white)
private var statLabels: [UILabel] = []
private let headingLabel = TrainingUI.text(size: 15.5, weight: .semibold)
private let viewAllButton = TrainingUI.button("查看全部", plain: true)
private let filters = UIStackView()
private var filterButtons: [UIButton] = []
private let searchField = UITextField()
private let tabBar = UIStackView()
private let tabBackground = UIView()
private var tabButtons: [UIButton] = []
private let footer = UIStackView()
private let stateLabel = TrainingUI.text(size: 14, color: TrainingUI.muted)
private let retryButton = TrainingUI.button("重新加载", secondary: true)
private let moreButton = TrainingUI.button("加载更多记录", plain: true)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
/// 默认连接正式服务,开发演示仅由用户显式打开。
init(service: any TrainingServing = TrainingServiceFactory.production(), showsHistory: Bool = false) {
self.service = service
viewModel.tab = showsHistory ? .records : .home
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
TrainingUI.navigation(self, title: "培训中心")
#if DEBUG
if !service.isDemo { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开发演示", style: .plain, target: self, action: #selector(demoTapped)) }
#endif
}
override func setupUI() {
view.backgroundColor = TrainingUI.background
header.axis = .vertical
header.spacing = 0
hero.axis = .vertical
hero.spacing = 8
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
hero.layer.cornerRadius = 14
hero.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
hero.isLayoutMarginsRelativeArrangement = true
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
hero.addArrangedSubview(greetingLabel)
hero.addArrangedSubview(titleLabel)
let stats = UIStackView()
stats.distribution = .fillEqually
stats.alignment = .fill
for caption in ["待考试", "已完成", "最近得分"] {
let value = TrainingUI.text("—", size: 23, weight: .bold, color: .white)
value.textAlignment = .center
statLabels.append(value)
let name = TrainingUI.text(caption, size: 12.5, color: .white)
name.textAlignment = .center
let column = UIStackView(arrangedSubviews: [value, name])
column.axis = .vertical
column.spacing = 6
stats.addArrangedSubview(column)
if statLabels.count > 1 {
let line = UIView()
line.backgroundColor = UIColor.white.withAlphaComponent(0.4)
column.addSubview(line)
line.snp.makeConstraints { $0.leading.top.bottom.equalToSuperview(); $0.width.equalTo(1) }
}
}
hero.setCustomSpacing(18, after: titleLabel)
hero.addArrangedSubview(stats)
header.addArrangedSubview(hero)
let body = UIStackView()
body.axis = .vertical
body.spacing = 11
body.isLayoutMarginsRelativeArrangement = true
body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13)
if service.isDemo { body.addArrangedSubview(TrainingUI.demoNotice()) }
let heading = UIStackView(arrangedSubviews: [headingLabel, viewAllButton])
heading.alignment = .center
heading.spacing = 8
headingLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
viewAllButton.setContentHuggingPriority(.required, for: .horizontal)
body.addArrangedSubview(heading)
filters.distribution = .fillEqually
filters.spacing = 9
for state in TrainingLearnerStatus.allCases {
let button = TrainingUI.button(state.title, secondary: true)
button.tag = state == .pendingExam ? 0 : 1
button.accessibilityIdentifier = "training.filter.\(button.tag)"
button.addTarget(self, action: #selector(filterTapped(_:)), for: .touchUpInside)
filterButtons.append(button)
filters.addArrangedSubview(button)
}
body.addArrangedSubview(filters)
searchField.font = .systemFont(ofSize: 13)
searchField.backgroundColor = .white
searchField.layer.cornerRadius = 8
searchField.placeholder = "搜索任务或课程名称"
searchField.clearButtonMode = .whileEditing
searchField.returnKeyType = .search
searchField.accessibilityIdentifier = "training.search"
searchField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1))
searchField.leftViewMode = .always
searchField.snp.makeConstraints { $0.height.equalTo(44) }
body.addArrangedSubview(searchField)
header.addArrangedSubview(body)
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 250
tableView.delegate = self
tableView.keyboardDismissMode = .onDrag
tableView.refreshControl = refreshControl
tableView.register(TrainingTaskCell.self, forCellReuseIdentifier: TrainingTaskCell.reuseIdentifier)
tableView.register(TrainingRecordCell.self, forCellReuseIdentifier: TrainingRecordCell.reuseIdentifier)
tableView.tableHeaderView = header
footer.axis = .vertical
footer.spacing = 12
footer.isLayoutMarginsRelativeArrangement = true
footer.layoutMargins = UIEdgeInsets(top: 24, left: 26, bottom: 24, right: 26)
stateLabel.textAlignment = .center
[stateLabel, retryButton, moreButton].forEach(footer.addArrangedSubview)
tableView.tableFooterView = footer
tabBackground.backgroundColor = .white
let line = UIView()
line.backgroundColor = TrainingUI.border
tabBackground.addSubview(line)
line.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(1) }
tabBar.distribution = .fillEqually
for tab in TrainingCenterTab.allCases {
let button = TrainingUI.button(tab.title, plain: true)
button.tag = tab.rawValue
button.accessibilityIdentifier = "training.tab.\(tab.rawValue)"
button.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
tabButtons.append(button)
tabBar.addArrangedSubview(button)
}
view.addSubview(tableView)
view.addSubview(tabBackground)
tabBackground.addSubview(tabBar)
configureDataSource()
applyState()
}
override func setupConstraints() {
tabBackground.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
tabBar.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(12)
$0.top.equalToSuperview().offset(7)
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-7)
}
tableView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(tabBackground.snp.top)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sizeTableSupplementaryViews()
}
private func sizeTableSupplementaryViews() {
let width = tableView.bounds.width
guard width > 0 else { return }
for stack in [header, footer] {
let height = stack.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height
if abs(stack.frame.height - height) > 0.5 || stack.frame.width != width {
stack.frame = CGRect(x: 0, y: 0, width: width, height: height)
if stack === header { tableView.tableHeaderView = header } else { tableView.tableFooterView = footer }
}
}
}
override func bindActions() {
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
searchField.addTarget(self, action: #selector(searchChanged), for: .editingChanged)
moreButton.addTarget(self, action: #selector(moreTapped), for: .touchUpInside)
}
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); reloadTapped() }
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func configureDataSource() {
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
switch item {
case .task(let id):
guard let task = self.viewModel.tasks.first(where: { $0.id == id }), let cell = table.dequeueReusableCell(withIdentifier: TrainingTaskCell.reuseIdentifier, for: indexPath) as? TrainingTaskCell else { return nil }
cell.configure(task: task)
cell.onAction = { [weak self] in self?.openTask(task, directAction: true) }
return cell
case .attempt(let taskID, let attemptID):
guard let task = self.viewModel.tasks.first(where: { $0.id == taskID }), let attempt = task.progress.attempts.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
cell.configure(task: task, attempt: attempt)
return cell
}
}
}
private func applyState() {
let session = AppStore.shared.session
let name = [session.realName, session.userName].first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? "当前学员"
greetingLabel.text = "你好,\(name)"
let context = session.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
titleLabel.text = context.isEmpty ? "我的培训中心" : "\(context) · 培训中心"
for (label, value) in zip(statLabels, [String(viewModel.pendingCount), String(viewModel.completedCount), viewModel.latestScore]) { label.text = value }
headingLabel.text = switch viewModel.tab { case .home: "新政策与必读内容"; case .tasks: "我的学习任务"; case .records: "考试记录" }
viewAllButton.isHidden = viewModel.tab != .home
filters.isHidden = viewModel.tab != .tasks
searchField.isHidden = viewModel.tab != .tasks
for (index, button) in filterButtons.enumerated() {
var configuration = button.configuration
configuration?.title = index == 0 ? "待考试 \(viewModel.pendingCount)" : "已完成 \(viewModel.completedCount)"
configuration?.background.backgroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary.withAlphaComponent(0.09) : .white
configuration?.baseForegroundColor = index == (viewModel.filter == .pendingExam ? 0 : 1) ? TrainingUI.primary : TrainingUI.muted
button.configuration = configuration
}
for (index, button) in tabButtons.enumerated() {
var configuration = button.configuration
configuration?.baseForegroundColor = index == viewModel.tab.rawValue ? TrainingUI.primary : TrainingUI.muted
button.configuration = configuration
button.accessibilityTraits = index == viewModel.tab.rawValue ? [.button, .selected] : .button
}
let items: [Item] = viewModel.tab == .records ? viewModel.records.prefix(viewModel.recordLimit).map { .attempt(taskID: $0.task.id, attemptID: $0.attempt.id) } : viewModel.visibleTasks.map { .task($0.id) }
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(items)
snapshot.reconfigureItems(items.filter { dataSource.snapshot().indexOfItem($0) != nil })
dataSource.apply(snapshot, animatingDifferences: false)
stateLabel.text = viewModel.errorMessage ?? (viewModel.isLoading ? "正在加载培训任务…" : viewModel.tab == .records ? "暂无考试记录\n交卷后可在此查看成绩和解析" : "暂无符合条件的任务\n景区分配给当前账号的任务会显示在这里")
stateLabel.isHidden = !items.isEmpty
retryButton.isHidden = viewModel.errorMessage == nil
retryButton.isEnabled = !viewModel.isLoading
moreButton.isHidden = viewModel.tab != .records || viewModel.records.count <= viewModel.recordLimit
if !viewModel.isLoading { refreshControl.endRefreshing() }
sizeTableSupplementaryViews()
}
/// 页面出现和下拉刷新都读取最新本人任务。
func reload() async { await viewModel.load(service: service); applyState() }
/// 在同一页面切换入口,返回课程时保留筛选上下文。
func selectTab(_ tab: TrainingCenterTab) {
view.endEditing(true)
viewModel.selectTab(tab)
searchField.text = ""
applyState()
tableView.setContentOffset(.zero, animated: false)
}
@objc private func reloadTapped() {
guard !viewModel.isLoading else { return }
Task { @MainActor in await reload() }
}
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; applyState() }
@objc private func searchChanged() { viewModel.keyword = searchField.text ?? ""; applyState() }
@objc private func moreTapped() { viewModel.recordLimit += 20; applyState() }
@objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) }
#if DEBUG
@objc private func demoTapped() {
do { navigationController?.pushViewController(TrainingCenterViewController(service: try TrainingServiceFactory.demo()), animated: true) }
catch { showToast(error.localizedDescription) }
}
#endif
private func openTask(_ task: TrainingTask, directAction: Bool) {
let controller: UIViewController = directAction && TrainingTaskPresentation(task: task).canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service)
navigationController?.pushViewController(controller, animated: true)
}
}
extension TrainingCenterViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .task(let id): if let task = viewModel.tasks.first(where: { $0.id == id }) { openTask(task, directAction: false) }
case .attempt(let taskID, let attemptID): navigationController?.pushViewController(TrainingResultViewController(taskID: taskID, attemptID: attemptID, service: service), animated: true)
}
}
}