import 'dart:core';

import 'package:anchor_collect_flutter/controllers/ble_service.dart';
import 'package:anchor_collect_flutter/routes/routes.dart';
import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../congifs.dart';
import '../../rfid/rfid_plugin.dart';
import 'setting_state.dart';

class SettingLogic extends GetxController {
  final SettingState state = SettingState();

  @override
  void onInit() {
    // 一开始就检查权限
    requestBlePermissions();
  }

  refreshBle() {
    if (state.isScanning.value) {
      DialogUtils.showToast('停止扫描');
      RfidPlugin.stopScanDevice();
    } else {
      state.scanResults.clear();
      DialogUtils.showToast('开始扫描');
      RfidPlugin.startScanDevice((args, args2) {
        state.scanResults.add(args);
      });
    }
  }

  connectBle(BuildContext context, int index) {
    if (Config.isConnect) {
      RfidPlugin.disConnectDevice();
    }
    RfidPlugin.stopScanDevice();
    state.isScanning.value = false;
    RfidPlugin.connectDevice(state.scanResults[index], (args, args1) {
      print('event:进入callback');
      DialogUtils.showToast('设备连接成功');
      Get.back();
    });
    Config.isConnect = true;
  }

  // 检查权限
  Future<bool> requestBlePermissions() async {
    var isLocationGranted = await Permission.locationWhenInUse.request();
    print('checkBlePermissions, isLocationGranted=$isLocationGranted');

    var isBleScanGranted = await Permission.bluetoothScan.request();
    print('checkBlePermissions, isBleScanGranted=$isBleScanGranted');
    //
    var isBleConnectGranted = await Permission.bluetoothConnect.request();
    print('checkBlePermissions, isBleConnectGranted=$isBleConnectGranted');
    //
    var isBleAdvertiseGranted = await Permission.bluetoothAdvertise.request();
    print('checkBlePermissions, isBleAdvertiseGranted=$isBleAdvertiseGranted');

    return isLocationGranted == PermissionStatus.granted &&
        isBleScanGranted == PermissionStatus.granted &&
        isBleConnectGranted == PermissionStatus.granted &&
        isBleAdvertiseGranted == PermissionStatus.granted;
  }
}
