import 'package:loopin/IM/im_service.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';

class ConversationViewModel {
  late V2TimConversation conversation;
  String? faceUrl;
  String? isCustomAdmin;

  ConversationViewModel({
    required this.conversation,
    this.faceUrl,
    this.isCustomAdmin = '0', // 默认不是管理员
  });

  static Future<List<ConversationViewModel>> createConversationViewModel({required List<V2TimConversation> convList}) async {
    final userIDList = <String>[];
    final groupIDList = <String>[];

    // 提前收集所有需要批量查询的 userID 和 groupID
    for (var conv in convList) {
      if (conv.userID != null) {
        userIDList.add(conv.userID!);
      } else if (conv.groupID != null) {
        groupIDList.add(conv.groupID!);
      }
    }
    logger.e('用户ID：$userIDList');

    Map<String, String?> userFaceUrlMap = {};
    Map<String, String?> groupFaceUrlMap = {};
    Map<String, String> isCustomAdmin = {};
    if (userIDList.isNotEmpty) {
      final userRes = await TencentImSDKPlugin.v2TIMManager.getUsersInfo(userIDList: userIDList);

      if (userRes.code == 0) {
        for (var user in userRes.data!) {
          final userId = user.userID ?? '';
          userFaceUrlMap[userId] = user.faceUrl;

          // 读取管理员标识
          final customInfo = user.customInfo;
          logger.w('自定义信息：${user.toJson()}');
          if (customInfo != null) {
            isCustomAdmin[userId] = customInfo['admin'] ?? '0';
          }
        }
      }
    }

    if (groupIDList.isNotEmpty) {
      final groupRes = await TencentImSDKPlugin.v2TIMManager.getGroupManager().getGroupsInfo(groupIDList: groupIDList);
      if (groupRes.code == 0) {
        for (var groupResult in groupRes.data!) {
          final info = groupResult.groupInfo;
          if (info != null) {
            groupFaceUrlMap[info.groupID] = info.faceUrl;
          }
        }
      }
    }

    final viewList = convList.map((conv) {
      String? faceUrl = conv.faceUrl;

      if (faceUrl == null || faceUrl.isEmpty) {
        if (conv.userID != null) {
          faceUrl = userFaceUrlMap[conv.userID!];
        } else if (conv.groupID != null) {
          faceUrl = groupFaceUrlMap[conv.groupID!];
        }
      }

      return ConversationViewModel(
        conversation: conv,
        faceUrl: faceUrl,
        isCustomAdmin: isCustomAdmin[conv.userID],
      );
    }).toList();

    return viewList;
  }
}
