import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/sp_o2.dart';
import 'package:vnote_device_plugin/models/exams/sp_o2.dart';
import 'package:vnoteapp/managers/interfaces/permission.dart';
import 'package:vnoteapp/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vnoteapp/pages/medical/controller.dart';
import 'package:vnoteapp/pages/medical/models/worker.dart';
import 'package:vnoteapp/pages/medical/widgets/device_status.dart';
import 'package:vnoteapp/pages/medical/widgets/side_bar.dart';

class BloodOxygen extends StatefulWidget {
  const BloodOxygen({
    super.key,
  });

  @override
  State<BloodOxygen> createState() => _ExamBloodOxygenState();
}

class _ExamBloodOxygenState extends State<BloodOxygen> {
  var permissionManager = Get.find<IPermissionManager>();
  var controller = Get.find<MedicalController>();

  late final SpO2DeviceWorker worker = SpO2DeviceWorker(
    mac: 'A4:C1:38:0B:CC:60',
    model: 'AOJ-70B',
  );

  late String pulse =
      controller.diagnosisDataValue['SpO2']?['Pulse_Frequency'] ?? '0';
  late String spO2 = controller.diagnosisDataValue['SpO2']?['Spo2'] ?? '0';
  WorkerStatus _connectStatus = WorkerStatus.connecting;

  @override
  void initState() {
    initOxygen();

    super.initState();
  }

  void workerAddListener() {
    worker.valueUpdateEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
  }

  Future<void> initOxygen() async {
    getPermission();
    workerAddListener();
    await connect();
    await initData();
  }

  Future<void> initData() async {
    await controller.readCachedRecord();
    pulse = controller.diagnosisDataValue['SpO2']?['Pulse_Frequency'];
    spO2 = controller.diagnosisDataValue['SpO2']?['Spo2'];
    setState(() {});
  }

  Future<void> connect() async {
    await worker.connect();
  }

  Future<void> disconnect() async {
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.valueUpdateEvent.removeListener(_onSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
    await worker.disconnect();
  }

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

  void _onSuccess(_, SpO2ExamValue e) {
    setState(() {
      pulse = e.pulse.toString();
      spO2 = e.spO2.toString();
      controller.diagnosisDataValue['SpO2'] = {
        'Pulse_Frequency': pulse,
        'Spo2': spO2
      };
      _connectStatus = WorkerStatus.connected;
    });
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    _connectStatus = WorkerStatus.connectionFailed;
    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    _connectStatus = WorkerStatus.connected;
    setState(() {});
  }

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    _connectStatus = WorkerStatus.disconnected;
    setState(() {});
  }

  Future<void> getPermission() async {
    await permissionManager.requestLocationPermission();
    await permissionManager.requestBluetoothConnectPermission();
    await permissionManager.requestBluetoothAdvertisePermission();
    await permissionManager.requestBluetoothScanPermission();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ExamCard(
            // clickCard: () {},
            content: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SideBar(
              title: '血氧饱和度',
              value: spO2,
              unit: '%',
            ),
            const Divider(indent: 30),
            SideBar(
              title: '脉率',
              value: pulse,
              unit: 'bpm',
            ),
          ],
        )),
        DeviceStatus(connectStatus: _connectStatus),
      ],
    );
  }
}
