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/check/widgets/exam_device_connect_status/connect.dart';
import 'package:vnoteapp/pages/check/widgets/exam_device_connect_status/connect_disconnected.dart';
import 'package:vnoteapp/pages/check/widgets/exam_device_connect_status/connect_fail.dart';
import 'package:vnoteapp/pages/check/widgets/exam_device_connect_status/connect_success.dart';

// ignore: must_be_immutable
class ExamBloodOxygen extends StatefulWidget {
  ExamBloodOxygen({
    super.key,
    required this.currentValue,
    required this.bloodOxygenInput,
  });
  Map<String, dynamic> currentValue;
  Function(Map<String, dynamic>) bloodOxygenInput;
  @override
  State<ExamBloodOxygen> createState() => _ExamBloodOxygenState();
}

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

  late final SpO2DeviceWorker worker = SpO2DeviceWorker(
    mac: 'A4:C1:38:0B:CC:60',
    model: 'AOJ-70B',
  );
  late String pulse = widget.currentValue['Pulse_Frequency'] ?? '0';
  late String spO2 = widget.currentValue['Spo2'] ?? '0';
  bool _connectFailStatus = false;
  bool _connectSuccessStatus = false;
  bool _isConnect = false;

  /// 设备连接中断的状态
  bool _connectDisconnectedStatus = false;
  @override
  void initState() {
    getPermission();
    worker.valueUpdateEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);

    connect();

    super.initState();
  }

  Future<void> connect() async {
    _connectFailStatus = false;
    _isConnect = true;
    _connectSuccessStatus = false;
    setState(() {});
    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();
      // connectFailState = false;
      // connectSuccessState = false;
      widget.bloodOxygenInput.call({
        'Spo2': spO2,
        'Pulse_Frequency': pulse,
      });
      widget.currentValue = {
        'Spo2': spO2,
        'Pulse_Frequency': pulse,
      };
      _isConnect = false;
      // disconnect();
    });
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    _connectFailStatus = true;
    _connectSuccessStatus = false;
    _isConnect = false;
    _connectDisconnectedStatus = false;
    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    _connectSuccessStatus = true;
    _connectFailStatus = false;
    _isConnect = false;
    _connectDisconnectedStatus = false;
    setState(() {});
  }

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    _connectDisconnectedStatus = true;
    _connectSuccessStatus = false;
    _connectFailStatus = false;
    _isConnect = false;
    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: [
            const SizedBox(
              height: 40,
            ),
            _SideBar(
              title: '血氧饱和度',
              value: spO2,
              unit: '%',
            ),
            const Divider(indent: 30),
            const SizedBox(
              height: 32,
            ),
            _SideBar(
              title: '脉率',
              value: pulse,
              unit: 'bpm',
            ),
          ],
        )),
        if (_connectFailStatus)
          DeviceConnectFail(
            connect: () => connect(),
          ),
        if (_connectSuccessStatus) const DeviceConnectSuccess(),
        if (_isConnect) const DeviceConnect(),
        if (_connectDisconnectedStatus)
          DeviceConnectDisconnected(
            connect: () => connect(),
          ),
      ],
    );
  }
}

class _SideBar extends StatelessWidget {
  final String title;
  final String value;
  final String unit;

  const _SideBar({
    required this.title,
    required this.value,
    required this.unit,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 30),
          child: Text(
            title,
            style: const TextStyle(
              fontSize: 25,
            ),
          ),
        ),
        Container(
          alignment: Alignment.bottomRight,
          padding: const EdgeInsets.only(
            bottom: 20,
            right: 30,
            left: 40,
          ),
          child: FittedBox(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                RichText(
                  text: TextSpan(
                    text: value,
                    style: const TextStyle(
                      fontSize: 80,
                      color: Colors.black,
                    ),
                    children: [
                      TextSpan(
                        text: unit,
                        style: const TextStyle(fontSize: 25),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
