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/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/controller.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';

class BodyTemperature extends StatefulWidget {
  const BodyTemperature({
    super.key,
  });

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

class _ExamBodyTemperatureState extends State<BodyTemperature> {
  var controller = Get.find<MedicalController>();
  late DeviceControllerManager temp;

  TempDeviceWorker? worker;

  WorkerStatus connectStatus = WorkerStatus.connecting;
  bool isConnectFail = false;
  int errorCount = 0;

  ///重试机制

  late String _value =
      controller.diagnosisDataValue['Temp']?['Temperature'] ?? '';
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(
      (timeStamp) {
        initTemperature();
        currentDevice();
      },
    );

    super.initState();
  }

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

    loadListeners();
    connect();
  }

  Future<void> initTemperature() async {
    _value = controller.diagnosisDataValue['Temp']?['Temperature'] ?? '';
    logger.i('_ExamBloodSugarState initData Temperature:$_value');
    setState(() {});
  }

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

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

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

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

    // controller.deviceCloseSuccessEvent.removeListener(_onDeviceCloseSuccess);
  }

  /// 尝试重连
  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(() {
      _value = e.toString();
      controller.diagnosisDataValue['Temp'] = {'Temperature': _value};
      controller.saveCachedRecord();
      connectStatus = WorkerStatus.connected;
    });
  }

  void _onTempTooLowOrTooHeigh(sender, e) {
    _value = e.toString();
    controller.diagnosisDataValue['Temp'] = {'Temperature': _value};
    controller.saveCachedRecord();
    connectStatus = WorkerStatus.connected;
    setState(() {});
  }

  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 _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: '',
      clickCard: () {
        _inputTemperature();
      },
      content: Row(
        children: [
          const SizedBox(
            width: 25,
          ),
          const Text(
            '体温',
            style: TextStyle(fontSize: 25),
          ),
          const Expanded(child: SizedBox()),
          Container(
            alignment: Alignment.bottomRight,
            height: 100,
            child: FittedBox(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    _value.isEmpty ? '--' : _value,
                    style: const TextStyle(
                      fontSize: 80,
                      color: Colors.black,
                    ),
                  ),
                  const Text(
                    '   °C',
                    style: TextStyle(fontSize: 25),
                  ),
                  const SizedBox(
                    width: 30,
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _inputTemperature() async {
    String? result = await VDialogNumber(
      title: '体温',
      initialValue: _value,
    ).show();
    if (result?.isNotEmpty ?? false) {
      _value = result ?? '';
      controller.diagnosisDataValue['Temp'] = {'Temperature': _value};
      controller.saveCachedRecord();
    }
    setState(() {});
  }
}
