import 'package:clean/base/base_controller.dart';
import 'package:clean/module/contact/contact_state.dart';
import 'package:flutter/Material.dart';
import 'package:flutter_contacts/contact.dart';
import 'package:get/get.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

class AllController extends BaseController {
  // 是否为编辑状态
  RxBool isEdit = false.obs;

  // 是否全选
  RxBool isAllSelected = false.obs;

  // 存储选中的图片ID
  final RxSet<String> selectedContacts = <String>{}.obs;

  final ItemScrollController itemScrollController = ItemScrollController();
  final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

  }

  void scrollToInitial(String initial) {
    int index = ContactState.initials.indexOf(initial);
    if (index != -1) {
      itemScrollController.jumpTo(
        index: index,
        // curve: Curves,
      );
    }
  }

  // 选择/取消选择联系人
  void toggleSelectContact(Contact selectContact) {
    final asset = ContactState.contactList.firstWhere((contact) => contact.id == selectContact.id);

    if (selectedContacts.contains(selectContact.id)) {
      selectedContacts.remove(selectContact.id);
    } else {
      selectedContacts.add(selectContact.id);
    }
    // 更新全选状态
    isAllSelected.value = ContactState.selectedContact.length == ContactState.contactList.length;
  }

  // 全选/取消全选
    void toggleSelectAll() {
    if (isAllSelected.value) {
      selectedContacts.clear();
    } else {
      selectedContacts.addAll(ContactState.contactList.map((contact) => contact.id));
    }
    isAllSelected.value = !isAllSelected.value;
  }

  // 退出编辑模式时清空选择
  void exitEditMode() {
    isEdit.value = false;
    selectedContacts.clear();
    isAllSelected.value = false;
  }

  void deleteBtnClick() {
    // 获取要删除的资产
    final contactToDelete =
    ContactState.contactList.where((contact) => selectedContacts.contains(contact.id)).toList();

    for (var contact in contactToDelete) {
      contact.delete();
    }

    exitEditMode();
    ContactState.loadContacts();
  }
}