jsdw_ios/QuickLocation/Section/Mine/MoodStatus/MoodStatusVC.swift

113 lines
3.7 KiB
Swift

//
// MoodStatusVC.swift
// QuickLocation
//
import UIKit
import RxSwift
import RxCocoa
final class MoodStatusVC: BaseViewController {
private var rootView: MoodStatusView!
private let viewModel = MoodStatusViewModel()
private var statusRequestVersion = 0
private var moodSelectionVersion = 0
override func loadView() {
rootView = MoodStatusView(frame: UIScreen.main.bounds)
view = rootView
}
override func viewDidLoad() {
super.viewDidLoad()
bind()
rootView.configure(
items: viewModel.items,
selectedMoodIndex: viewModel.selectedMoodIndex.value
)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
requestUserStatus()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
statusRequestVersion += 1
}
private func bind() {
rootView.onBack = { [weak self] in
guard self?.viewModel.isSaving == false else { return }
self?.navigationController?.popViewController(animated: true)
}
rootView.onSelectMood = { [weak self] moodIndex in
self?.moodSelectionVersion += 1
self?.viewModel.select(moodIndex: moodIndex)
}
rootView.onSave = { [weak self] in
self?.save()
}
viewModel.selectedMoodIndex
.asDriver()
.drive(onNext: { [weak self] moodIndex in
self?.rootView.updateSelection(moodIndex: moodIndex)
})
.disposed(by: disposeBag)
}
private func requestUserStatus() {
statusRequestVersion += 1
let requestVersion = statusRequestVersion
let selectionVersion = moodSelectionVersion
UserService.userStatus()
.subscribe(onNext: { [weak self] response in
guard let self, requestVersion == self.statusRequestVersion else { return }
guard response.code == "0", let model = response.model else {
DLToast.showError(text: response.message ?? "获取用户状态失败")
return
}
AppContextManager.shared.updateAccountState(status: model.status, mood: model.mood)
if selectionVersion == self.moodSelectionVersion {
self.viewModel.applyServerMood(model.mood)
}
}, onError: { [weak self] error in
guard let self, requestVersion == self.statusRequestVersion else { return }
DLToast.showError(text: error.localizedDescription)
})
.disposed(by: disposeBag)
}
private func save() {
guard !viewModel.isSaving else { return }
switch viewModel.validateSave() {
case .missing:
DLToast.show(text: "请选择心情")
case let .ready(moodIndex):
statusRequestVersion += 1
viewModel.beginSaving()
rootView.setSaving(true)
DLToast.showLoading()
UserService.setMood(moodIndex: moodIndex)
.subscribe(onNext: { [weak self] _ in
self?.viewModel.endSaving()
AppContextManager.shared.updateAccountMood(moodIndex)
DLToast.show(text: "保存成功") {
AppRouter.shared.popOrDismiss()
NotificationCenter.default.post(name: .RefreshGroupInfoNotification, object: nil)
}
}, onError: { [weak self] _ in
self?.viewModel.endSaving()
self?.rootView.setSaving(false)
}).disposed(by: disposeBag)
}
}
}