import 'package:flutter/material.dart';
import 'package:get/get.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/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/widgets/device_controller.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';
import 'package:fis_common/logger/logger.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> {
  final controller = Get.find<DeviceController>();
  late WorkerStatus connectStatus = WorkerStatus.connecting;
  late String pulse = widget.currentValue['Pulse_Frequency'] ?? '0';
  late String spO2 = widget.currentValue['Spo2'] ?? '0';
  DeviceControllerManager? spo2;
  SpO2DeviceWorker? worker;
  bool isConnectFail = false;
  int errorCount = 0;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      currentDevice();
    });
  }

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

    loadListeners();
    await connect();
  }

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

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

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

  /// 尝试重连
  Future<void> tryReconnect() async {
    if (worker != null) {
      await disconnect();
      await connect();
    }
  }

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

  @override
  void dispose() {
    spo2?.dispose();
    releaseListeners();
    disconnect();
    worker?.dispose();
    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,
      };
      connectStatus = WorkerStatus.connected;
      // disconnect();
    });
  }

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

    if (errorCount < 3) {
      errorCount++;
      tryReconnect();
    } else {
      isConnectFail = true;
    }
    connectStatus = WorkerStatus.connectionFailed;

    setState(() {});
  }

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

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    logger.i("设备连接中断:${worker!.mac}");
    tryReconnect();
    errorCount = 0;
    connectStatus = WorkerStatus.disconnected;
    setState(() {});
  }

  @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 (!isConnectFail)
          DeviceStatusPosition(
            deviceStatus: DeviceStatus(connectStatus: connectStatus),
          )
        else
          _buildErrorButton(),
      ],
    );
  }

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

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),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
