import 'package:chat/services/tim/conversation_service.dart';
import 'package:chat/services/tim_service.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/enum/group_add_opt_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/group_application_type_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/group_member_filter_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/group_member_role_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/group_type.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_group_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_application.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_full_info.dart';

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

  /// 群管理实例
  V2TIMGroupManager get groupManager =>
      TimService.to.instance.v2TIMGroupManager;

  /// 我的群组列表
  RxList<V2TimGroupInfo> groups =
      List<V2TimGroupInfo>.empty(growable: true).obs;

  @override
  void onInit() async {
    super.onInit();
    await fetchList();
  }

  Future<void> fetchList() async {
    var result = await groupManager.getJoinedGroupList();

    if (result.code == 0) {
      groups.value = result.data!;
    }
  }

  /// 创建群
  Future<String?> create(
    String groupName,
    List<V2TimFriendInfo> memberList, {
    String? groupType,
  }) async {
    var result = await groupManager.createGroup(
      groupType: groupType ?? GroupType.Public,
      groupName: groupName,
      notification: '',
      introduction: '',
      faceUrl: '',
      isAllMuted: false,
      isSupportTopic: false,
      addOpt: GroupAddOptTypeEnum.V2TIM_GROUP_ADD_AUTH,
      memberList: memberList.map((e) {
        return V2TimGroupMember(
          role: GroupMemberRoleTypeEnum.V2TIM_GROUP_MEMBER_ROLE_MEMBER,
          userID: e.userID,
        );
      }).toList(),
    );

    if (result.code != 0) {
      UiTools.toast(result.desc);
    }

    await fetchList();
    await TimConversationService.to.fetchList();

    return result.data;
  }

  /// 加群申请列表
  Future<List<V2TimGroupApplication?>?> applies(String groupID) async {
    var result = await groupManager.getGroupApplicationList();

    if (result.code == 0) {
      return result.data?.groupApplicationList;
    } else {
      UiTools.toast(result.desc);
      return null;
    }
  }

  /// 同意加群
  Future<void> accept() async {
    await groupManager.acceptGroupApplication(
      fromUser: '',
      groupID: '',
      toUser: '',
    );
  }

  /// 拒绝加群请求
  Future<void> refuse() async {
    await groupManager.refuseGroupApplication(
      addTime: 0,
      fromUser: '',
      groupID: '',
      toUser: '',
      type: GroupApplicationTypeEnum.V2TIM_GROUP_APPLICATION_GET_TYPE_JOIN,
    );
  }

  /// 加入群组
  Future<bool> join(
    V2TimGroupInfo group,
    String message,
  ) async {
    var result = await TimService.to.instance.joinGroup(
      groupID: group.groupID,
      groupType: group.groupType,
      message: message,
    );

    if (result.code == 0) {
      await fetchList();
      return true;
    } else {
      UiTools.toast(result.desc);
      return false;
    }
  }

  /// 邀请加群
  Future<bool> invite(
    V2TimGroupInfo group,
    List<String> userList,
  ) async {
    var result = await groupManager.inviteUserToGroup(
      groupID: group.groupID,
      userList: userList,
    );

    if (result.code == 0) {
      return true;
    } else {
      UiTools.toast(result.desc);
      return false;
    }
  }

  /// 退出群组
  Future<void> quit(
    V2TimGroupInfo group,
  ) async {
    await TimService.to.instance.quitGroup(
      groupID: group.groupID,
    );
    await fetchList();
    await TimConversationService.to.deleteById(
      'group_' + group.groupID,
    );
  }

  /// 解散群组
  Future<bool> dismiss(
    V2TimGroupInfo group,
    V2TimConversation conversation,
  ) async {
    var result = await TimService.to.instance.dismissGroup(
      groupID: group.groupID,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 获取群资料
  Future<V2TimGroupInfo?> info(String groupId) async {
    var result = await groupManager.getGroupsInfo(groupIDList: [groupId]);

    if (result.code == 0) {
      return result.data![0].groupInfo!;
    } else {
      UiTools.toast(result.desc);
    }
    return null;
  }

  /// 更新群资料
  Future<bool> updateName(
    V2TimGroupInfo group,
    String groupName,
  ) async {
    var result = await groupManager.setGroupInfo(
      info: V2TimGroupInfo.fromJson(
        {
          'groupID': group.groupID,
          'groupType': group.groupType,
          'groupName': groupName,
        },
      ),
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 更新群公告
  Future<bool> updateNotification(
    V2TimGroupInfo group,
    String notification,
  ) async {
    var result = await groupManager.setGroupInfo(
      info: V2TimGroupInfo.fromJson(
        {
          'groupID': group.groupID,
          'groupType': group.groupType,
          'notification': notification,
        },
      ),
    );

    if (result.code == 0) {
      await TimConversationService.to.fetchList();
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 修改加群方式
  Future<bool> updateAddOpt(
    V2TimGroupInfo group,
    String notification,
  ) async {
    var result = await groupManager.setGroupInfo(
      info: V2TimGroupInfo.fromJson(
        {
          'groupID': group.groupID,
          'groupType': group.groupType,
          'groupAddOpt': group.groupAddOpt,
        },
      ),
    );

    if (result.code == 0) {
      await TimConversationService.to.fetchList();
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 获取群组成员
  Future<List<V2TimGroupMemberFullInfo?>?> members(
    String groupID, {
    int count = 10,
    GroupMemberFilterTypeEnum filter =
        GroupMemberFilterTypeEnum.V2TIM_GROUP_MEMBER_FILTER_ALL,
  }) async {
    var result = await groupManager.getGroupMemberList(
      count: count,
      filter: filter,
      nextSeq: '0',
      offset: 0,
      groupID: groupID,
    );

    if (result.code == 0) {
      return result.data!.memberInfoList!;
    }
    return null;
  }

  /// 获取群成员资料
  Future<V2TimGroupMemberFullInfo?> getMemberInfo(
    V2TimGroupInfo group,
    String userID,
  ) async {
    var result = await groupManager.getGroupMembersInfo(
      groupID: group.groupID,
      memberList: [userID],
    );

    if (result.data != null) {
      return result.data!.first;
    } else {
      return null;
    }
  }

  /// 设置群成员资料
  Future<bool> setMemberInfo(
    V2TimGroupInfo group,
    String userID,
    String nameCard,
  ) async {
    var result = await groupManager.setGroupMemberInfo(
      groupID: group.groupID,
      userID: userID,
      nameCard: nameCard,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 禁言群成员, 时间单位秒，如果是0，应该就解除禁言了
  Future<bool> muteMember(
    V2TimGroupInfo group,
    String userID, {
    int seconds = 60,
  }) async {
    var result = await groupManager.muteGroupMember(
      groupID: group.groupID,
      userID: userID,
      seconds: seconds,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 全员禁言/解除全员禁言
  Future<bool> mute(
    V2TimGroupInfo group,
    bool isAllMuted,
  ) async {
    var result = await groupManager.setGroupInfo(
      info: V2TimGroupInfo(
        isAllMuted: isAllMuted,
        groupID: group.groupID,
        groupType: group.groupType,
      ),
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 踢人
  Future<bool> kickMember(
    V2TimGroupInfo group,
    List<String> memberList,
  ) async {
    var result = await groupManager.kickGroupMember(
      groupID: group.groupID,
      memberList: memberList,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 设置管理员
  Future<bool> setMemberRole(
    V2TimGroupInfo group,
    String userID,
    GroupMemberRoleTypeEnum role,
  ) async {
    var result = await groupManager.setGroupMemberRole(
      groupID: group.groupID,
      userID: userID,
      role: role,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }

  /// 转让群主
  Future<bool> transfer(
    V2TimGroupInfo group,
    String userID,
  ) async {
    var result = await groupManager.transferGroupOwner(
      groupID: group.groupID,
      userID: userID,
    );

    if (result.code == 0) {
      return true;
    }
    UiTools.toast(result.desc);
    return false;
  }
}
