import 'dart:convert';
import 'dart:io';

import 'package:clean/base/base_controller.dart';
import 'package:clean/module/contact/contact_state.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../utils/toast_util.dart';

class ContactController extends BaseController {
  @override
  Future<void> onInit() async {
    // TODO: implement onInit
    super.onInit();

    if (await Permission.contacts.request().isGranted) {
      await ContactState.loadContacts();
      // await restoreContacts();
    } else {
      ToastUtil.show("请先开启相册权限");
    }
  }

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

    // 将联系人数据转换为 JSON
    List<Map<String, dynamic>> contactsJson =
        contacts.map((contact) => contact.toJson()).toList();

    try {

      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/contacts_backup.json');
      await file.writeAsString(jsonEncode(contactsJson));

      print('备份成功: ${file.path}');
    } catch (e) {
      print('备份失败: $e');
    }
  }

  Future<void> restoreContacts() async {
    try {

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

      for (var contact in contacts) {
        await contact.delete();
      }

      final directory = await getApplicationDocumentsDirectory();
      // 从本地文件读取备份数据
      final file = File('${directory.path}/contacts_backup.json');
      String contactsJsonString = await file.readAsString();
      List<dynamic> contactsJson = jsonDecode(contactsJsonString);

      // 将 JSON 数据转换为联系人对象并写入通讯录
      for (var contactJson in contactsJson) {
        Contact contact = Contact.fromJson(contactJson);
        contact.id = "";
        await FlutterContacts.insertContact(contact);
      }

      print('恢复成功');
    } catch (e) {
      print('恢复失败: $e');
    }
  }


  void init() {}
}
