import 'package:get/get.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../../../model/response/kr_message_list.dart';
import '../../../services/api_service/kr_api.user.dart';
import '../../../utils/kr_common_util.dart';



class KRMessageController extends GetxController {
  final KRUserApi kr_userApi = KRUserApi();
  // 通知列表数据
  final RxList<KRMessage> kr_messages = <KRMessage>[].obs;

  final RxBool kr_isLoading = false.obs;
  final RxBool kr_hasMore = true.obs;
  int kr_page = 1;
  final int kr_size = 10;
  final EasyRefreshController refreshController = EasyRefreshController();

  @override

  void onInit() {
    super.onInit();
    kr_getMessageList();
  }

  // 刷新列表
  Future<void> kr_onRefresh() async {
    kr_page = 1;
    kr_hasMore.value = true;
    kr_messages.clear();
    await kr_getMessageList();
    refreshController.finishRefresh();
  }

  // 加载更多
  Future<void> kr_onLoadMore() async {
    if (!kr_hasMore.value || kr_isLoading.value) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    kr_page++;
    await kr_getMessageList();
    refreshController.finishLoad(kr_hasMore.value ? IndicatorResult.success : IndicatorResult.noMore);
  }

  Future<void> kr_getMessageList() async {
    if (kr_isLoading.value) return;
    kr_isLoading.value = true;

    final either = await kr_userApi.kr_getMessageList(kr_page, kr_size);
    either.fold(
      (error) {
        KRCommonUtil.kr_showToast(error.msg);
        if (kr_page > 1) kr_page--;
      },
      (list) {
        if (list.announcements.isEmpty) {
          kr_hasMore.value = false;
        } else {
          // 对消息进行排序，确保 pinned 为 true 的消息排在前面
          final sortedMessages = List<KRMessage>.from(list.announcements)
            ..sort((a, b) {
              // 首先按 pinned 状态排序
              if (a.pinned != b.pinned) {
                return a.pinned ? -1 : 1; // pinned 为 true 的排在前面
              }
              // 如果 pinned 状态相同，则按创建时间降序排序
              return b.createdAt.compareTo(a.createdAt);
            });
          kr_messages.addAll(sortedMessages);
        }
      },
    );
    
    kr_isLoading.value = false;
  }

  @override
  void onClose() {
    refreshController.dispose();
    super.onClose();
  }
}
