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_identity_picker_search/index.dart';

class PersonOrIdentityPickerController extends GetxController {
  PersonOrIdentityPickerController(
      {required this.mode, required this.initData});

  ContactPickerArguments initData;
  final ContactPickMode mode;
  final eventBus = EventBus();
  final personIdentityPickerId = 'person_identity_picker_id';

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

   Map<String, String> headers = {};
 
  /// 已经选中的身份列表
  final RxList<O2Identity> identityPickedList = <O2Identity>[].obs;

 @override
  void onInit() {
    super.onInit();
    eventBus.on(EventBus.personPickerRemovePersonMsg, personIdentityPickerId, (arg) {
      if (arg is O2Identity) {
        identityPickedList.remove(arg);
      }
     });
     eventBus.on(EventBus.identityPickerRemoveIdentityMsg, personIdentityPickerId, (arg) {
      if (arg is O2Identity) {
        identityPickedList.remove(arg);
      }
     });
  }
  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    eventBus.off(EventBus.personPickerRemovePersonMsg, personIdentityPickerId);
    eventBus.off(EventBus.identityPickerRemoveIdentityMsg, personIdentityPickerId);
    super.onClose();
  }

  @override
  void onReady() {
    // 初始化数据
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    // 初始化面包屑
    breadcrumbBeans.clear();
    breadcrumbBeans.add(ContactBreadcrumbBean(
        O2.o2DefaultUnitParentId, 'home_tab_contact'.tr, orgLevel));
    dealWithInitData();
    startLoading();
    super.onReady();
  }

  // 传入的初始化数据
  Future<void> dealWithInitData() async {
    if (mode == ContactPickMode.personPicker) {
      final initUserList = initData.initUserList ?? [];
      if (initUserList.isNotEmpty) {
        final checkedIdentities = await OrganizationAssembleExpressService.to.listIdentityWithPersons(initUserList);
        if (checkedIdentities != null && checkedIdentities.isNotEmpty) {
          if (initData.multiple == true) {
            for (var identity in checkedIdentities) {
              identityPickedList.add(identity);
              eventBus.emit(EventBus.contactPickerAddPersonMsg, identity);
            }
          } else {
            identityPickedList.add(checkedIdentities[0]);
            eventBus.emit(EventBus.contactPickerAddPersonMsg, checkedIdentities[0]); 
          }
        }
      }
    } else if (mode == ContactPickMode.identityPicker) {
      final initIdList = initData.initIdList ?? [];
      if (initIdList.isNotEmpty) {
        final checkedIdentities = await OrganizationAssembleExpressService.to.listIdentityObjects(initIdList);
        if (checkedIdentities != null && checkedIdentities.isNotEmpty) {
          if (initData.multiple == true) {
            for (var identity in checkedIdentities) {
              identityPickedList.add(identity);
              eventBus.emit(EventBus.contactPickerAddIdentityMsg, identity);
            }
          } else {
            identityPickedList.add(checkedIdentities[0]);
            eventBus.emit(EventBus.contactPickerAddIdentityMsg, checkedIdentities[0]); 
          }
        }
      }
    }
  }

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

  /// 查询数据
  Future<void> loadOrgAndIdentityData(String parentId, int level) async {
    orgLevel = level;
    OLogger.d(
        '查询数据， orgLevel: $orgLevel, parent: $parentId, topList:${initData.topUnitList}  dutyList:${initData.dutyList}');
    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);
      List<O2Identity>? identits;
      if (initData.dutyList != null && initData.dutyList?.isNotEmpty == true) {
        identits = await OrganizationAssembleExpressService.to
            .identityListByUnitAndDuty(initData.dutyList!, parentId);
      } else {
        identits =
            await OrganizationControlService.to.identityListWithUnit(parentId);
      }
      refreshListData(orgs ?? [], identits ?? []);
    }
  }

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

    ///  人员头像
  String personIconUrl(String person) {
    return OrganizationControlService.to.iconUrl(person);
  }

  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));
    loadOrgAndIdentityData(o2unit.id ?? '', orgLevel);
  }
  /// 当前身份或人员是否已经选中
  bool isItemChecked(O2Identity o2identity) {
    final isCheced = identityPickedList.firstWhereOrNull((element) => element.distinguishedName == o2identity.distinguishedName);
    return isCheced != null;
  }

  /// 选中状态变化
  void onItemCheckedChange(O2Identity o2identity, bool? checked) {
    OLogger.d('checked change id：${o2identity.distinguishedName} checked: $checked');
    if (checked == true) {
      if (initData.multiple == true) {
        if ((initData.maxNumber??0) > 0 && identityPickedList.length >= initData.maxNumber!) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        }
      } else {
        if (identityPickedList.isNotEmpty) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        } 
      }
      identityPickedList.add(o2identity);
      if (mode == ContactPickMode.personPicker) {
        eventBus.emit(EventBus.contactPickerAddPersonMsg, o2identity);
      } else if(mode == ContactPickMode.identityPicker) {
        eventBus.emit(EventBus.contactPickerAddIdentityMsg, o2identity);
      }
    } else {
      identityPickedList.remove(o2identity);
      if (mode == ContactPickMode.personPicker) {
        eventBus.emit(EventBus.contactPickerRemovePersonMsg, o2identity);
      } else if(mode == ContactPickMode.identityPicker) {
        eventBus.emit(EventBus.contactPickerRemoveIdentityMsg, o2identity);
      }
    }
  }

  Future<void> openSearchDialog() async {
    final result = await PersonIdentityPickerSearchPage.openSearch(initData, identityPickedList);
    if (result != null &&  result['identityList'] != null) {
      List<O2Identity> resultList = result['identityList'] ?? [];
      identityPickedList.clear();
      identityPickedList.addAll(resultList);
      if (mode == ContactPickMode.personPicker) {
        eventBus.emit(EventBus.contactPickerChangeAllPersonMsg, resultList);
      } else if(mode == ContactPickMode.identityPicker) {
        eventBus.emit(EventBus.contactPickerChangeAllIdentityMsg, resultList);
      }
    }
  }
}
