import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/components/dialog_input.dart';
import 'package:vitalapp/managers/device_controller_manager.dart';
import 'package:vitalapp/pages/check/widgets/device_controller.dart';
import 'package:vitalapp/pages/mappers/urine.dart';
import 'package:vitalapp/pages/medical/controllers/urinalysis.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/check/widgets/exam_configurable/exam_card.dart';
import 'package:vitalapp/pages/medical/controller.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status.dart';
import 'package:vnote_device_plugin/devices/urine.dart';
import 'package:vnote_device_plugin/models/exams/urine.dart';

///  尿常规
class ExamUrinalysis extends StatefulWidget {
  const ExamUrinalysis({
    super.key,
    required this.currentValue,
    required this.urinalysis,
  });
  final Map currentValue;
  final Function(Map) urinalysis;

  @override
  State<ExamUrinalysis> createState() => _ExamUrinalysisState();
}

class _ExamUrinalysisState extends State<ExamUrinalysis> {
  final controller = Get.find<DeviceController>();
  late DeviceControllerManager urinaly;
  late UrineDeviceWorker worker;
  UrineExamData? urineExamData;
  String? deviceType = MedicalController.typeConvertMap[DeviceTypes.URINE];

  WorkerStatus connectStatus = WorkerStatus.connecting;

  List<Map<String, String>> urinalysis = [
    {"name": '中性粒细胞', "key": 'LEU'},
    {"name": '红细胞', "key": 'BLD'},
    {"name": '尿亚硝酸盐', "key": 'NIT'},
    {"name": '酮体', "key": 'KET'},
    {"name": '尿胆原', "key": 'UBG'},
    {"name": '胆红素', "key": 'BIL'},
    {"name": '尿蛋白', "key": 'PRO'},
    {"name": '葡萄糖', "key": 'GLU'},
    {"name": '酸碱度', "key": 'PH'},
    {"name": '尿比重', "key": 'SG'},
    {"name": '维C', "key": 'VC'},
  ];

  Map _value = {};
  @override
  void initState() {
    initTemperature();
    currentDevice();
    super.initState();
  }

  Future<void> currentDevice() async {
    DeviceModel? device = await controller.getDevice(DeviceTypes.URINE);
    if (device == null) {
      connectStatus = WorkerStatus.unboundDevice;
      return;
    }
    urinaly =
        DeviceControllerManager(DeviceTypes.URINE, device.model, device.mac);
    worker = urinaly.worker as UrineDeviceWorker;
    connectStatus = urinaly.connectStatus;
    loadListeners();
  }

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

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

  Future<void> initData() async {
    _value = widget.currentValue;
    setState(() {});
  }

  Future<void> disconnect() async {
    if (!(worker == null)) {
      await worker.disconnect();
      releaseListeners();
    }
  }

  void releaseListeners() {
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.successEvent.removeListener(_onSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
    // worker.tempTooLowEvent.removeListener(_onTempTooLowOrTooHeigh);
    // worker.tempTooHighEvent.removeListener(_onTempTooLowOrTooHeigh);
    // controller.deviceCloseSuccessEvent.removeListener(_onDeviceCloseSuccess);
  }

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

  void _onSuccess(_, UrineExamData e) {
    setState(() {
      // _value = e.toString();
      print(e);
      urineExamData = e;
      _value = UrineExamDataMapper.convertUrineExamDataToMap(urineExamData!);
      widget.urinalysis(_value);
      connectStatus = WorkerStatus.connected;
    });
  }

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

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

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

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

  Widget _buildTemperature() {
    return ExamCard(
      title: '尿常规',
      // clickCard: () {
      //   _input();
      // },
      content: Container(
        width: double.infinity,
        alignment: Alignment.center,
        padding: const EdgeInsets.only(
          bottom: 20,
          right: 30,
          left: 40,
        ),
        // constraints: const BoxConstraints(minHeight: 150),
        child: GridView.count(
          shrinkWrap: true,
          childAspectRatio: 6,
          crossAxisCount: 2, // 列数为2，即两列布局
          children: urinalysis.map((item) {
            return _buildUrineItem(item);
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildUrineItem(Map<String, String> urine) {
    return InkWell(
      onTap: () {
        _input(urine['name']!, urine['key']!);
      },
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              alignment: Alignment.center,
              width: 180,
              child: Row(
                children: [
                  Text(
                    urine['key']!,
                    style: const TextStyle(
                      fontSize: 22,
                      color: Colors.black,
                    ),
                  ),
                  Text(
                    '(${urine['name']!})',
                    // text: _value.isEmpty ? '--' : _value,
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      fontSize: 22,
                    ),
                  ),
                ],
              ),
            ),
            Text(
              _value[urine['key']!] ?? '',
              // text: _value.isEmpty ? '--' : _value,
              style: const TextStyle(
                fontSize: 40,
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _input(String name, String key) async {
    String? result = await VDialogInput(
      title: name,
      initialValue: _value[key],
    ).show();
    if (result?.isNotEmpty ?? false) {
      _value[key] = result ?? '';
    }
    widget.urinalysis(_value);
    setState(() {});
  }
}
