import 'package:get/get.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/models/conversation_type.dart' as myConversationType;
import 'package:loopin/models/conversation_view_model.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation_filter.dart';

class ChatController extends GetxController {
  RxInt count = 20.obs; // 每页条数
  RxString nextSeq = '0'.obs; // 页码
  RxBool isFinished = false.obs; // 是否拉取完？默认未拉取完

  final chatList = <ConversationViewModel>[].obs;

  void initChatData() {
    chatList.value = <ConversationViewModel>[];
    nextSeq.value = '0';
    isFinished.value = false;
  }

  // 获取所有会话列表
  void getConversationList() async {
    if (isFinished.value) {
      // 拉取完数据了，直接结束
      return;
    }
    final res = await ImService.instance.getConversationList(nextSeq.value, count.value);

    if (!res.success || res.data == null) return;

    final List<ConversationViewModel> convList = res.data;
    for (var conv in convList) {
      logger.i('基本会话: ${conv.conversation.toJson()}, 会话ID: ${conv.conversation.conversationID}');
    }

    chatList.addAll(convList);
    // 不包含noFriend才执行加载数据逻辑,分页加载时候过滤
    final hasNoFriend = chatList.any((item) => item.conversation.conversationGroupList?.contains(myConversationType.ConversationType.noFriend.name) ?? false);
    if (!hasNoFriend) {
      getNoFriendData();
    }
  }

  ///构建陌生人消息菜单入口
  void getNoFriendData({V2TimConversation? csion}) async {
    // 检测会话列表是否已有陌生人消息菜单
    final hasNoFriend = chatList.any((item) => item.conversation.conversationGroupList?.contains(myConversationType.ConversationType.noFriend.name) ?? false);
    if (hasNoFriend) {
      // 已经有了入口
      final ConversationViewModel matchItem = chatList.firstWhere(
        (item) => item.conversation.conversationGroupList?.contains(myConversationType.ConversationType.noFriend.name) ?? false,
      );
      // 获取陌生人未读总数
      final unreadTotal = await ImService.instance.getUnreadMessageCountByFilter(
        filter: V2TimConversationFilter(
          conversationGroup: myConversationType.ConversationType.noFriend.name,
          hasUnreadCount: true,
        ),
      );
      matchItem.conversation.lastMessage = csion!.lastMessage;
      matchItem.conversation.unreadCount = unreadTotal.data;
      chatList.refresh();
      return;
    }
    // 没有则执行创建逻辑
    final res = await ImService.instance.getConversationListByFilter(
      filter: V2TimConversationFilter(conversationGroup: myConversationType.ConversationType.noFriend.name),
      nextSeq: 0,
      count: 1,
    );
    if (res.success && res.data != null) {
      final convList = res.data!.conversationList ?? [];
      if (convList.isNotEmpty) {
        // logger.i(res.data!.toJson());
        // 有陌生人消息，1.获取未读数，2.组装converstaionviewmodel
        final unread = await ImService.instance.getUnreadMessageCountByFilter(
          filter: V2TimConversationFilter(
            conversationGroup: myConversationType.ConversationType.noFriend.name,
            hasUnreadCount: true,
          ),
        );
        if (unread.success) {
          final conv = convList.first;
          final faceUrl = 'assets/images/notify/msr.png';
          conv.showName = '陌生人消息';
          conv.unreadCount = unread.data;
          final createItem = ConversationViewModel(
            conversation: conv,
            faceUrl: faceUrl,
          );
          final newList = List<ConversationViewModel>.from(chatList);
          newList.add(createItem);
          newList.sort((a, b) {
            final atime = a.conversation.lastMessage?.timestamp ?? 0;
            final btime = b.conversation.lastMessage?.timestamp ?? 0;
            return btime.compareTo(atime); // 降序
          });
          chatList.value = newList;
        }
      }
    }
  }

  /// 按会话分组查询 getConversationListByFilter
  // void getConversationList() async {
  //   final res = await ImService.instance.getConversationListByFilter(
  //     filter: V2TimConversationFilter(conversationGroup: null),
  //     nextSeq: nextSeq.value,
  //   );
  //   final convList = res.data!.conversationList;
  //   logger.i(res.data!.toJson());
  //   chatList.value = convList;
  //   // for (var element in convList ?? []) {
  //   //   logger.i(element.toJson());
  //   //   // 你可以在这里继续处理 element
  //   // }
  // }
}
