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/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/controllers/temp.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.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 TempDeviceController temp;

  late TempDeviceWorker worker;

  WorkerStatus connectStatus = WorkerStatus.connecting;

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

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

    loadListeners();
  }

  Future<void> initTemperature() async {
    await initData();
  }

  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> initData() async {
    await controller.readCachedRecord();
    _value = controller.diagnosisDataValue['Temp']?['Temperature'] ?? '';
    setState(() {});
  }

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

  void releaseListeners() {
    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);
  }

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

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

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

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

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

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

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

  Widget _buildTemperature() {
    return ExamCard(
      title: '体温',
      // 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(
                textAlign: TextAlign.end,
                text: TextSpan(
                  text: _value.isEmpty ? '--' : _value,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: const [
                    TextSpan(text: ' '),
                    TextSpan(
                      text: '°C',
                      style: TextStyle(fontSize: 25),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _inputTemperature() async {
    String? result = await VDialogNumber(
      title: '体温',
      initialValue: _value,
    ).show();
    if (result?.isNotEmpty ?? false) {
      _value = result ?? '';
    }
  }
}
