import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

class OrgPickerSearchController extends GetxController {
  OrgPickerSearchController();

  final state = OrgPickerSearchState();
  final TextEditingController searchController = TextEditingController();

  final FocusNode searchNode = FocusNode();

  ContactPickerArguments? pickerArgs;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final args = Get.arguments;
    if (args != null) {
      pickerArgs = args['arguments'];
      final list = args['unitPickedList'];
      state.unitPickedList.clear();
      if (list != null && list.isNotEmpty) {
        state.unitPickedList.addAll(list);
      }
    }
    super.onReady();
  }

  void onEditingComplete() {
    final key = searchController.text.trim();
    OLogger.d("搜索关键字 ：$key  onEditingComplete");
    onSearch(key);
  }

  void onSubmit(String v) {
    final key = searchController.text.trim();
    OLogger.d("搜索关键字 ：$key  onSubmit");
    onSearch(key);
  }

  /// 搜索
  Future<void> onSearch(String key) async {
    OLogger.d("搜索关键字：$key");
    if (key.isNotEmpty) {
      final list = await OrganizationControlService.to.unitSearch(key);
      state.unitList.clear();
      if (list != null && list.isNotEmpty) {
        state.unitList.addAll(list);
      }
    } else {
      state.unitList.clear();
    }
  }

  bool isItemChecked(O2Unit o2unit) {
    final isCheced = state.unitPickedList.firstWhereOrNull(
        (element) => element.distinguishedName == o2unit.distinguishedName);
    return isCheced != null;
  }

  void onItemCheckedChange(O2Unit o2unit, bool? checked) {
    OLogger.d(
        'checked change id：${o2unit.distinguishedName} checked: $checked');
    if (checked == true) {
      if (pickerArgs?.multiple == true) {
        if ((pickerArgs?.maxNumber ?? 0) > 0 &&
            state.unitPickedList.length >= (pickerArgs?.maxNumber)!) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        }
      } else {
        if (state.unitPickedList.isNotEmpty) {
          Loading.toast('contact_picker_msg_more_than_max'.tr);
          return;
        }
      }
      state.unitPickedList.add(o2unit);
    } else {
      state.unitPickedList.remove(o2unit);
    }
  }

  void clickCancel() {
    Get.back(result: {
      'unitList': state.unitPickedList,
    });
  }
}
