import 'package:call_log/call_log.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:project_telephony/base/base_style.dart';
import 'package:project_telephony/constants/api.dart';
import 'package:project_telephony/model/network/api_client.dart';
import 'package:project_telephony/ui/home/set/func/exclude_contacts_func.dart';
import 'package:project_telephony/utils/headers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../model/exclude_pn_model.dart';
import '../../../../model/phone_num_model.dart';
import '../../../../utils/toast/cloud_toast.dart';
import '../../../widget/scaffold_theme_widget.dart';

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

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

class _CallRecordsListState extends State<CallRecordsList> {
  List<PhoneNumModel> phoneNum = [];
  List<PhoneNumModel> phoneNum2 = [];
  // List<ExcludePnModel> phoneNum3 = [];
  List phoneNum3=[];
  // Map<String, String> get phoneNum3 => {};

  final EasyRefreshController _easyRefreshController = EasyRefreshController();
  late bool notifications;
  late bool trackHistory;
  late bool instantOrders;
  late SharedPreferences prefs;
  List<String> numList = [];

  // List<String> =[]
  @override
  void initState() {
    // getList();
    getList();
    super.initState();
  }

  @override
  void dispose() {
    _easyRefreshController.dispose();
    super.dispose();
  }

  getList() async {
    phoneNum.clear();
    final Iterable<CallLogEntry> entries = await CallLog.query();
    for (CallLogEntry entrie in entries) {
      if (!numList.contains(entrie.number)) {
        numList.add(entrie.number!);
        phoneNum.add(PhoneNumModel(
          num: entrie.number,
          time: entrie.timestamp,
          name: entrie.name,
          state: false,
        ));
      }
    }
    for (int i = 0; i < phoneNum.length; i++) {
      phoneNum2.add(PhoneNumModel(
        num: phoneNum[i].num,
        time: phoneNum[i].time,
        name: phoneNum[i].name,
        state: phoneNum[i].state,
      ));
    }
    // for (CallLogEntry entrie in entries) {
    //   if (!numList.contains(entrie.number)) {
    //     numList.add(entrie.number!);
    //     phoneNum.add(PhoneNumModel(
    //       num: entrie.number,
    //       time: entrie.timestamp,
    //       name: entrie.name,
    //       state: false,
    //     ));
    //   }
    // }
  }

  @override
  Widget build(BuildContext context) {
    return ScaffoldThemeWidget(
        bottom: '添加',
        title: '从通话记录添加',
        isBorder: true,
        isOpacity: phoneNum3.isNotEmpty,
        onTap: () async {

          if (phoneNum3.isEmpty) {
            CloudToast.show('请选择手机号');
          } else {
            // print(phoneNum3);
          await ExcludeFunc.getContactsList(phoneNum3);
            // Navigator.pop(context,true);
          Get.back();
          Get.back();

          }
          // _easyRefreshController.callRefresh();
          // phoneNum3.clear();
        },
        child: EasyRefresh(
          firstRefresh: true,
          header: MaterialHeader(),
          controller: _easyRefreshController,
          onRefresh: () async {
            getList();
            setState(() {});
          },
          child: ListView.builder(
            itemBuilder: (context, index) {
              return _getBox(phoneNum2[index], phoneNum2[index].num!,phoneNum2[index].name?? "");
            },
            itemCount: phoneNum2.length,
          ),
        ));
//    var profileBuilder =  FutureBuilder(
//      // future: _incrementCounter(),
//         future: getList() , // a Future<String> or null
//         builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
//           if(snapshot.connectionState==ConnectionState.done){
//             return ListView.builder(
//               itemBuilder: (context, index) {
//                 return _getBox(phoneNum[index]);
//               },
//               itemCount: phoneNum.length,
//             );
//           }else{
//             return const SizedBox();
//           }
//         });
// return    ScaffoldThemeWidget(
//     bottom: '添加',
//     title: '从通话记录添加',
//     isBorder: true,
//     isOpacity: false,
//     onTap: () {
//
//     },
//     child:  profileBuilder
// );
    // Column(
    //   children: [
    //     Container(width: 750.w, height: 1000.w, child: Text("")
    //
    //         // ListView(
    //         //   children: [],
    //         // ),
    //         ),
    //     PloneBottom(onTap: () async {
    //       // Iterable<CallLogEntry> entries = await CallLog.get();
    //       final Iterable<CallLogEntry> entries = await CallLog.query();
    //       for (CallLogEntry entrie in entries) {
    //         a.add(entrie.number);
    //       }
    //       // var b = entries.length;
    //       print("通话记录条数$a");
    //     })
    //   ],
    // );
  }

  _getBox(PhoneNumModel item, String num,String name) {
    return CheckboxListTile(
      onChanged: (bool? value) {
        setState(() {
          item.state = value!;
          if (item.state) {
            phoneNum3.add({"phone":num,"remark":name});
            // phoneNum3.add((phone: num, remark: name));

          } else {
            phoneNum3.remove({"phone":num,"remark":name});
            // phoneNum3.remove(ExcludePnModel(phone: num, remark: name)) ;
          }
        });
      },
      value: item.state,
      title: Text(
        item.num!,
        style: TextStyle(fontSize: 32.w, fontWeight: FontWeight.bold),
      ),
      subtitle: Row(
        children: [
          Text(
            DateUtil.formatDateMs(item.time! * 1000, format: 'MM/dd HH:mm'),
            style: TextStyle(fontSize: 28.sp, color: BaseStyle.color999999),
          ),
          30.wb,
          Text(
            item.name == null ? "" : item.name!,
            style: TextStyle(fontSize: 28.sp, color: BaseStyle.color999999),
          )
        ],
      ),
    );
  }
}
