import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/sugar.dart';
import 'package:vnote_device_plugin/models/exams/sugar.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';

import 'package:vitalapp/components/dialog_number.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/controllers/sugar.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';

// ignore: must_be_immutable
class BloodSugar extends StatefulWidget {
  const BloodSugar({
    super.key,
  });

  @override
  State<BloodSugar> createState() => _ExamBloodSugarState();
}

class _ExamBloodSugarState extends State<BloodSugar> {
  var controller = Get.find<MedicalController>();
  late SugarDeviceController sugar;
  late SugarDeviceWorker worker;
  WorkerStatus _connectStatus = WorkerStatus.connecting;

  late String _value = controller.diagnosisDataValue['GLU']?['sugar'] ?? '';
  @override
  void initState() {
    initSugar();
    super.initState();
  }

  void loadListeners() {
    worker.successEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);
    worker.connect();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.SUGAR);
    if (device.isNull) {
      _connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    sugar = SugarDeviceController(device?.model ?? '', device?.mac ?? '');
    worker = sugar.worker;
    _connectStatus = sugar.connectStatus;

    loadListeners();
  }

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

  Future<void> initData() async {
    await controller.readCachedRecord();
    _value = controller.diagnosisDataValue['GLU']?['sugar'] ?? '';
    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);
  }

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

  void _onSuccess(_, SugarExamData e) {
    setState(() {
      _value = e.sugar.toString();
      controller.diagnosisDataValue['GLU'] = {'sugar': _value};
      _connectStatus = WorkerStatus.connected;
    });
  }

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

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

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

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

  Widget _buildSugar() {
    return ExamCard(
      title: '血糖',
      // clickCard: () {
      //   _inputSugar();
      // },
      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.isEmpty ? '--' : _value,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: const [
                    TextSpan(text: ' '),
                    TextSpan(
                      text: 'mmol/L',
                      style: TextStyle(fontSize: 25),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

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