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/temp.dart';
import 'package:vitalapp/components/dialog_number.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/models/form.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 ExamBodyTemperature extends StatefulWidget {
  ExamBodyTemperature({
    super.key,
    required this.currentFormObject,
    required this.currentInputValue,
    this.bodyTemperatureInput,
  });
  FormObject currentFormObject;
  String currentInputValue;
  Function(String value)? bodyTemperatureInput;

  @override
  State<ExamBodyTemperature> createState() => _ExamBodyTemperatureState();
}

class _ExamBodyTemperatureState extends State<ExamBodyTemperature> {
  final controller = Get.find<DeviceController>();
  late DeviceControllerManager temp;
  TempDeviceWorker? worker;
  WorkerStatus? connectStatus;
  bool isConnectFail = false;
  int errorCount = 0;

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.TEMP);

    if (device == null) {
      connectStatus = WorkerStatus.unboundDevice;
      worker = null;
      setState(() {});
      return;
    }
    temp = DeviceControllerManager(DeviceTypes.TEMP, device.model, device.mac);
    worker = temp.worker as TempDeviceWorker;
    connectStatus = WorkerStatus.connecting;
    setState(() {});
    loadListeners();
    connect();
  }

  @override
  void initState() {
    currentDevice();

    super.initState();
  }

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

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

  void loadListeners() {
    worker!.successEvent.addListener(_onSuccess);
    worker!.connectErrorEvent.addListener(_onConnectFail);
    worker!.connectedEvent.addListener(_onConnectSuccess);
    worker!.disconnectedEvent.addListener(_onDisconnected);
    worker!.tempTooLowEvent.addListener(_onTempTooLowOrTooHeigh);
    worker!.tempTooHighEvent.addListener(_onTempTooLowOrTooHeigh);
  }

  void releaseListeners() {
    if (worker != null) {
      worker!.connectErrorEvent.removeListener(_onConnectFail);
      worker!.connectedEvent.removeListener(_onConnectSuccess);
      worker!.successEvent.removeListener(_onSuccess);
      worker!.disconnectedEvent.removeListener(_onDisconnected);
      worker!.tempTooLowEvent.removeListener(_onTempTooLowOrTooHeigh);
      worker!.tempTooHighEvent.removeListener(_onTempTooLowOrTooHeigh);
    }
  }

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

  @override
  void dispose() {
    if (worker != null) {
      temp.dispose();
    }
    releaseListeners();
    disconnect();
    worker?.dispose();
    super.dispose();
  }

  void _onSuccess(_, double e) {
    setState(() {
      widget.currentInputValue = e.toString();
      widget.bodyTemperatureInput!.call(widget.currentInputValue);
      connectStatus = WorkerStatus.connected;
    });
  }

  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) {
    logger.i("设备连接成功:${worker!.mac}");
    connectStatus = WorkerStatus.connected;
    errorCount = 0;
    isConnectFail = false;
    setState(() {});
  }

  void _onTempTooLowOrTooHeigh(sender, e) {
    widget.currentInputValue = e.toString();
    widget.bodyTemperatureInput!.call(widget.currentInputValue);
    connectStatus = WorkerStatus.connected;
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildTemperature(),
        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,
          ),
        ],
      ),
    );
  }

  Widget _buildTemperature() {
    return ExamCard(
      title: widget.currentFormObject.label ?? '',
      clickCard: () {
        _inputTemperature();
      },
      content: Container(
        alignment: Alignment.bottomRight,
        padding: const EdgeInsets.only(
          bottom: 20,
          right: 30,
          left: 40,
        ),
        constraints: const BoxConstraints(minHeight: 150),
        child: FittedBox(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              RichText(
                text: TextSpan(
                  text: widget.currentInputValue,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: [
                    TextSpan(
                      text: widget.currentFormObject.append ?? '',
                      style: const TextStyle(fontSize: 25),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _inputTemperature() async {
    String? result = await VDialogNumber(
      title: widget.currentFormObject.label,
      initialValue: widget.currentInputValue,
    ).show();
    if (result?.isNotEmpty ?? false) {
      widget.currentInputValue = result ?? '';
      widget.bodyTemperatureInput!.call(widget.currentInputValue);
    }
  }
}
