import 'package:chat/models/moment/moment_model.dart';
import 'package:chat/routes/moments_routes.dart';
import 'package:chat/providers/moment_provider.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:chat/views/moments/index/widgets/quick_reply_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

class MomentController extends GetxController {
  static MomentController get to => Get.find<MomentController>();

  final EasyRefreshController refreshController = EasyRefreshController();
  final ScrollController scrollController = ScrollController();

  // 连接通知器
  final LinkHeaderNotifier headerNotifier = LinkHeaderNotifier();

  final momentData = Rx<MomentModel?>(null);

  // 当前选中的moment id
  int currentMomentIndex = 0;

  static const defaultHitText = '回复';
  final replyBarHitTest = defaultHitText.obs;

  @override
  void onReady() {
    super.onReady();
    callRefresh();
  }

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

  void callRefresh() {
    refreshController.callRefresh();
  }

  Future<void> refreshList() async {
    final res = await MomentProvider.fetchMomentList();
    if (res != null) {
      momentData.value = res;
    }
    refreshController.resetLoadState();
  }

  Future<void> loadMoreList() async {
    if (momentData.value == null || momentData.value!.data!.isEmpty) {
      return;
    }
    final res = await MomentProvider.fetchMomentList(
      momentData.value?.data?.last.createdAt,
    );
    if (res != null) {
      final data = res.data ?? [];
      if (data.isEmpty || res.page?.hasMore == true) {
        refreshController.finishLoad(noMore: true);
      }
      momentData.value?.data?.addAll(data);
      momentData.refresh();
    }
  }

  void pushToDetail(int index) {
    currentMomentIndex = index;
    Get.toNamed(MomentsRoutes.detail, arguments: {'index': index});
  }

  // 点赞
  Future<void> likeMoment(MomentItemModel item) async {
    final result = await MomentProvider.likeMoment(item.dynamicId!);
    if (result != null) {
      if (item.isLike != result && result && item.likerCount != null) {
        item.likerCount = item.likerCount! + 1;
      } else {
        item.likerCount = item.likerCount! - 1;
      }
      item.isLike = result;
      momentData.refresh();
    }
  }

  // 删除动态
  Future<void> delMoment(MomentItemModel item) async {
    final result = await MomentProvider.delMoment(item.dynamicId!);
    if (result == true) {
      final moment = momentData.value?.data?.indexWhere(
        (e) => e.dynamicId == item.dynamicId,
      );
      momentData.value?.data!.removeAt(moment!);
      momentData.refresh();
      Get.back();
    }
  }

  // 删除评论
  Future<void> delReply(
    int index,
    int dynamicId, [
    Comment? comment,
  ]) async {
    final result = await MomentProvider.delComment(
      dynamicId,
      comment?.id,
    );
    if (result == true) {
      final moment = momentData.value?.data?.firstWhere(
        (e) => e.dynamicId == dynamicId,
        orElse: () => MomentItemModel(),
      );
      if (moment?.dynamicId == null) return;
      moment?.comments?.removeAt(index);
      momentData.refresh();
      UiTools.toast('删除成功');
    }
  }

  // 发送回复
  Future<void> sendReply(
    int dynamicId,
    String content, [
    Comment? comment,
  ]) async {
    final result = await MomentProvider.replyComment(
      dynamicId,
      content,
      comment?.id,
    );
    if (result != null) {
      final moment = momentData.value?.data?.firstWhere(
        (e) => e.dynamicId == dynamicId,
        orElse: () => MomentItemModel(),
      );
      if (moment?.dynamicId == null) return;
      moment?.comments?.add(result);
      momentData.refresh();
      Get.back();
      // UiTools.toast('回复成功');
    }
  }

  // 弹出QuickReplyBar
  Future<void> showReplyBar(int dynamicId, [Comment? comment]) async {
    Get.bottomSheet(
      QuickReplyBar(dynamicId: dynamicId, comment: comment),
    );
  }
}
