import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/components/dialog_number.dart';
import 'package:vitalapp/managers/device_controller_manager.dart';
import 'package:vitalapp/pages/medical/widgets/device_status_position.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/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';
import 'package:fis_common/logger/logger.dart';

class BloodOxygen extends StatefulWidget {
  const BloodOxygen({Key? key}) : super(key: key);

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

class _ExamBloodOxygenState extends State<BloodOxygen> {
  final controller = Get.find<MedicalController>();
  late DeviceControllerManager spo2;
  SpO2DeviceWorker? worker;
  String pulse = '';
  String spO2 = '';
  bool isConnectFail = false;
  int errorCount = 0;
  WorkerStatus _connectStatus = WorkerStatus.connecting;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      initOxygen();
    });
  }

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

  Future<void> initOxygen() async {
    await currentDevice();
    await initData();
  }

  Future<void> currentDevice() async {
    final device = await controller.getDevice(DeviceTypes.SPO2);
    if (device == null) {
      _connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      worker = null;
      return;
    }
    spo2 = DeviceControllerManager(DeviceTypes.SPO2, device.model, device.mac);
    worker = spo2.worker as SpO2DeviceWorker;
    _connectStatus = spo2.connectStatus;
    loadListeners();
  }

  Future<void> initData() async {
    await controller.readCachedRecord();

    setState(() {
      pulse = controller.diagnosisDataValue['SpO2']?['Pulse_Frequency'] ?? '';
      spO2 = controller.diagnosisDataValue['SpO2']?['Spo2'] ?? '';
    });
  }

  void loadListeners() {
    worker!.valueUpdateEvent.addListener(_onSuccess);
    worker!.connectErrorEvent.addListener(_onConnectFail);
    worker!.connectedEvent.addListener(_onConnectSuccess);
    worker!.disconnectedEvent.addListener(_onDisconnected);
    worker!.connect();
  }

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

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

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

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    logger.i("连接设备失败:${worker!.mac}");

    if (errorCount < 3) {
      errorCount++;
      disconnect();
      loadListeners();
    } else {
      isConnectFail = true;
    }
    _connectStatus = WorkerStatus.connectionFailed;

    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    logger.i("设备连接成功:${worker!.mac}");
    _connectStatus = WorkerStatus.connected;
    errorCount = 0;
    isConnectFail = false;
    setState(() {});
  }

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    logger.i("设备连接中断:${worker!.mac}");
    if (errorCount < 3) {
      errorCount++;
      disconnect();
      loadListeners();
    } else {
      isConnectFail = true;
    }
    _connectStatus = WorkerStatus.disconnected;
    setState(() {});
  }

  Future<void> _inputOxygen(String title) async {
    final result = await VDialogNumber(
      title: title,
      initialValue: spO2,
    ).show();
    if (result?.isNotEmpty ?? false) {
      spO2 = result ?? '';
      controller.diagnosisDataValue['SpO2'] = {
        'Pulse_Frequency': pulse,
        'Spo2': spO2
      };
      controller.saveCachedRecord();
    }

    setState(() {});
  }

  Future<void> _inputOxygen1(String title) async {
    final result = await VDialogNumber(
      title: title,
      initialValue: pulse,
    ).show();
    if (result?.isNotEmpty ?? false) {
      pulse = result ?? '';
    }
    controller.diagnosisDataValue['SpO2'] = {
      'Pulse_Frequency': pulse,
      'Spo2': spO2
    };
    controller.saveCachedRecord();
    setState(() {});
  }

  /// 需要封装一下
  Widget _buildErrorButton() {
    return DeviceStatusPosition(
      deviceStatus: Row(
        children: [
          const Text(
            '请确认设备是否启动',
            style: TextStyle(fontSize: 24, color: Colors.red),
          ),
          IconButton(
            onPressed: () {
              worker?.connect();
              setState(() {
                _connectStatus = WorkerStatus.connecting;
                isConnectFail = false;
              });
            },
            icon: const Icon(Icons.refresh),
            iconSize: 32,
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        ExamCard(
          content: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SideBar(
                title: '血氧饱和度',
                value: spO2 == '0' ? '--' : spO2,
                unit: '%',
                onTap: () async {
                  await _inputOxygen('血氧饱和度');
                },
              ),
              const Divider(indent: 30),
              SideBar(
                title: '脉率',
                value: pulse == '0' ? '--' : pulse,
                unit: 'bpm',
                onTap: () async {
                  await _inputOxygen1('脉率');
                },
              ),
            ],
          ),
        ),
        if (!isConnectFail)
          DeviceStatusPosition(
            deviceStatus: DeviceStatus(connectStatus: _connectStatus),
          )
        else
          _buildErrorButton(),
      ],
    );
  }
}
