import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vnote_device_plugin/devices/weight.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/bmi.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';
import 'package:vitalapp/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 controller = Get.find<MedicalController>();
  late BmiDeviceController bmi;
  late WeightDeviceWorker worker;

  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 {
    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 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.WEIGHT);
    if (device.isNull) {
      _connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    bmi = BmiDeviceController(device?.model ?? '', device?.mac ?? '');
    worker = bmi.worker;
    _connectStatus = bmi.connectStatus;

    loadListeners();
  }

  Future<void> initBmi() async {
    currentDevice();
    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 _onDeviceCloseSuccess(sender, e) {
    if (e) {
      connect();
    }
  }

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