import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/temp.dart';
import 'package:vnoteapp/components/dialog_number.dart';
import 'package:vnoteapp/managers/interfaces/permission.dart';
import 'package:vnoteapp/pages/check/models/form.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 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> {
  var permissionManager = Get.find<IPermissionManager>();
  late final TempDeviceWorker worker = TempDeviceWorker(
    mac: 'D0:05:00:00:00:67',
    model: 'YHW-6',
  );

  /// 设备连接失败的状态
  bool _connectFailStatus = false;

  /// 设备连接中断的状态
  bool _connectDisconnectedStatus = false;

  /// 设备连接成功的状态
  bool _connectSuccessStatus = false;

  /// 设备是否连接中
  bool _isConnect = false;
  @override
  void initState() {
    getPermission();
    worker.successEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);

    connect();
    super.initState();
  }

  Future<void> connect() async {
    _connectFailStatus = false;
    _isConnect = true;
    _connectSuccessStatus = false;
    _connectDisconnectedStatus = false;
    setState(() {});
    await worker.connect();
  }

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

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

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

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

  void _onConnectSuccess(sender, e) {
    _connectSuccessStatus = true;
    _isConnect = false;
    _connectFailStatus = 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: [
        _buildTemperature(),
        if (_connectFailStatus)
          DeviceConnectFail(
            connect: () => connect(),
          ),
        if (_connectSuccessStatus) const DeviceConnectSuccess(),
        if (_isConnect) const DeviceConnect(),
        if (_connectDisconnectedStatus)
          DeviceConnectDisconnected(
            connect: () => connect(),
          ),
      ],
    );
  }

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