import 'package:flutter/material.dart';
import 'package:get/get.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/managers/interfaces/permission.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';

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

/// TODO 先完成配置设备的替换 还需要优化
class _ExamBodyTemperatureState extends State<ExamBodyTemperature> {
  var permissionManager = Get.find<IPermissionManager>();
  final controller = Get.find<DeviceController>();
  WorkerStatus connectStatus = WorkerStatus.connecting;
  bool isAccessTypeAuth = false;
  late TempDeviceWorker worker;

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.TEMP);
    isAccessTypeAuth = await controller.isAccessTypeAuth(DeviceTypes.TEMP);
    if (device.isNull) {
      connectStatus = WorkerStatus.unboundDevice;
      return;
    }
    worker = TempDeviceWorker(
      model: device?.model ?? '',
      mac: device?.mac ?? '',
    );
    loadListeners();
  }

  @override
  void initState() {
    currentDevice();

    super.initState();
  }

  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);
    worker.connect();
  }

  Future<void> disconnect() async {
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.successEvent.removeListener(_onSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
    worker.tempTooLowEvent.removeListener(_onTempTooLowOrTooHeigh);
    worker.tempTooHighEvent.removeListener(_onTempTooLowOrTooHeigh);
    await worker.disconnect();
  }

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

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

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    connectStatus = WorkerStatus.connectionFailed;
    worker.connect();
    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    connectStatus = WorkerStatus.connected;
    setState(() {});
  }

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

  void _onDisconnected(sender, e) {
    connectStatus = WorkerStatus.disconnected;
    worker.connect();
    print('设备连接中断');
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildTemperature(),
        if (isAccessTypeAuth) DeviceStatus(connectStatus: connectStatus),
      ],
    );
  }

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