import 'package:flutter_contacts/contact.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:get/get.dart';

class ContactState {

  static RxList<Contact> contactList = <Contact>[].obs;

  static RxList<String> initials = <String>[].obs;

  static RxMap<String, List<Contact>> groupedContacts = <String, List<Contact>>{}.obs;

  static RxList<Contact> selectedContact = <Contact>[].obs;

  static Future<void> loadContacts() async {
    await getContacts();
    ContactState.groupedContacts.value = groupContactsByInitial(ContactState.contactList);
    ContactState.initials.value = ContactState.groupedContacts.keys.toList()..sort();
  }

  static Future<void> getContacts() async {

    // 获取所有联系人
    List<Contact> contacts = await FlutterContacts.getContacts(
      withProperties: true,
      withPhoto: true,
    );

    // 按名字的首字母排序
    contacts.sort((a, b) => (a.displayName ?? '').compareTo(b.displayName ?? ''));
    ContactState.contactList.value = contacts;
  }

  static Map<String, List<Contact>> groupContactsByInitial(List<Contact> contacts) {
    Map<String, List<Contact>> groupedContacts = {};

    for (var contact in contacts) {
      String initial = (contact.displayName ?? '').isNotEmpty
          ? contact.displayName[0].toUpperCase()
          : '#';

      if (!groupedContacts.containsKey(initial)) {
        groupedContacts[initial] = [];
      }
      groupedContacts[initial]!.add(contact);
    }

    return groupedContacts;
  }
}