import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/sugar.dart';
import 'package:vnote_device_plugin/models/exams/sugar.dart';
import 'package:vnoteapp/managers/interfaces/permission.dart';
import 'package:vnoteapp/pages/check/widgets/exam_configurable/exam_card.dart';

import 'package:vnoteapp/components/dialog_number.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';

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

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

class _ExamBloodSugarState extends State<BloodSugar> {
  var permissionManager = Get.find<IPermissionManager>();
  var controller = Get.find<MedicalController>();

  late final SugarDeviceWorker worker = SugarDeviceWorker(
    mac: '60:98:66:C4:0E:51',
    model: 'i-sens630',
  );
  WorkerStatus _connectStatus = WorkerStatus.connecting;

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

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

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

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

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

  Future<void> getPermission() async {
    await permissionManager.requestLocationPermission();
    await permissionManager.requestBluetoothConnectPermission();
    await permissionManager.requestBluetoothAdvertisePermission();
    await permissionManager.requestBluetoothScanPermission();
  }

  @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,
                  style: const TextStyle(
                    fontSize: 80,
                    color: Colors.black,
                  ),
                  children: const [
                    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 ?? '';
    }
  }
}
