import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/devices/weight.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';
import 'package:vnoteapp/pages/medical/widgets/side_bar.dart';

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

  @override
  State<BodyWeight> createState() => _ExamBodyWeightState();
}

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

  late final WeightDeviceWorker worker = WeightDeviceWorker(
    mac: 'CF:E4:2C:22:01:39',
    model: 'CF398BLE',
  );

  WorkerStatus _connectStatus = WorkerStatus.connecting;

  late String _weight = controller.diagnosisDataValue['BMI']?['Weight'] ?? '';
  late String _height = controller.diagnosisDataValue['BMI']?['Height'] ?? '';
  late String _bmi = controller.diagnosisDataValue['BMI']?['Bmi'] ?? '';

  @override
  void initState() {
    initBmi();
    super.initState();
  }

  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 workerAddListener() {
    worker.successEvent.addListener(_onSuccess);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);
  }

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

  Future<void> initData() async {
    await controller.readCachedRecord();
    if (controller.diagnosisDataValue['BMI'] == null) {
      controller.diagnosisDataValue['BMI'] = {};
    }
    _weight = controller.diagnosisDataValue['BMI']?['Weight'] ?? '';
    _height = controller.diagnosisDataValue['BMI']?['Height'] ?? '';
    _bmi = controller.diagnosisDataValue['BMI']?['Bmi'] ?? '';
    setState(() {});
  }

  void _onSuccess(_, double e) {
    setState(() {
      _weight = e.toString();
      _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 ExamCard(
        titleText: const SizedBox(),
        // clickCard: () {},
        content: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SideBar(
              title: '身高',
              value: _height,
              unit: 'cm',
              onTap: _inputHeight,
            ),
            const Divider(indent: 30),
            Stack(
              children: [
                SideBar(
                  title: '体重',
                  value: _weight,
                  hasDevice: true,
                  unit: 'kg',
                  onTap: _inputWeight,
                ),
                DeviceStatus(connectStatus: _connectStatus),
              ],
            ),
            const Divider(indent: 30),
            SideBar(
              title: 'BMI',
              value: _bmi,
              unit: 'kg/m²',
            ),
          ],
        ));
  }

  Future<void> _inputWeight() async {
    String? result = await VDialogNumber(
      title: '体重',
      initialValue: _weight,
    ).show();
    if (result?.isNotEmpty ?? false) {
      _weight = result ?? '';
      getBmi();
      controller.diagnosisDataValue['BMI']?['Weight'] = _weight;
      controller.diagnosisDataValue['BMI']?['Bmi'] = _bmi;
    }
    setState(() {});
  }

  void getBmi() {
    if (_weight.isNotEmpty && _height.isNotEmpty) {
      _bmi = (double.parse(_weight) /
              ((double.parse(_height) / 100) * (double.parse(_height) / 100)))
          .toStringAsFixed(2);
    }
  }

  Future<void> _inputHeight() async {
    String? result = await VDialogNumber(
      title: '身高',
      initialValue: _height,
    ).show();
    if (result?.isNotEmpty ?? false) {
      _height = result ?? '';

      getBmi();
      controller.diagnosisDataValue['BMI']?['Height'] = _height;
      controller.diagnosisDataValue['BMI']?['Bmi'] = _bmi;
    }
    setState(() {});
  }
}
