import 'package:get/get.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
import 'package:tencent_im_sdk_plugin/enum/conversation_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'conversation_service.dart';

class LoadMessageResult {
  String? lastMsgId;
  bool noMore;

  LoadMessageResult({
    this.lastMsgId,
    required this.noMore,
  });
}

class TimMessageService extends GetxService {
  static TimMessageService get to => Get.find<TimMessageService>();

  RxList<V2TimMessage> messages = List<V2TimMessage>.empty(growable: true).obs;

  var curConversationId = '';

  Future<String?> loadMessagesFromService(
    V2TimConversation conversation,
    String? lastMsgId,
    AutoScrollController _scrollController,
  ) async {
    if (lastMsgId == null && curConversationId != conversation.conversationID) {
      messages.clear();
      curConversationId = conversation.conversationID;
    }

    V2TimValueCallback<List<V2TimMessage>> result;
    if (conversation.type == ConversationType.V2TIM_GROUP) {
      result = await TimConversationService.to.messageManager
          .getGroupHistoryMessageList(
        groupID: conversation.groupID!,
        count: 20,
        lastMsgID: lastMsgId,
      );
    } else {
      result = await TimConversationService.to.messageManager
          .getC2CHistoryMessageList(
        userID: conversation.userID!,
        count: 20,
        lastMsgID: lastMsgId,
      );
    }
    var list = result.data ?? [];
    if (lastMsgId == null) {
      messages.value = list.reversed.toList();
      _scrollController.scrollToIndex(
        messages.length - 1,
        preferPosition: AutoScrollPosition.begin,
      );
    } else {
      //加载更多
      if (list.isNotEmpty) {
        messages.value = messages.reversed.toList(); //正常顺序
        messages.addAll(list);
        messages.value = messages.reversed.toList(); //反转一次
      }
    }
    if (messages.isNotEmpty) {
      return messages.first.msgID;
    } else {
      return '';
    }
  }

  addMessage(V2TimMessage message) {
    messages.add(message);
  }
}
