import 'package:get/get.dart';

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

class OrgPickerController extends GetxController {
  OrgPickerController({required this.initData});

  final ContactPickerArguments initData;

  int orgLevel = 0; // 组织层级
  //面包屑
  RxList<ContactBreadcrumbBean> breadcrumbBeans = <ContactBreadcrumbBean>[].obs;
  // 组织列表
  final RxList<O2Unit> orgList = <O2Unit>[].obs;

  /// 已经选中的组织列表
  final RxList<O2Unit> unitPickedList = <O2Unit>[].obs;

  final eventBus = EventBus();
  final unitPickerId = 'unit_picker_id';


 @override
  void onInit() {
    super.onInit();
    eventBus.on(EventBus.unitPickerRemoveUnitMsg, unitPickerId, (arg) {
      if (arg is O2Unit) {
        unitPickedList.remove(arg);
      }
     });
    
  }
  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    eventBus.off(EventBus.unitPickerRemoveUnitMsg, unitPickerId);
    super.onClose();
  }


  @override
  void onReady() {
    // 初始化面包屑
    breadcrumbBeans.clear();
    breadcrumbBeans.add(ContactBreadcrumbBean(
        O2.o2DefaultUnitParentId, 'home_tab_contact'.tr, orgLevel));
    dealWithInitData();
    startLoading();
    super.onReady();
  }

  // 传入的初始化数据
  Future<void> dealWithInitData() async {
    final initDeptList = initData.initDeptList ?? [];
    if (initDeptList.isNotEmpty) {
      final checkedUnits = await OrganizationAssembleExpressService.to
          .listUnitObjects(initDeptList);
      if (checkedUnits != null && checkedUnits.isNotEmpty) {
        if (initData.multiple == true) {
          for (var unit in checkedUnits) {
            unitPickedList.add(unit);
            eventBus.emit(EventBus.contactPickerAddUnitMsg, unit);
          }
        } else {
          unitPickedList.add(checkedUnits[0]);
          eventBus.emit(EventBus.contactPickerAddUnitMsg, checkedUnits[0]);
        }
      }
    }
  }

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

  /// 查询数据
  Future<void> loadOrgData(String parentId, int level) async {
    orgLevel = level;
    OLogger.d(
        '查询数据， orgLevel: $orgLevel, parent: $parentId, topList:${initData.topUnitList}');
    Loading.show();
    if (parentId == O2.o2DefaultUnitParentId) {
      // 顶层 只查询组织
      List<O2Unit>? topList;
      if (initData.topUnitList != null &&
          initData.topUnitList?.isNotEmpty == true) {
        topList =
            await OrganizationControlService.to.unitList(initData.topUnitList!);
      } else {
        topList = await OrganizationControlService.to.unitTopList();
      }
      refreshListData(topList ?? []);
    } else {
      List<O2Unit>? orgs =
          await OrganizationControlService.to.unitListWithParent(parentId);
      refreshListData(orgs ?? []);
    }
  }

  void refreshListData(List<O2Unit> unitList) {
    Loading.dismiss();
    orgList.clear();
    orgList.addAll(unitList);
  }

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

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

  /// 当前组织是否已经选中
  bool isItemChecked(O2Unit o2unit) {
    final isCheced =
        unitPickedList.firstWhereOrNull((element) => element.id == o2unit.id);
    return isCheced != null;
  }

  /// 选中状态变化
  void onItemCheckedChange(O2Unit o2unit, bool? checked) {
    OLogger.d(
        'checked change id：${o2unit.distinguishedName} checked: $checked');
    if (checked == true) {
      if (initData.multiple == true) {
        if ((initData.maxNumber ?? 0) > 0 &&
            unitPickedList.length >= initData.maxNumber!) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        }
      } else {
        if (unitPickedList.isNotEmpty) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        }
      }
      unitPickedList.add(o2unit);
      eventBus.emit(EventBus.contactPickerAddUnitMsg, o2unit);
    } else {
      unitPickedList.remove(o2unit);
      eventBus.emit(EventBus.contactPickerRemoveUnitMsg, o2unit);
    }
  }

  Future<void> openSearchDialog() async {
    final result = await OrgPickerSearchPage.openSearch(initData, unitPickedList);
    if (result != null &&  result['unitList'] != null) {
      List<O2Unit> resultList = result['unitList'] ?? [];
      unitPickedList.clear();
      unitPickedList.addAll(resultList);
      eventBus.emit(EventBus.contactPickerChangeAllUnitMsg, resultList);
    }
  }
}
