import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/string_extension.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/widgets/index.dart';
import '../../contact/contact_picker/index.dart';
import 'index.dart';

class GroupMembersController extends GetxController {
  GroupMembersController();

  final state = GroupMembersState();
  String? conversationId;
  IMConversationInfo? conversationInfo;
 
  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null) {
      if (map["conversationInfo"] != null) {
        conversationInfo = map["conversationInfo"] as IMConversationInfo;
      }
      state.canUpdate = map["update"] ?? false;
    }
    if (conversationInfo == null) {
      Loading.showError('args_error'.tr);
      Get.back();
    }
    conversationId = conversationInfo!.id;
    state.groupName = conversationInfo!.title ?? '';
    state.groupAdminName = (conversationInfo!.adminPerson ?? '').o2NameCut();
    state.memberList.clear();
    state.memberList.addAll(conversationInfo!.personList??[]);
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
 
  void clickDeleteMember(String personDn) {
    if (!state.canUpdate) {
      return;
    }
    if (personDn == O2ApiManager.instance.o2User?.distinguishedName) {
      return;
    }
    String name = personDn.o2NameCut();
    O2UI.showConfirm(Get.context, '确认要删除【$name】这个成员吗？', okPressed: () => _removeMember(personDn));
  }

  void clickAddMember() async {
    var result = await ContactPickerPage.startPicker([ContactPickMode.personPicker], multiple: true);
    if (result is ContactPickerResult) {
      List<String> personList = [];
      result.users?.forEach((element) {
        personList.add(element.distinguishedName!);
      });
      if (personList.isNotEmpty) {
        var oldPersonList = state.memberList.toList();
        oldPersonList.addAll(personList);
        updateMembers(oldPersonList);
      }
    }
  }

  void _removeMember(String personDn) {
    var personList = state.memberList.toList();
    personList.remove(personDn);
    updateMembers(personList);
  }



  void updateMembers(List<String> personList) async {
    var form = IMConversationInfo();
    form.id = conversationId;
    form.personList = personList;
    final result =
          await MessageCommunicationService.to.updateConversation(form);
      OLogger.d("更新会话成员： $result");
    if (result != null) {
      state.memberList.clear();
      state.memberList.addAll(personList);
      Loading.toast('im_chat_success_update_group_members'.tr);
    }
  }
}
