import 'dart:async';
import 'dart:ui';

import 'package:call_log/call_log.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
import 'package:flutter_background_service_android/flutter_background_service_android.dart';
import 'package:project_telephony/utils/headers.dart';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:telephony/telephony.dart';

Future<void> initializeService() async {
  // SharedPreferences preferences = await SharedPreferences.getInstance();

  final service = FlutterBackgroundService();

  await service.configure(
    androidConfiguration: AndroidConfiguration(
      // this will be executed when app is in foreground or background in separated isolate
      onStart: onStart,
      // auto start service
      autoStart: true,
      isForegroundMode: true,
    ),
    iosConfiguration: IosConfiguration(
      // auto start service
      autoStart: true,
      // this will be executed when app is in foreground in separated isolate
      onForeground: onStart,
      // you have to enable background fetch capability on xcode project
      onBackground: onIosBackground,
    ),
  );
  service.startService();
}
// }

bool onIosBackground(ServiceInstance service) {
  WidgetsFlutterBinding.ensureInitialized();
  print('FLUTTER BACKGROUND FETCH');
  return true;
}

void onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  int flag = 0;
  String? phoneNum = "";
  int? callRecords = 0;
  String? state1="";
  // CallType? state1;
  String callState;
  final Iterable<CallLogEntry> entry = await CallLog.query();
  service.on('stopService').listen((event) {
    service.stopSelf();
  });
  // setForegroundNotificationInfo(title: "你好", content: "再见");
  // AndroidServiceInstance.
  // service.setNotificationInfo("").listen((event){
  //
  // });
  // Telephony.backgroundInstance.sendSms(to: "13486828191", message: "123123");
  Timer.periodic(const Duration(seconds: 1), (timer) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    CallState state = await Telephony.instance.callState;
    callState = state.name;
    // print(entry.first.duration);
    print(callState+"$flag");
    String? ref = prefs.getString('refSms');
    String? con = prefs.getString('conSms');
    // print(con);


    if (callState == "IDLE") {
      //闲置
      if (flag != 0) {
        final Iterable<CallLogEntry> entry = await CallLog.query();
        phoneNum = entry.first.number;
        callRecords = entry.first.duration;
        print(phoneNum);
        if (flag > 0) {
          print("来电拒接/未接");
          // Telephony.backgroundInstance.sendSms(to: phoneNum!, message: ref!);
          print("发送成功");
        } else if(flag==-1){
          print("来电接听");
          // Telephony.backgroundInstance.sendSms(to: phoneNum!, message: con!);
        }else {
          print(entry.first.callType);
          print(entry.first.duration);
          if(entry.first.duration!>0){
            print("去电接听");
          }else{
            print("去电未接");
          }
          // Telephony.backgroundInstance.sendSms(to: phoneNum!, message: con!);
          print("发送成功");
        }
        flag = 0;
      }
    } else if (callState == "RINGING") {
      //响铃
      flag=1;
      print('通话');
    } else if (callState == "OFFHOOK") {
      //通话
      if (flag > 0) flag *= -1;
      if(flag==0)flag=-2;
      print('不通话');
    }
  });
}