import 'package:get/get.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/index.dart';
import 'index.dart';
import 'org_person_list/index.dart';
import 'person/index.dart';

class ContactController extends GetxController {
  ContactController();

  final state = ContactState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    loadContact();
    super.onReady();
  }

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

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadContact() async {
    if (O2ContactPermissionManager.instance.isCurrentPersonCannotQueryAll()) {
      OLogger.i('当前用户没有权限查询通讯录');
      return ;
    }
    var dn = O2ApiManager.instance.o2User?.distinguishedName;
    if (dn != null && dn.isNotEmpty) {
      var myIdentities =
          await OrganizationControlService.to.identityListByPerson(dn);
      if (myIdentities != null && myIdentities.isNotEmpty) {
        loadMyDepartments(myIdentities);
        if (!O2ContactPermissionManager.instance.isCurrentPersonCannotQueryOuter()) {
           loadTopUnit(myIdentities);
        } else {
          OLogger.i('当前用户没有权限查询外部门！');
        }
      }
    }
  }

  Future<void> loadMyDepartments(List<O2Identity> identities) async {
    var myDepartments = await OrganizationAssembleExpressService.to
        .unitListWithIdentities(
            identities.map((e) => e.distinguishedName!).toList());
    if (myDepartments != null && myDepartments.isNotEmpty) {
      // 查询排除
      List<O2Unit> newList = [];
      for (var element in myDepartments) {
        if (!O2ContactPermissionManager.instance.isExcludeUnit(element.distinguishedName??'')) {
          newList.add(element);
        }
      }
      state.myDepartments.addAll(newList);
    }
  }

  Future<void> loadTopUnit(List<O2Identity> identities) async {
    state.topUnit.clear();
    List<O2Unit> tops = [];
    // 全部顶级列示
    for (var i = 0; i < identities.length; i++) {
      final idDn = identities[i].distinguishedName;
      if (idDn?.isEmpty == true) {
        continue;
      }
      final unitTop = await OrganizationAssembleExpressService.to.unitByIdAndLevel(idDn!, 1);
      if (unitTop != null) {
        if (!O2ContactPermissionManager.instance.isExcludeUnit(unitTop.distinguishedName??'')) {
          if (!tops.any((uniqueObj) => uniqueObj.distinguishedName == unitTop.distinguishedName)) { // 去重复
            tops.add(await loadFirstLevelUnitAndPersonList(unitTop));
          }
        }
      }
    }
    state.topUnit.addAll(tops);
  }

  /// 获取第一层组织人员列表
  Future<O2Unit> loadFirstLevelUnitAndPersonList(O2Unit parent) async {
    final parentId = parent.distinguishedName;
    if (parentId == null) {
      OLogger.e('顶级组织的 ${parent.name} distinguishedName is null');
      return parent;
    }
    // 加载组织列表
    List<O2Unit>? orgs = await OrganizationControlService.to.unitListWithParent(parentId);
    if (orgs != null && orgs.isNotEmpty) { // 排除检查
      List<O2Unit> newUnitList = [];
      for (var element in orgs) {
        if (!O2ContactPermissionManager.instance.isExcludeUnit(element.distinguishedName??'')) {
          newUnitList.add(element);
        }
      }
      orgs = newUnitList;
    }
    parent.subUnitList = orgs;
    // 加载人员列表
    List<O2Identity>? identits = await OrganizationControlService.to.identityListWithUnit(parentId);
    List<O2Person>? persons;
    if (identits != null && identits.isNotEmpty) {
      persons = await OrganizationAssembleExpressService.to.listPersonWithIdentities(identits.map((e) => e.distinguishedName!).toList());
      if (persons != null && persons.isNotEmpty) {
        List<O2Person> newlist = [];
        for (var element in persons) { // 排除检查
          if (!O2ContactPermissionManager.instance.isExcludePerson(element.distinguishedName ?? '')) {
            newlist.add(element);
          }
        }
        persons = newlist;
      }
    }
    parent.personList = persons;
    return parent;
  }

  void openSearchContact() {
    if (O2ContactPermissionManager.instance.isCurrentPersonCannotQueryAll() || O2ContactPermissionManager.instance.isCurrentPersonCannotQueryOuter()) {
      OLogger.i('当前用户没有权限搜索通讯录');
      Loading.toast('contact_no_permission'.tr);
      return ;
    }
    Get.toNamed(O2OARoutes.homeContactSearch);
  }
  /// 打开部门
  void openDept(O2Unit o2unit) {
    OrgPersonListPage.open(top: o2unit);
  }
  ///
  /// 打开个人信息
  /// 
  void clickEnterPerson(O2Person person) {
    PersonPage.openPersonInfo(person);
  }
}
