Files
suixinkan_uikit/suixinkan/UI/Training/TrainingCenterViewController.swift
lujiuyin 27be1f30ed feat(training): 新增已结束筛选并精简课程展示
新增已结束任务筛选与只读回顾资格,保留搜索和游标分页。移除任务小节数量及课程附件文件名、切换入口,并更新接口和界面回归测试。
2026-10-20 14:04:25 +08:00

385 lines
19 KiB
Swift

import SnapKit
import UIKit
/// 培训首页、完整任务列表和考试记录共用一个页面,与小程序入口保持一致。
@MainActor
final class TrainingCenterViewController: TrainingBaseViewController {
/// 差异化列表中的任务与考试记录标识。
private enum Item: Hashable { case task(String), attempt(String) }
private var reloadTask: Task<Void, Never>?
private var reloadLoadingToken: UUID?
private var moreTask: Task<Void, Never>?
private var moreLoadingToken: UUID?
private var searchTask: Task<Void, Never>?
private let service: any TrainingDataServing
private let viewModel = TrainingRemoteCenterViewModel()
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 TrainingDataServing)? = nil, showsHistory: Bool = false) {
self.service = service ?? TrainingRemoteServiceFactory.production()
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: "培训中心")
}
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.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)
let heroContainer = UIStackView(arrangedSubviews: [hero])
heroContainer.axis = .vertical
heroContainer.isLayoutMarginsRelativeArrangement = true
heroContainer.layoutMargins = UIEdgeInsets(top: 12, left: 13, bottom: 12, right: 13)
header.addArrangedSubview(heroContainer)
let body = UIStackView()
body.axis = .vertical
body.spacing = 11
body.isLayoutMarginsRelativeArrangement = true
body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13)
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 (index, state) in TrainingLearnerStatus.allCases.enumerated() {
let button = TrainingUI.button(state.title, secondary: true)
var configuration = button.configuration
configuration?.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 6, bottom: 12, trailing: 6)
configuration?.titleAlignment = .center
configuration?.titleLineBreakMode = .byWordWrapping
button.configuration = configuration
button.tag = index
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() {
retryButton.accessibilityIdentifier = "training.center.retry"
moreButton.accessibilityIdentifier = "training.center.more"
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 attemptID):
guard let attempt = self.viewModel.records.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
cell.configure(attempt: attempt)
return cell
}
}
}
private func applyState(completion: (() -> Void)? = nil) {
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() {
let state = TrainingLearnerStatus.allCases[index]
let selected = state == viewModel.filter
var configuration = button.configuration
configuration?.title = switch state {
case .pendingExam: "待考试 \(viewModel.pendingCount)"
case .completed: "已完成 \(viewModel.completedCount)"
case .ended: state.title
}
configuration?.background.backgroundColor = selected ? TrainingUI.primary.withAlphaComponent(0.09) : .white
configuration?.baseForegroundColor = selected ? TrainingUI.primary : TrainingUI.muted
button.configuration = configuration
button.accessibilityTraits = selected ? [.button, .selected] : .button
}
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.map { .attempt($0.id) } : viewModel.tasks.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: true, completion: completion)
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.hasMore
moreButton.isEnabled = !viewModel.isLoadingMore
var moreConfiguration = moreButton.configuration
moreConfiguration?.title = viewModel.isLoadingMore ? "正在加载…" : "加载更多"
moreButton.configuration = moreConfiguration
if !viewModel.isLoading { refreshControl.endRefreshing() }
sizeTableSupplementaryViews()
}
/// 页面出现和下拉刷新都读取最新本人任务。
func reload() async {
await viewModel.load(service: service)
guard !Task.isCancelled else { return }
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
applyState { continuation.resume() }
}
}
/// 在同一页面切换入口,返回课程时保留筛选上下文。
func selectTab(_ tab: TrainingCenterTab) {
view.endEditing(true)
viewModel.selectTab(tab)
searchField.text = ""
reloadTapped()
tableView.setContentOffset(.zero, animated: false)
}
@objc private func reloadTapped() {
scheduleReload(showsLoading: true)
}
private func releaseReloadLoading() {
if let token = reloadLoadingToken { endRequestLoading(token) }
reloadLoadingToken = nil
}
private func releaseMoreLoading() {
if let token = moreLoadingToken { endRequestLoading(token) }
moreLoadingToken = nil
}
private func scheduleReload(showsLoading: Bool) {
if showsLoading {
searchTask?.cancel()
searchTask = nil
}
reloadTask?.cancel()
releaseReloadLoading()
moreTask?.cancel()
moreTask = nil
releaseMoreLoading()
let token = showsLoading ? beginRequestLoading() : nil
reloadLoadingToken = token
reloadTask = Task { @MainActor in
defer {
if let token { endRequestLoading(token) }
if reloadLoadingToken == token { reloadLoadingToken = nil }
}
await reload()
}
}
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
@objc private func filterTapped(_ button: UIButton) {
guard TrainingLearnerStatus.allCases.indices.contains(button.tag) else { return }
viewModel.filter = TrainingLearnerStatus.allCases[button.tag]
reloadTapped()
}
@objc private func searchChanged() {
viewModel.setKeyword(searchField.text ?? "")
reloadTask?.cancel()
releaseReloadLoading()
moreTask?.cancel()
moreTask = nil
releaseMoreLoading()
searchTask?.cancel()
moreButton.isHidden = true
searchTask = Task { @MainActor [weak self] in
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
self?.scheduleReload(showsLoading: false)
}
}
@objc private func moreTapped() {
guard moreTask == nil, viewModel.hasMore, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
let token = beginRequestLoading()
moreLoadingToken = token
moreTask = Task { @MainActor in
defer {
endRequestLoading(token)
if moreLoadingToken == token {
moreLoadingToken = nil
moreTask = nil
}
}
await viewModel.loadMore(service: service)
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
applyState()
}
}
@objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) }
private func openTask(_ task: TrainingTaskSummary, directAction: Bool) {
let controller: UIViewController = directAction && task.learnerStatus == .pendingExam && task.learning.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 attemptID): if let attempt = viewModel.records.first(where: { $0.id == attemptID }) { navigationController?.pushViewController(TrainingResultViewController(taskID: attempt.taskID, attemptID: attempt.id, service: service), animated: true) }
}
}
}