import 'package:get/get.dart';

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

class OrgPersonListController extends GetxController {
  OrgPersonListController();

  final state = OrgPersonListState();
  int orgLevel = 0; // 组织层级
  O2Unit? initTopUnit;

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null && map is O2Unit) {
      initTopUnit = map;
    }
    if (initTopUnit != null) {
      state.breadcrumbBeans.clear();
      state.breadcrumbBeans.add(ContactBreadcrumbBean(
          initTopUnit!.distinguishedName ?? '',
          initTopUnit!.name ?? '',
          initTopUnit!.level ?? 0));
    } else {
      // 初始化面包屑
      state.breadcrumbBeans.clear();
      state.breadcrumbBeans.add(ContactBreadcrumbBean(
          O2.o2DefaultUnitParentId, 'home_tab_contact'.tr, orgLevel));
    }

    startLoading();
    super.onReady();
  }

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

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

  void clickBreadcrumb(ContactBreadcrumbBean bean) {
    var lastIndex = -1;
    for (var i = 0; i < state.breadcrumbBeans.length; i++) {
      final element = state.breadcrumbBeans[i];
      if (bean.key == element.key) {
        lastIndex = i;
        break;
      }
    }
    if (lastIndex >= 0) {
      final newList = state.breadcrumbBeans.sublist(0, lastIndex + 1);
      state.breadcrumbBeans.clear();
      state.breadcrumbBeans.addAll(newList);
      orgLevel = newList.last.level;
      startLoading();
    }
  }

  /// 点击组织进入下一级
  void clickEnterOrg(O2Unit o2unit) {
    OLogger.d('clickEnterOrg  id：${o2unit.distinguishedName} ');
    orgLevel += 1;
    state.breadcrumbBeans.add(
        ContactBreadcrumbBean(o2unit.id ?? '', o2unit.name ?? '', orgLevel));
    loadOrgAndIdentityData(o2unit.id ?? '', orgLevel);
  }

  ///
  /// 打开个人信息
  /// 
  void clickEnterPerson(O2Person person) {
    PersonPage.openPersonInfo(person);
  }

  //刷新列表
  void startLoading() {
    final bean = state.breadcrumbBeans[state.breadcrumbBeans.length - 1]; //最后一个
    loadOrgAndIdentityData(bean.key, bean.level);
  }

  /// 查询数据
  Future<void> loadOrgAndIdentityData(String parentId, int level) async {
    orgLevel = level;
    OLogger.d('查询数据， orgLevel: $orgLevel, parent: $parentId ');
    Loading.show();
    if (parentId == O2.o2DefaultUnitParentId) {
      // 顶层 只查询组织
      List<O2Unit>? topList = await OrganizationControlService.to.unitTopList();
      refreshListData(topList ?? [], []);
    } else {
      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;
      }
      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;
        }
      }
      refreshListData(orgs ?? [], persons ?? []);
    }
  }

  void refreshListData(List<O2Unit> unitList, List<O2Person> identits) {
    Loading.dismiss();
    state.orgList.clear();
    state.orgList.addAll(unitList);
    state.personList.clear();
    state.personList.addAll(identits);
  }
}
