import 'dart:async';

import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:permission_handler/permission_handler.dart';

import '../models/cattle_resume_entity.dart';
import '../models/dict_entity.dart';
import '../models/user_model.dart';

typedef void DiscoveredCallback(args);
typedef void ConnectCallback(args);

class BleService extends GetxService {
  static BleService get to => Get.find();

  late DiscoveredCallback? discoveredCallback;
  late ConnectCallback? connectCallback;

  // 添加一个 StreamController
  final _readController = StreamController<List<int>>();

  Stream<List<int>> get readStream => _readController.stream;

  late Uuid _serviceId;
  late Uuid _writeCharacteristicId;
  late Uuid _notifiCharacteristicId;

  // 添加一个标志，用于控制读取循环是否应该继续
  bool _shouldContinueReading = false;

  var isScanning = false.obs;
  final ble = FlutterReactiveBle();

  //判断是否正在扫描
  StreamSubscription<DiscoveredDevice>? scanSubscription;

  //判断设备选中状态
  final selectedDevice = Rx<DiscoveredDevice?>(null);

  //判断设备连接状态
  String deviceStatus = '';

  // ignore: cancel_subscriptions
  late StreamSubscription<ConnectionStateUpdate> streamSubscriptionConnection;

  Future<BleService> init() async {
    return this;
  }

  // 切换扫描状态
  Future<void> toggleScan(DiscoveredCallback callback) async {
    discoveredCallback = callback;
    if (isScanning.value) {
      await scanSubscription?.cancel();
      isScanning.value = false;
    } else {
      await scanDevices();
    }
  }

  // 扫描设备
  Future<void> scanDevices() async {
    // 检查权限
    bool permissionsGranted = await requestBlePermissions();
    if (!permissionsGranted) {
      Get.snackbar('Permissions required', 'Please grant all necessary permissions');
      return;
    }
    // 扫描开始时，设置 isScanning 为 true
    isScanning.value = true;

    // 扫描设备
    final scanStream = ble.scanForDevices(
      withServices: [],

      //scanMode: ScanMode.balanced,  // 将 scanMode 设置为 balanced 功耗均衡，扫描慢
      scanMode: ScanMode.lowLatency, // 将 scanMode 设置为 lowLatency 功耗大 扫描快
    );

    // 监听扫描结果
    scanSubscription = scanStream.listen((device) {
      // 如果设备名称不为空，且列表中没有该设备，则添加到列表中
      if (device.name != null && device.name!.isNotEmpty) {
        if (discoveredCallback != null) {
          discoveredCallback!(device);
        }
      }
    });

    ///扫描10秒
    Future.delayed(const Duration(seconds: 15), () async {
      await scanSubscription?.cancel();
      isScanning.value = false;
      DialogUtils.showToast('自动停止扫描');
    });
  }

  // 连接设备
  Future<void> connectToDevice(DiscoveredDevice device, BuildContext context, ConnectCallback callback) async {
    connectCallback = callback;
    selectedDevice.value = device; // 设置当前选中的设备

    await scanSubscription?.cancel(); // 在连接设备之前，停止扫描
    isScanning.value = false; // 设置 isScanning 为 false

    DialogUtils.showLoadingDialog('正在连接到 ${device.name}');
    // 显示正在连接的对话框
    // showDialog(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (BuildContext context) {
    //     return AlertDialog(
    //       title: Text('Connecting to ${device.name}'),
    //       content: CircularProgressIndicator(),
    //     );
    //   },
    // );

    // 连接设备
    var connection = ble.connectToDevice(
      id: device.id,
      connectionTimeout: const Duration(milliseconds: 10000),
      servicesWithCharacteristicsToDiscover: {},
    );

    // 监听连接状态
    streamSubscriptionConnection = connection.listen((update) async {
      // 如果连接状态为 connected，则显示连接成功的提示
      if (update.connectionState == DeviceConnectionState.connected) {
        // 发现服务和特性
        final services = await ble.discoverServices(device.id);
        for (final service in services) {
          if (service.serviceId.toString() == '000180') {
            _serviceId = service.serviceId;
            if (kDebugMode) {
              print('Discovered service ${service.serviceId}');
            }
            for (final characteristic in service.characteristics) {
              if(characteristic.isWritableWithoutResponse) {
                _writeCharacteristicId = characteristic.characteristicId;
                if (kDebugMode) {
                  print('WritableWithoutResponse characteristic ${characteristic.characteristicId} of service ${service.serviceId}');
                }
              }
              if(characteristic.isNotifiable) {
                _notifiCharacteristicId = characteristic.characteristicId;
                if (kDebugMode) {
                  print('Notifiable characteristic ${characteristic.characteristicId} of service ${service.serviceId}');
                }
              }
            }
          }
        }
        // 设置最大传输单元
        await ble.requestMtu(deviceId: device.id, mtu: 512);
        await Future.delayed(const Duration(seconds: 1)); // 添加延迟
        deviceStatus = 'Connected'; // 更新设备的连接状态
        // Get.snackbar('Connected', 'Connected to ${device.name}');
        // Navigator.of(context).pop();
        if (connectCallback != null) {
          connectCallback!(device);
        }

        // 关闭对话框
        DialogUtils.dismissDialog();
      } else if (update.connectionState == DeviceConnectionState.connecting) {
        DialogUtils.showToast('设备连接中');
      } else {
        DialogUtils.dismissDialog();
        DialogUtils.showToast('连接设备失败');
        deviceStatus = 'Disconnected'; // 更新设备的连接状态
      }
    });
  }

  // 读取数据
  Future<List<int>> readData() async {
    if (selectedDevice.value == null) {
      throw Exception('No device connected');
    }
    final characteristic = QualifiedCharacteristic(
      deviceId: selectedDevice.value!.id,
      serviceId: _serviceId,
      characteristicId: _writeCharacteristicId,
    );

    final result = await ble.readCharacteristic(characteristic);

    return result;
  }

// 写入数据
  Future<void> writeData(List<int> data) async {
    if (selectedDevice.value == null) {
      throw Exception('No device connected');
    }

    final characteristic = QualifiedCharacteristic(
      deviceId: selectedDevice.value!.id,
      serviceId: _serviceId,
      characteristicId: _writeCharacteristicId,
    );

    await ble.writeCharacteristicWithResponse(characteristic, value: data);
  }

  // 启动循环读取数据
  Future<void> startReading() async {
    _shouldContinueReading = true;

    while (_shouldContinueReading) {
      // 读取数据
      final data = await readData();
      // 将数据添加到 Stream 中
      _readController.add(data);
      // 等待一段时间，然后再次读取数据
      await Future.delayed(const Duration(seconds: 1));
    }
  }

  // 停止循环读取数据
  void stopReading() {
    _shouldContinueReading = false;
  }

  @override
  void onClose() {
    _readController.close();
    super.onClose();
  }

  // 检查权限
  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;
  }
}
