import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'model.dart';

class MessageController extends GetxController {
  final RefreshController refreshController = RefreshController(initialRefresh: false);
  final RxList<MessageModel> messageList = <MessageModel>[].obs;
  int _pageNum = 1;
  final int _pageSize = 20;

  // 是否所有已读状态
  final RxBool allRead = false.obs;

  @override
  void onInit() {
    super.onInit();
    _loadData(isRefresh: true);
  }

  void onRefresh() => _loadData(isRefresh: true);

  void onLoading() => _loadData(isRefresh: false);

  Future<void> _loadData({bool isRefresh = false}) async {
    final int targetPage = isRefresh ? 1 : _pageNum + 1;

    try {
      final Map<String, dynamic> requestData = {
        'appFlag': 1,
        'pageNum': targetPage,
        'pageSize': _pageSize,
      };

      final response = await HttpService.to.get(
        'appointment/unread_notice/page',
        params: requestData,
      );

      if (response == null) {
        throw Exception("Response is null");
      }

      final result = BaseModel.fromJson(response.data);

      if (result.code != 0) {
        throw Exception(result.message ?? "Business error");
      }

      final recordsList = result.data?["records"] as List? ?? [];

      final List<MessageModel> newData = recordsList.map((e) {
        return MessageModel(
          id: e['id']?.toString() ?? '',
          title: e['noticeTitle'] ?? '',
          content: e['noticeContent'] ?? '',
          createTime: e['createTime'] ?? '',
          isRead: int.tryParse(e['isRead']?.toString() ?? '0') ?? 0,
        );
      }).toList();

      if (isRefresh) {
        messageList.assignAll(newData);
        _pageNum = 1; // 只有成功了才重置页码
      } else {
        messageList.addAll(newData);
        if (newData.isNotEmpty) {
          _pageNum++; // 只有成功且有数据才+1
        }
      }

      _updateRefreshState(isRefresh, newData.length);

      // 检查是否全部已读
      _checkAllRead();
    } catch (e) {
      Logger.d("加载失败: $e"); // 建议加上日志
      if (isRefresh) {
        refreshController.refreshFailed();
      } else {
        refreshController.loadFailed();
      }
    }
  }

  /// 处理 RefreshController 状态
  void _updateRefreshState(bool isRefresh, int count) {
    if (isRefresh) {
      refreshController.refreshCompleted();
      // 如果刷新后的数据量小于 pageSize，说明没有更多数据了
      if (count < _pageSize) {
        refreshController.loadNoData();
      } else {
        // 必须重置 footer 状态，否则之前如果是 NoData 状态无法再加载
        refreshController.resetNoData();
      }
    } else {
      if (count == 0) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }
  }



  // 标记全部已读
  void markAllRead() async {
    showLoading('正在标记...');
    try {
      final response = await HttpService.to.post('appointment/unread_notice/read/all');
      if (response != null) {
        final result = BaseModel.fromJson(response.data);
        if (result.code == 0) {
          for (var msg in messageList) {
            msg.isRead = 0;
          }
          messageList.refresh();
          allRead.value = true;

          dismissLoading();
          showSuccessToast('全部已读');
        }
      }
    } catch (e) {
      dismissLoading();
      showErrorToast('操作失败');
    }
  }

  // 标记单条已读（弹窗显示时调用）
  void markRead(MessageModel message) async {
    if (message.isRead == 0) return;

    final response = await HttpService.to.post(
      '/appointment/unread_notice/read/${message.id}',
    );
    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0) {
        message.isRead = 0;
        messageList.refresh();
        _checkAllRead();
      }
    }
  }

  void _checkAllRead() {
    allRead.value = messageList.every((msg) => msg.isRead == 0);
  }
}
