import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

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

  final ContactPickerArguments initData;
   // 群组列表
  final RxList<O2Group> groupList = <O2Group>[].obs;
  // 已经选中的组织列表
  final RxList<O2Group> groupPickedList = <O2Group>[].obs;

  //
  final refreshController = RefreshController();
  final hasMoreData = true.obs;
  String lastGroupId = O2.o2DefaultPageFirstKey;

  final eventBus = EventBus();
  final goupPickerId = 'group_picker_id';

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

  @override
  void onReady() {
    dealWithInitData();
    refreshGroupList();
    super.onReady();
  }


  // 传入的初始化数据
  Future<void> dealWithInitData() async {
    final initGroupList = initData.initGroupList ?? [];
    if (initGroupList.isNotEmpty) {
      final checkedGroups = await OrganizationAssembleExpressService.to.listGroupObjects(initGroupList);
      if (checkedGroups != null && checkedGroups.isNotEmpty) {
        if (initData.multiple == true) {
          for (var group in checkedGroups) {
            groupPickedList.add(group);
            eventBus.emit(EventBus.contactPickerAddGroupMsg, group);
          }
        } else {
          groupPickedList.add(checkedGroups[0]);
          eventBus.emit(EventBus.contactPickerAddGroupMsg, checkedGroups[0]);
        }
      }
    }
  }
  /// 刷新列表
  Future<void> refreshGroupList() async {
    lastGroupId = O2.o2DefaultPageFirstKey;
    final list = await OrganizationControlService.to.getGroupListByPage(lastGroupId);
    if (list == null || list.isEmpty == true) {
      hasMoreData.value = false;
      refreshController.refreshCompleted();
      return;
    }
    groupList.clear();
    groupList.addAll(list);
    lastGroupId = groupList.last.id!;
    if (list.length == O2.o2DefaultPageSize) {
      hasMoreData.value = true;
    }
    refreshController.refreshCompleted();
  }
  /// 加载更多数据
  Future<void> getMoreGroupList() async {
    if (!hasMoreData.value) {
      refreshController.loadComplete();
      return;
    }
    final list = await OrganizationControlService.to.getGroupListByPage(lastGroupId);
    if (list == null || list.isEmpty == true) {
      hasMoreData.value = false;
      refreshController.loadComplete();
      return;
    }
    groupList.addAll(list);
    lastGroupId = groupList.last.id!;
    if (list.length == O2.o2DefaultPageSize) {
      hasMoreData.value = true;
    }
    refreshController.loadComplete();
  }

  /// 当前 群组是否已经选中
  bool isItemChecked(O2Group group) {
    final isCheced = groupPickedList.firstWhereOrNull((element) => element.distinguishedName == group.distinguishedName);
    return isCheced != null;
  }

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

 
}
