import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:chat/models/im/group_conversation_model.dart';
import 'package:chat/services/auth_service.dart';
import 'package:chat/services/tim/conversation_service.dart';
import 'package:chat/services/tim/group_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_member_filter_enum.dart';
import 'package:tencent_im_sdk_plugin/enum/group_member_role.dart';
import 'package:tencent_im_sdk_plugin/enum/group_member_role_enum.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_group_member_full_info.dart';

class GroupController extends GetxController {
  static GroupController get to => Get.find<GroupController>();

  Rx<GroupConversationModel> currentGroup =
      GroupConversationModel(groupID: '').obs;

  @override
  void onClose() {
    currentGroup.value = GroupConversationModel(groupID: '');
    TimService.to.currentConversationId.value = '';
    super.onClose();
  }

  /// 设置当前操作的群组
  Future<void> setCurrentGroup(String groupId) async {
    var group = await TimGroupService.to.info(groupId);

    if (group != null) {
      TimService.to.currentConversationId.value = 'group_' + groupId;

      currentGroup.value.group = group;

      currentGroup.value.groupID = groupId;

      var selfInfo = await TimGroupService.to.getMemberInfo(
        group,
        AuthService.to.userId,
      );

      if (selfInfo?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_ADMIN) {
        currentGroup.value.isAdmin = true;
      }

      if (selfInfo?.role == GroupMemberRoleType.V2TIM_GROUP_MEMBER_ROLE_OWNER) {
        currentGroup.value.isOwner = true;
      }

      currentGroup.value.selfInfo = await TimGroupService.to.getMemberInfo(
        group,
        AuthService.to.userId,
      );

      currentGroup.value.conversation = await TimConversationService.to.getById(
        'group_' + groupId,
      );

      currentGroup.refresh();
    }
  }

  /// 获取群成员列表
  Future<void> fetchGroupMemberList() async {
    var members = await TimGroupService.to.members(
      currentGroup.value.groupID,
      count: 13,
    );

    currentGroup.value.memberList = members;

    var admins = await TimGroupService.to.members(
      currentGroup.value.groupID,
      count: 100,
      filter: GroupMemberFilterTypeEnum.V2TIM_GROUP_MEMBER_FILTER_ADMIN,
    );

    currentGroup.value.adminList = admins;
    currentGroup.refresh();
  }

  /// 更新群名称
  Future<void> updateGroupName(String name) async {
    var result = await TimGroupService.to.updateName(
      currentGroup.value.group!,
      name,
    );

    if (result) {
      currentGroup.value.group!.groupName = name;
      currentGroup.value.conversation!.showName = name;
      currentGroup.refresh();
      UiTools.toast('群名称修改成功');
      Get.back();
    }
  }

  /// 更新我的群名片
  Future<void> updateGroupNameCard(String nameCard) async {
    var res = await TimGroupService.to.setMemberInfo(
      currentGroup.value.group!,
      AuthService.to.userId,
      nameCard,
    );
    if (res) {
      currentGroup.value.selfInfo!.nameCard = nameCard;
      currentGroup.refresh();

      UiTools.toast('群名片修改成功');
      Get.back();
    }
  }

  Future<void> updateGroupNotification(String notification) async {
    var res = await TimGroupService.to.updateNotification(
      currentGroup.value.group!,
      notification,
    );
    if (res) {
      currentGroup.value.group!.notification = notification;
      currentGroup.refresh();

      UiTools.toast('群公告更新成功');
      Get.back();
    }
  }

  Future<void> togglePinned() async {
    var res = await TimConversationService.to.setOnTop(
      currentGroup.value.conversation!,
    );

    if (res) {
      currentGroup.value.conversation = await TimConversationService.to.getById(
        'group_' + currentGroup.value.groupID,
      );

      currentGroup.refresh();
      UiTools.toast('修改成功');
    }
  }

  Future<void> toggleReceiveOpt() async {
    var res = await TimConversationService.to.setReceiveOpt(
      currentGroup.value.conversation!,
    );

    if (res) {
      currentGroup.value.conversation = await TimConversationService.to.getById(
        'group_' + currentGroup.value.groupID,
      );
      currentGroup.refresh();

      UiTools.toast('修改成功');
    }
  }

  /// 移除群成员
  Future<bool> kick(List<String> ids) async {
    var result = await TimGroupService.to.kickMember(
      GroupController.to.currentGroup.value.group!,
      ids,
    );

    if (result) {
      setCurrentGroup(currentGroup.value.groupID);
      fetchGroupMemberList();
    }

    return result;
  }

  Future<bool> transfer(V2TimGroupMemberFullInfo member) async {
    OkCancelResult result = await showOkCancelAlertDialog(
      style: AdaptiveStyle.iOS,
      context: Get.context!,
      title: '操作提示',
      message: '确定选择 ${member.nickName} 为新群主，您将自动放弃群主身份。',
      okLabel: '确定',
      cancelLabel: '取消',
      defaultType: OkCancelAlertDefaultType.ok,
    );

    if (result == OkCancelResult.ok) {
      var res = await TimGroupService.to.transfer(
        currentGroup.value.group!,
        member.userID,
      );

      if (res) {
        /// 直接修改当前用户的身份，为普通用户
        currentGroup.value.isAdmin = false;
        currentGroup.value.isOwner = false;
        await fetchGroupMemberList();
      }

      return res;
    }
    return false;
  }

  Future<bool> setAdmin(String userID) async {
    var result = await TimGroupService.to.setMemberRole(
      currentGroup.value.group!,
      userID,
      GroupMemberRoleTypeEnum.V2TIM_GROUP_MEMBER_ROLE_ADMIN,
    );

    if (result) {
      UiTools.toast('设置群管理成功');
    }
    return result;
  }

  Future<bool> cancelAdmin(String userID) async {
    var result = await TimGroupService.to.setMemberRole(
      currentGroup.value.group!,
      userID,
      GroupMemberRoleTypeEnum.V2TIM_GROUP_MEMBER_ROLE_MEMBER,
    );
    if (result) {
      UiTools.toast('取消群管理成功');
    }

    return result;
  }
}
