import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/managers/device_controller_manager.dart';
import 'package:vitalapp/managers/interfaces/device.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/controllers/blue_location_mixin.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/patient/card_reader/controller.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/ic_reader.dart';
import 'package:vnote_device_plugin/models/exams/ic_reader.dart';
import 'package:fis_common/logger/logger.dart';

class BluetoothCardReaderController extends FControllerBase
    with BluetoothAndLocationMixin {
  BluetoothCardReaderController();
  ICReaderDeviceWorker? worker;
  DeviceControllerManager? icReader;
  WorkerStatus connectStatus = WorkerStatus.connecting;

  /// 是否连接中
  bool get isCardReaderConnecting => connectStatus == WorkerStatus.connecting;

  /// 是否已连接
  bool get isCardReaderConnected => connectStatus == WorkerStatus.connected;

  final _deviceManager = Get.find<IDeviceManager>();

  // _initData() async {
  //   bool result = await Idread.init();
  //   if (result) {
  //     bool start = await Idread.startRead();
  //     if (start) {
  //       Idread.dataStreamListen((data) {
  //         if (data is IdCardInfoModel) {
  //           onReadInfo(data);
  //         }
  //       });
  //     }
  //   }
  //   isCardReaderConnected = result;
  //   update(["bluetooth_card_reader"]);
  // }

  Future<DeviceModel?> getDevice(String type) async {
    List<DeviceModel> devices = await _deviceManager.getDeviceList();

    return devices.firstWhereOrNull((element) => element.type == type);
  }

  connectDevice() async {
    logger.i('BluetoothCardReaderController connectDevice');
    DeviceModel? device = await getDevice(DeviceTypes.IC_READER);
    if (device == null) {
      logger.i('BluetoothCardReaderController device is null');
      connectStatus = WorkerStatus.unboundDevice;
      worker = null;
      return;
    }
    logger.i('BluetoothCardReaderController device is not null');
    if (icReader != null) {
      icReader!.dispose();
      releaseListeners();
      await Future.delayed(const Duration(milliseconds: 500)); // 等待上一个reader释放
    }

    icReader = DeviceControllerManager(
        DeviceTypes.IC_READER, device.model, device.mac);
    logger.i(
        'BluetoothCardReaderController icReader: ${device.model}, ${device.mac} .');
    worker = icReader?.worker as ICReaderDeviceWorker;

    logger.i('BluetoothCardReaderController get worker');
    loadListeners();
    connectStatus = icReader!.connectStatus;
    update(["bluetooth_card_reader"]);
  }

  Future<void> icReaderDevice() async {
    logger.i('BluetoothCardReaderController icReaderDevice');
    await connectDevice();
  }

  void loadListeners() {
    logger.i('BluetoothCardReaderController loadListeners');
    worker?.successEvent.addListener(_onSuccess);
    worker!.connectErrorEvent.addListener(_onConnectFail);
    worker!.connectedEvent.addListener(_onConnectSuccess);
    worker!.disconnectedEvent.addListener(_onDisconnected);
    worker!.connect();
  }

  void releaseListeners() {
    worker!.successEvent.removeListener(_onSuccess);
    worker!.connectErrorEvent.removeListener(_onConnectFail);
    worker!.connectedEvent.removeListener(_onConnectSuccess);
    worker!.disconnectedEvent.removeListener(_onDisconnected);
  }

  /// 读取到数据的回调
  void onReadInfo(ICReaderExamData data) {
    final result = CardReaderResult(
      success: true,
      cardNo: data.cardNo,
      name: data.name,
      nation: data.nation,
      gender: data.gender == '男' ? GenderEnum.Male : GenderEnum.Female,
      birthday: DateTime.parse(data.birthday),
      address: data.address,
    );
    Get.back(
      result: result,
    );
  }

  void _onSuccess(_, ICReaderExamData e) {
    logger.i('读卡成功 ${e.name}');
    onReadInfo(e);
    connectStatus = WorkerStatus.connected;
    update(["bluetooth_card_reader"]);
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    logger.i('BluetoothCardReaderController 连接设备失败');
    connectStatus = WorkerStatus.connectionFailed;
    update(["bluetooth_card_reader"]);
  }

  void _onConnectSuccess(sender, e) {
    logger.i('BluetoothCardReaderController connectStatus:$connectStatus 连接成功');
    logger.i('BluetoothCardReaderController _onConnectSuccess');
    connectStatus = WorkerStatus.connected;
    update(["bluetooth_card_reader"]);
  }

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    logger.i('BluetoothCardReaderController 设备连接中断');
    connectStatus = WorkerStatus.disconnected;
    update(["bluetooth_card_reader"]);
  }

  @override
  void onReady() {
    super.onReady();

    icReaderDevice();
  }

  @override
  void onClose() {
    if (worker != null) {
      releaseListeners();
      worker!.disconnect();
      worker!.dispose();
      worker = null;
    }
    super.onClose();
  }
}
