Files
2026-09-28 20:12:34 +08:00

84 lines
2.7 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// ============================================================
/// 【课堂习题 · 收藏 / 错题本】(1:1 迁移 Vue exerciseCollect.js)
///
/// type=1 收藏;type=2 错题(仅 view 模式可用)。
/// ============================================================
library;
import 'package:new_learn/core/api/conquerPackage/classExercises/api.dart';
import 'package:new_learn/features/conquerPackage/classExercises/controllers/exercise_session.dart';
import 'package:new_learn/features/conquerPackage/classExercises/models/question_model.dart';
class ExerciseCollectHandlers {
ExerciseCollectHandlers({
required this.session,
required this.bridge,
});
final ExerciseSession session;
final ExerciseUiBridge bridge;
final ClassExercisesApi _api = ClassExercisesApi.instance;
dynamic _field(dynamic resp, String key) {
if (resp is Map) {
if (resp[key] != null) return resp[key];
final data = resp['data'];
if (data is Map && data[key] != null) return data[key];
}
return null;
}
/// type:1=收藏,2=错题本
Future<void> onClickAddUserCollect(int type) async {
// 错题仅查看模式可用
if (type == 2 && !session.isView) return;
final info = session.currentQuestion;
if (info == null) return;
final selected = type == 1 ? info.isCollect : info.isWrongCollect;
try {
if (selected) {
final id = type == 1 ? info.collectId : info.wrongCollectId;
await _api.cancleCollect(<String, dynamic>{
'type': type,
'id': id ?? 0,
});
_syncCollectState(type, true, null, info);
bridge.toast(type == 1 ? '取消收藏成功' : '取消错题成功');
} else {
final packId =
session.totalPackId.isNotEmpty ? session.totalPackId : session.packId;
final res = await _api.addUserCollect(<String, dynamic>{
'type': type,
'packId': packId,
'questionId': info.questionId,
'recordQuestionId': info.id,
});
final resId = _field(res, 'id');
_syncCollectState(type, false, resId, info);
bridge.toast(type == 1 ? '收藏成功' : '错题添加成功');
}
bridge.notifyListeners();
} catch (_) {
bridge.toast(type == 1 ? '收藏失败' : '失败');
}
}
/// 同步收藏态(对标 syncCollectState)
void _syncCollectState(
int type,
bool wasSelected,
dynamic resId,
QuestionModel info,
) {
if (type == 2) {
info.isWrongCollect = !wasSelected;
info.wrongCollectId = wasSelected ? 0 : resId;
} else {
info.isCollect = !wasSelected;
info.collectId = wasSelected ? 0 : resId;
}
}
}