import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:loopin/IM/controller/chat_controller.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/im_message.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/models/conversation_view_model.dart';
import 'package:loopin/pages/groupChat/controller/group_detail_controller.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimGroupListener.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_group_change_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_group_member_change_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_group_member_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_topic_info.dart';
import 'package:tencent_cloud_chat_sdk/native_im/adapter/tim_manager.dart';

final logger = Logger();

class ImGroupListeners {
  ImGroupListeners();

  late final V2TimGroupListener _listener;

  void register() {
    _listener = V2TimGroupListener(
      onGroupCreated: (String groupID) {
        logger.i('群被创建: $groupID');
        onGroupCreated(groupID);
      },
      onGroupDismissed: (String groupID, V2TimGroupMemberInfo opUser) {
        logger.i('群组被解散: $groupID, 操作人: ${opUser.nickName}');
        onGroupDismissed(groupID, opUser);
      },
      onGroupRecycled: (String groupID, V2TimGroupMemberInfo opUser) {
        logger.i('群组被回收: $groupID, 操作人: ${opUser.nickName}');
      },
      onGroupInfoChanged: (String groupID, List<V2TimGroupChangeInfo?> changeInfos) {
        logger.i('群信息变更: $groupID, $changeInfos');
        onGroupInfoChanged(groupID, changeInfos);
      },
      onMemberEnter: (String groupID, List<V2TimGroupMemberInfo> memberList) {
        logger.i('成员加入群 $groupID: ${memberList.map((e) => e.userID).join(', ')}');
        onMemberEnter(groupID, memberList);
      },
      onMemberLeave: (String groupID, V2TimGroupMemberInfo member) {
        logger.i('成员离开群 $groupID: ${member.userID}');
        onMemberLeave(groupID, member);
      },
      onMemberInvited: (String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {
        logger.i('成员被邀请 $groupID, inviter: ${opUser.userID}, members: ${memberList.map((e) => e.userID).join(', ')}');
        onMemberInvited(groupID, memberList);
      },
      onMemberKicked: (String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {
        logger.i('成员被踢 $groupID, opUser: ${opUser.userID}, members: ${memberList.map((e) => e.userID).join(', ')}');
        onMemberKicked(groupID, memberList);
      },
      onMemberInfoChanged: (String groupID, List<V2TimGroupMemberChangeInfo> v2TIMGroupMemberChangeInfoList) {
        logger.i('成员信息变更: $groupID, $v2TIMGroupMemberChangeInfoList');
        onMemberInfoChanged(groupID, v2TIMGroupMemberChangeInfoList);
      },
      onQuitFromGroup: (String groupID) {
        logger.i('主动退出群 $groupID');
        onQuitFromGroup(groupID);
      },
      onReceiveJoinApplication: (String groupID, V2TimGroupMemberInfo member, String opReason) {
        logger.i('收到入群申请 $groupID, member: ${member.userID}, reason: $opReason');
        onReceiveJoinApplication(groupID, member, opReason);
      },
      onApplicationProcessed: (String groupID, V2TimGroupMemberInfo opUser, bool isAgreeJoin, String opReason) {
        logger.i('入群申请已处理 $groupID, opUser: ${opUser.userID}, isAgree: $isAgreeJoin, reason: $opReason');
        onApplicationProcessed(groupID, opUser, isAgreeJoin, opUser);
      },
      onGrantAdministrator: (String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {
        logger.i('被授予管理员 $groupID, opUser: ${opUser.userID}, members: ${memberList.map((e) => e.userID).join(', ')}');
        onGrantAdministrator(groupID, opUser, memberList);
      },
      onRevokeAdministrator: (String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {
        logger.i('管理员权限被撤销 $groupID, opUser: ${opUser.userID}, members: ${memberList.map((e) => e.userID).join(', ')}');
        onRevokeAdministrator(groupID, opUser, memberList);
      },
      onReceiveRESTCustomData: (String groupID, String customData) {
        logger.i('收到自定义数据 $groupID: $customData');
        onReceiveRESTCustomData(groupID, customData);
      },
      onGroupAttributeChanged: (String groupID, Map<String, String> groupAttributeMap) {
        logger.i('群属性变更 $groupID: $groupAttributeMap');
      },
      onAllGroupMembersMuted: (String groupID, bool isMute) {
        logger.i('全体禁言状态变更 $groupID: $isMute');
      },
      onMemberMarkChanged: (String groupID, List<String> memberIDList, int markType, bool enableMark) {
        logger.i('成员标记变更 $groupID, members: ${memberIDList.join(', ')}, type: $markType, enable: $enableMark');
      },
      onGroupCounterChanged: (String groupID, String key, int newValue) {
        logger.i('群计数器变更 $groupID, key: $key, value: $newValue');
      },
      onTopicCreated: (String groupID, String topicID) {
        logger.i('话题创建 $groupID, topic: $topicID');
      },
      onTopicDeleted: (String groupID, List<String> topicIDList) {
        logger.i('话题删除 $groupID, topics: ${topicIDList.join(', ')}');
      },
      onTopicInfoChanged: (String groupID, V2TimTopicInfo topicInfo) {
        logger.i('话题信息变更 $groupID, topic: ${topicInfo.topicID}');
      },
    );

    TIMManager.instance.addGroupListener(listener: _listener);

    logger.i("群组监听器已注册");
  }

  void unregister() {
    TIMManager.instance.removeGroupListener(listener: _listener);
    logger.i("群组监听器已移除");
  }

  // 新群被创建
  void onGroupCreated(String groupID) {}

  //解散群
  void onGroupDismissed(String groupID, V2TimGroupMemberInfo opUser) {}

  // 群信息变更
  void onGroupInfoChanged(String groupID, List<V2TimGroupChangeInfo?> changeInfos) {}

  // 成员加入群
  void onMemberEnter(String groupID, List<V2TimGroupMemberInfo> memberList) {}

  // 成员离开群
  void onMemberLeave(String groupID, V2TimGroupMemberInfo member) {
    if (Get.isRegistered<GroupDetailController>()) {
      final ctl = Get.find<GroupDetailController>();
      ctl.init();
    }
  }

  // 成员被邀请入群
  void onMemberInvited(String groupID, List<V2TimGroupMemberInfo> memberList) async {
    if (Get.isRegistered<GroupDetailController>()) {
      final ctl = Get.find<GroupDetailController>();
      ctl.init();
    }
    //在群标记，目的为了清除被踢后的标记
    await ImService.instance.setConversationCustomData(customData: 'int', conversationIDList: ['group_$groupID']);
  }

  // 成员被踢出群
  void onMemberKicked(String groupID, List<V2TimGroupMemberInfo> memberList) async {
    if (Get.isRegistered<GroupDetailController>()) {
      final ctl = Get.find<GroupDetailController>();
      ctl.init();
    }
    // 这里处理会话
    final infoCtl = Get.find<ImUserInfoController>();
    final hasSelf = memberList.any((m) => m.userID == infoCtl.userID.value);
    logger.e(hasSelf);
    if (hasSelf) {
      // 给群打上标记
      await ImService.instance.setConversationCustomData(customData: 'out', conversationIDList: ['group_$groupID']);

      // 被踢的人中包含自己，先在本地找会话，没有在去云端找
      final chatCtl = Get.find<ChatController>();
      ConversationViewModel? conv;
      try {
        conv = chatCtl.chatList.firstWhere((m) => m.conversation.groupID == groupID);
      } catch (e) {
        conv = null;
      }
      if (conv != null) {
        logger.e('本地找到');
        // 本地有 9=群tips
        final result = await IMMessage().createTextMessage(text: '你已被移出群聊');
        if (result.success && result.data != null) {
          V2TimMessage msg = result.data!.messageInfo!;
          msg.cloudCustomData = 'tips';
          final index = chatCtl.chatList.indexOf(conv);
          if (index != -1) {
            chatCtl.chatList[index].conversation.lastMessage = msg;
            chatCtl.chatList.refresh();
            logger.e('刷新');
          }
        }
      } else {
        // 本地没拉到，去云端获取，
        final cloudRes = await ImService.instance.getConversation(conversationID: 'group_$groupID');
        if (cloudRes.success && cloudRes.data != null) {
          V2TimConversation cloudConv = cloudRes.data;
          final result = await IMMessage().createTextMessage(text: '你已被移出群聊');
          if (result.success && result.data != null) {
            V2TimMessage msg = result.data!.messageInfo!;
            msg.cloudCustomData = 'tips';
            cloudConv.lastMessage = msg;
            final resModel = await ConversationViewModel.createConversationViewModel(convList: [cloudConv]);
            chatCtl.chatList.insertAll(0, resModel);
          }
        }
      }
    }
  }

  // 成员信息变更
  void onMemberInfoChanged(String groupID, List<V2TimGroupMemberChangeInfo> v2timGroupMemberChangeInfoList) {}

  // 主动退出群
  void onQuitFromGroup(String groupID) {}

  // 入群申请
  void onReceiveJoinApplication(String groupID, V2TimGroupMemberInfo member, String opReason) {}

  // 处理入群申请处理结果
  void onApplicationProcessed(String groupID, V2TimGroupMemberInfo opUser, bool isAgreeJoin, V2TimGroupMemberInfo opUser2) {}

  // 册封管理员
  void onGrantAdministrator(String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {}

  // 移除管理员权限
  void onRevokeAdministrator(String groupID, V2TimGroupMemberInfo opUser, List<V2TimGroupMemberInfo> memberList) {}

  // 收到自定义消息
  void onReceiveRESTCustomData(String groupID, String customData) {}
}
