import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/sp_o2.dart';
import 'package:vnote_device_plugin/models/exams/sp_o2.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/controllers/oxygen.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';
import 'package:vitalapp/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 controller = Get.find<MedicalController>();
  late SpO2DeviceController spo2;

  late SpO2DeviceWorker worker;

  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 loadListeners() {
    worker.valueUpdateEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.connect();
  }

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

  Future<void> initOxygen() async {
    currentDevice();

    await initData();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.SPO2);
    if (device.isNull) {
      _connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    spo2 = SpO2DeviceController(device?.model ?? '', device?.mac ?? '');
    worker = spo2.worker;
    _connectStatus = spo2.connectStatus;

    loadListeners();
  }

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

  Future<void> disconnect() async {
    if (!worker.isNull) {
      await worker.disconnect();
      releaseListeners();
    }
  }

  @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(() {});
  }

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