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/widgets/exam_configurable/exam_card.dart';
import 'package:vnoteapp/pages/medical/controller.dart';
import 'package:vnoteapp/pages/medical/models/worker.dart';
import 'package:vnoteapp/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 permissionManager = Get.find<IPermissionManager>();
  var controller = Get.find<MedicalController>();

  late final TempDeviceWorker worker = TempDeviceWorker(
    mac: 'D0:05:00:00:00:67',
    model: 'YHW-6',
  );
  WorkerStatus _connectStatus = WorkerStatus.connecting;

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

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

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

  Future<void> connect() async {
    await 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(() {
      _value = e.toString();
      controller.diagnosisDataValue['Temp'] = {'Temperature': _value};
      _connectStatus = WorkerStatus.connected;
    });
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');
    _connectStatus = WorkerStatus.connectionFailed;
    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;
    connect();
    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(),
        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(
                text: TextSpan(
                  text: _value,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: const [
                    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 ?? '';
    }
  }
}
