import 'package:bot_toast/bot_toast.dart';

import 'package:flutter/material.dart';
import 'package:flutter_contacts/contact.dart';
import 'package:flutter_contacts/flutter_contacts.dart';

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

import 'package:project_telephony/ui/widget/scaffold_theme_widget.dart';

class ExcludeContactsPage extends StatefulWidget {
  const ExcludeContactsPage({Key? key}) : super(key: key);

  @override
  _ExcludeContactsPageState createState() => _ExcludeContactsPageState();
}

class _ExcludeContactsPageState extends State<ExcludeContactsPage> {
  late List<Contact> contacts;
  List<String> numbers = [];
  List<bool> status = [];
  var flag = true;

  @override
  void initState() {
    super.initState();
    _incrementCounter();
  }

  Future _incrementCounter() async {
    contacts = await FlutterContacts.getContacts();
    for (var element in contacts) {
      final full = await FlutterContacts.getContact(element.id);
      numbers.add(full!.phones.first.number);
      status.add(false);
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var profileBuilder = FutureBuilder(
      future: _incrementCounter(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting && flag) {
          flag = false;
          return Container();
        } else {
          return ListView.builder(
            itemCount: contacts.length,
            itemBuilder: (context, i) => ListTile(
              title: Text(
                contacts[i].displayName,
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              subtitle: Text(
                numbers[i],
                style: TextStyle(
                  fontSize: 28.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
              trailing: Checkbox(
                value: status[i],
                // 改变后的事件
                onChanged: (value) {
                  setState(() {
                    status[i] = !status[i];
                  });
                },
                // 选中后的颜色
                activeColor: Colors.blue,
                // 选中后对号的颜色
                checkColor: Colors.white,
              ),
            ).paddingOnly(left: 20.w),
          );
        }
      },
    );

    return ScaffoldThemeWidget(
      title: "从通讯录添加",
      bottom: "添加",
      onTap: () {
        if (status.contains(true)) {
          // BotToast.showText(text: "有");

          Get.back();
        } else {
          BotToast.showText(text: "还未选中手机号");
        }
      },
      isOpacity: status.contains(true),
      isBorder: true,
      child: profileBuilder,
    );
  }
}
