Files
kitchen/lib/src/controllers/feed/hot_controller.dart
2026-04-15 07:11:28 +08:00

121 lines
3.3 KiB
Dart
Raw 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.
// 2026-04-10 | HotController | 热门排行控制器 | 完全重写使用HotItem模型
// 2026-04-13 | 新增rate评分排序选项
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:mom_kitchen/src/controllers/base_controller.dart';
import 'package:mom_kitchen/src/repositories/hot_repository.dart' as repo;
import 'package:mom_kitchen/src/services/ui/toast_service.dart';
enum HotPeriod { today, month, total }
class HotController extends BaseController {
final repo.HotRepository _hotRepository = repo.HotRepository();
final Rx<HotPeriod> currentPeriod = Rx<HotPeriod>(HotPeriod.total);
final Rx<String> currentSortBy = 'view'.obs;
final RxList<repo.HotItem> hotList = RxList<repo.HotItem>([]);
@override
void onInit() {
super.onInit();
Future.delayed(Duration.zero, () => loadHot());
}
void switchPeriod(HotPeriod period) {
if (currentPeriod.value == period) return;
currentPeriod.value = period;
loadHot();
}
void switchSortBy(String sortBy) {
if (currentSortBy.value == sortBy) return;
currentSortBy.value = sortBy;
loadHot();
}
Future<void> loadHot() async {
await runWithLoading(() async {
try {
final result = await _hotRepository.fetchMergedHotList(
period: _periodToString(currentPeriod.value),
sortBy: currentSortBy.value,
limit: 20,
);
hotList.value = result;
if (result.isEmpty) {
ToastService.show(message: '暂无$periodName排行数据 📊');
} else {
ToastService.show(message: '已加载${result.length}$periodName排行 🎉');
}
} catch (e) {
debugPrint('HotController.loadHot error: $e');
errorMessage.value = e.toString();
String userMessage;
if (e.toString().contains('SocketException')) {
userMessage = '网络连接失败,请检查网络 🔌';
} else if (e.toString().contains('TimeoutException')) {
userMessage = '请求超时,请稍后重试 ⏰';
} else {
userMessage = '获取排行数据失败: $e';
}
ToastService.show(message: userMessage);
}
});
}
String _periodToString(HotPeriod period) {
switch (period) {
case HotPeriod.today:
return 'today';
case HotPeriod.month:
return 'month';
case HotPeriod.total:
return 'total';
}
}
String get periodName {
switch (currentPeriod.value) {
case HotPeriod.today:
return '今日';
case HotPeriod.month:
return '本月';
case HotPeriod.total:
return '累计';
}
}
String get sortByName {
switch (currentSortBy.value) {
case 'view':
return '浏览量';
case 'like':
return '点赞数';
case 'rate':
return '评分';
default:
return '浏览量';
}
}
static List<String> get periodNames => ['今日', '本月', '累计'];
static List<String> get sortByNames => ['浏览量', '点赞数', '评分'];
static String getSortByValue(String name) {
switch (name) {
case '浏览量':
return 'view';
case '点赞数':
return 'like';
case '评分':
return 'rate';
default:
return 'view';
}
}
}