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/mappers/urine.dart';
import 'package:vitalapp/pages/medical/controllers/urinalysis.dart';
import 'package:vitalapp/pages/medical/widgets/device_status_position.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';
import 'package:fis_common/logger/logger.dart';

///  尿常规
class Urinalysis extends StatefulWidget {
  const Urinalysis({
    super.key,
  });

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

class _ExamUrinalysisState extends State<Urinalysis> {
  var controller = Get.find<MedicalController>();
  late DeviceControllerManager urinaly;
  late UrineDeviceWorker worker;
  UrineExamData? urineExamData;
  bool isConnectFail = false;
  int errorCount = 0;
  String? get 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() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      initUrinlysis();
      currentDevice();
      controller.changePatient.addListener(_onPatientChange);
    });

    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> initUrinlysis() async {
    await initData();
  }

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

  Future<void> initData() async {
    await controller.readCachedRecord();
    if (controller.diagnosisDataValue.isNotEmpty &&
        controller.diagnosisDataValue.containsKey(deviceType)) {
      _value = controller.diagnosisDataValue[deviceType!];
    } else {
      _value = {};
    }
    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);
  }

  @override
  void dispose() {
    controller.changePatient.removeListener(_onPatientChange);
    disconnect();
    worker.dispose();
    super.dispose();
  }

  void _onSuccess(_, UrineExamData e) {
    setState(() {
      // _value = e.toString();
      print(e);
      urineExamData = e;
      controller.diagnosisDataValue[deviceType!] =
          UrineExamDataMapper.convertUrineExamDataToMap(urineExamData!);
      _value = controller.diagnosisDataValue[deviceType!];
      controller.saveCachedRecord();
      connectStatus = WorkerStatus.connected;
    });
  }

  void _onConnectFail(sender, e) {
    print('连接设备失败');

    logger.i("设备连接失败:${worker.mac}");
    if (errorCount < 3) {
      errorCount++;
      disconnect();
      worker.connect();
    } else {
      isConnectFail = true;
    }

    connectStatus = WorkerStatus.connectionFailed;
    setState(() {});
  }

  void _onConnectSuccess(sender, e) {
    logger.i("设备连接成功:${worker.mac}");
    isConnectFail = false;
    errorCount = 0;
    connectStatus = WorkerStatus.connected;
    setState(() {});
  }

  void _onDisconnected(sender, e) {
    print('设备连接中断');
    logger.i("设备连接中断:${worker.mac}");
    if (errorCount < 3) {
      errorCount++;
      disconnect();
      worker.connect();
    } else {
      isConnectFail = true;
    }
    connectStatus = WorkerStatus.disconnected;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildTemperature(),
        if (!isConnectFail)
          DeviceStatusPosition(
            deviceStatus: DeviceStatus(connectStatus: connectStatus),
          )
        else
          _buildErrorButton(),
      ],
    );
  }

  Widget _buildErrorButton() {
    return DeviceStatusPosition(
      deviceStatus: Row(
        children: [
          const Text(
            '请确认设备是否启动',
            style: TextStyle(fontSize: 24, color: Colors.red),
          ),
          IconButton(
            onPressed: () {
              worker.connect();
              setState(() {
                connectStatus = WorkerStatus.connecting;
                isConnectFail = false;
              });
            },
            icon: const Icon(Icons.refresh),
            iconSize: 32,
          ),
        ],
      ),
    );
  }

  Widget _buildTemperature() {
    return ExamCard(
      title: '尿常规',
      // clickCard: () {
      //   _inputTemperature();
      // },
      content: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.only(
          bottom: 20,
          right: 30,
          left: 40,
        ),
        constraints: const BoxConstraints(minHeight: 150),
        child: GridView.count(
          shrinkWrap: true,
          childAspectRatio: 4,
          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: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            alignment: Alignment.centerLeft,
            width: 100,
            height: 55,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              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: 16,
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 65,
            width: 160,
            alignment: Alignment.centerLeft,
            child: Text(
              _value[urine['key']!] ?? '',
              // text: _value.isEmpty ? '--' : _value,
              maxLines: 2,
              style: const TextStyle(
                fontSize: 30,
              ),
            ),
          )
        ],
      ),
    );
  }

  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 ?? '';
    }
    controller.diagnosisDataValue[deviceType!] = _value;
    controller.saveCachedRecord();
    // widget.urinalysis(_value);
    setState(() {});
  }

  void _onPatientChange(Object sender, String e) {
    setState(() {
      _value = {};
      controller.diagnosisDataValue[deviceType!] = {};
    });
  }
}
