import 'dart:async';
import 'dart:convert';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/components/button.dart';
import 'package:vitalapp/global.dart';
import 'package:vitalapp/managers/device_controller_manager.dart';
import 'package:vitalapp/managers/interfaces/data_convert.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/twelve_ecg.dart';
import 'package:vitalapp/pages/medical/models/worker.dart';
import 'package:vitalapp/pages/medical/widgets/device_status_position.dart';
import 'package:vitalapp/pages/medical/widgets/twelve_ecg_view/controller.dart';
import 'package:vitalapp/pages/medical/widgets/twelve_ecg_view/view.dart';
import 'package:vitalapp/pages/medical/widgets/twelve_ecg_view/widgets/conclusion_dialog.dart';
import 'package:vitalapp/pages/medical/widgets/twelve_ecg_view/widgets/count_down_page.dart';
import 'package:vitalapp/pages/medical/widgets/twelve_ecg_view/widgets/ecg_device_status.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:http/http.dart' as http;
import 'package:vnote_device_plugin/devices/twelve_heart.dart';
import 'package:vnote_device_plugin/models/exams/twelve_heart.dart';

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

  @override
  State<TwelveHeartRate> createState() => _HeartRateState();
}

class _HeartRateState extends State<TwelveHeartRate> {
  final MedicalController medicalController = Get.find<MedicalController>();
  final IDataConvertManager dataConvertManager =
      Get.find<IDataConvertManager>();
  late DeviceControllerManager twelveHeart;
  late TwelveHeartDeviceWorker worker;
  WorkerStatus connectStatus = WorkerStatus.connecting;
  TwelveEcgStatus twelveEcgStatus = TwelveEcgStatus.noSampling;
  List<int> ecgPoint = [];
  int errorCount = 0;
  bool isConnectFail = false;
  late String _heart = medicalController.diagnosisDataValue['TwelveHeart']
              ?['HEART12']
          ?.toString() ??
      '';
  late String _assess =
      medicalController.diagnosisDataValue['TwelveHeart']?['ASSESS12'] ?? '';

  late String _analyse12 =
      medicalController.diagnosisDataValue['TwelveHeart']?['Analyse12'] ?? '';

  /// 初始时的心电初始数据
  List<int>? initEcgData;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _buildEcgView(),
        DeviceStatusPosition(
          currentTop: 24,
          deviceStatus: EcgDeviceStatus(
            connectStatus: connectStatus,
          ),
        ),
        if (twelveEcgStatus == TwelveEcgStatus.unstableSampling)
          _buildUnstableSampling(),
        if (twelveEcgStatus == TwelveEcgStatus.stableSampling)
          _buildCountdownPage(),
        _buildOperateButton(),
        if (_assess.isNotEmpty)
          const Positioned(
            left: 16,
            bottom: 10,
            child: Text(
              "轻触屏幕查看心电图",
              style: TextStyle(
                fontSize: 24,
                color: Colors.black,
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildEcgView() {
    return ExamCard(
      titleText: const SizedBox(),
      content: SizedBox(
        height: 620,
        // margin: const EdgeInsets.only(bottom: 10),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                const Expanded(child: SizedBox()),
                const Text(
                  "心率",
                  style: TextStyle(
                    fontSize: 24,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Text(
                  _heart.isEmpty ? '--' : _heart,
                  style: const TextStyle(
                    fontSize: 60,
                    color: Colors.black,
                  ),
                ),
                const Text(
                  "  bpm",
                  style: TextStyle(fontSize: 25),
                ),
                const SizedBox(
                  width: 250,
                )
              ],
            ),
            Expanded(
              child: ListView(
                shrinkWrap: true,
                children: [
                  SizedBox(
                    height: 520,
                    child: LayoutBuilder(builder: (context, constraints) {
                      if (initEcgData == null) {
                        return Container();
                      } else {
                        return TwelveEcgView(
                          width: constraints.maxWidth,
                          height: constraints.maxHeight,
                          initData: initEcgData!,
                          currentIndex: 0,
                          isConclusion: _assess.isNotEmpty,
                        );
                      }
                    }),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUnstableSampling() {
    return const Positioned(
      left: 20,
      top: 24,
      child: Text(
        '波形正在稳定中',
        style: TextStyle(fontSize: 24, color: Colors.blue),
      ),
    );
  }

  Widget _buildCountdownPage() {
    return Positioned(
      left: 20,
      top: 24,
      child: Row(
        children: const [
          CountdownPage(
            seconds: 30,
          ),
        ],
      ),
    );
  }

  Widget _buildOperateButton() {
    return Positioned(
      left: 24,
      top: 24,
      child: Row(
        children: [
          if (twelveEcgStatus == TwelveEcgStatus.noSampling &&
              (connectStatus == WorkerStatus.connectionFailed ||
                  connectStatus == WorkerStatus.disconnected ||
                  connectStatus == WorkerStatus.boundDeviceFail)) ...[
            SizedBox(
              width: 150,
              height: 50,
              child: VButton(
                onTap: () =>
                    connectStatus == WorkerStatus.connecting ? null : connect(),
                child: const Center(
                  child: Text(
                    "采样",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
          ],
          if (_assess.isNotEmpty)
            SizedBox(
              width: 150,
              height: 50,
              child: VButton(
                onTap: () => _openConclusion(),
                child: const Center(
                  child: Text(
                    "查看结果",
                    style: TextStyle(fontSize: 24),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 设备初始化
  Future<void> initDevice() async {
    DeviceModel? device =
        await medicalController.getDevice(DeviceTypes.TWELVEHEART);
    if (device == null) {
      connectStatus = WorkerStatus.unboundDevice;
      setState(() {});
      return;
    }
    twelveHeart = DeviceControllerManager(
        DeviceTypes.TWELVEHEART, device.model, device.mac);
    worker = twelveHeart.worker as TwelveHeartDeviceWorker;
    connectStatus = WorkerStatus.disconnected;

    loadListeners();
  }

  /// 尝试重连
  Future<void> tryReconnect() async {
    await disconnect();
    await connect();
    setState(() {
      connectStatus = WorkerStatus.connecting;
      isConnectFail = false;
    });
  }

  Future<void> disconnect() async {
    await worker.disconnect();
  }

  Future<void> connect() async {
    connectStatus = WorkerStatus.connecting;
    isConnectFail = false;
    await worker.connect();
    setState(() {});
  }

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

  /// 重置数据以及心电图
  void resetEcgView() {
    try {
      TwelveEcgViewController ecgViewController =
          Get.find<TwelveEcgViewController>();
      ecgViewController.isInitPoints = false;
      ecgViewController.allPoints = [];
      ecgViewController.reset();
    } catch (e) {
      logger.i('心率图测量失败：$e');
    }
  }

  /// 数据初始化
  Future<void> initData() async {
    if (medicalController.diagnosisDataValue['TwelveHeart'] == null) {
      medicalController.diagnosisDataValue['TwelveHeart'] = {};
    }
    if (medicalController.diagnosisDataValue['TwelveHeart']?['ECG_POINT12'] !=
            null &&
        medicalController.diagnosisDataValue['TwelveHeart']?['ECG_POINT12'] !=
            "[]") {
      String pointInfo = medicalController.diagnosisDataValue['TwelveHeart']
              ?['ECG_POINT12'] ??
          '';
      if ((pointInfo.toString().startsWith('https://') ||
              pointInfo.toString().startsWith('http://')) &&
          kIsOnline) {
        final response = await http.get(Uri.parse(pointInfo));
        pointInfo = response.body;
      }
      initEcgData = jsonDecode(pointInfo).cast<int>();
    } else {
      initEcgData = [];
    }

    setState(() {});
  }

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

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

  void loadListeners() {
    worker.boundingEvent.addListener(_onBounding);
    worker.boundSuccessEvent.addListener(_onBoundSuccess);
    worker.boundFailEvent.addListener(_onBoundFail);
    worker.connectErrorEvent.addListener(_onConnectFail);
    worker.connectedEvent.addListener(_onConnectSuccess);
    worker.disconnectedEvent.addListener(_onDisconnected);
    worker.resultReceivedEvent.addListener(_onHrValueUpdate);
    worker.ecgStableEvent.addListener(_onEcgStable);
    worker.ecgConclusionEvent.addListener(_onConclusion);
    worker.startSaveSuccessEvent.addListener(_onSaveSuccess);
  }

  void releaseListeners() {
    worker.boundingEvent.removeListener(_onBounding);
    worker.boundSuccessEvent.removeListener(_onBoundSuccess);
    worker.boundFailEvent.removeListener(_onBoundFail);
    worker.connectErrorEvent.removeListener(_onConnectFail);
    worker.connectedEvent.removeListener(_onConnectSuccess);
    worker.disconnectedEvent.removeListener(_onDisconnected);
    worker.resultReceivedEvent.removeListener(_onHrValueUpdate);
    worker.ecgStableEvent.removeListener(_onEcgStable);
    worker.ecgConclusionEvent.removeListener(_onConclusion);
    worker.startSaveSuccessEvent.removeListener(_onSaveSuccess);
  }

  /// 设置最终数据
  Future<void> setEcgData() async {
    TwelveEcgViewController ecgViewController =
        Get.find<TwelveEcgViewController>();
    ecgViewController.isPaused = true;
    medicalController.diagnosisDataValue['TwelveHeart']?['ECG12'] =
        await ecgViewController.getFullDataImageBase64();
    medicalController.diagnosisDataValue['TwelveHeart']?['ECG_POINT12'] =
        jsonEncode(ecgViewController.allPoints);
    ecgViewController.updateTwelveEcgView();
  }

  void _onConnectFail(sender, e) async {
    logger.i("设备连接失败:${worker.mac}");
    connectStatus = WorkerStatus.connectionFailed;
    twelveEcgStatus = TwelveEcgStatus.noSampling;
    setState(() {});
  }

  /// 采样稳定
  void _onEcgStable(sender, e) async {
    twelveEcgStatus = TwelveEcgStatus.stableSampling;
    PromptBox.toast("当前心电已稳定,开始采样");
    logger.i('当前心电已稳定,开始采样');
    resetEcgView();
    setState(() {});
  }

  void _onSaveSuccess(sender, e) async {
    if (e) {
      PromptBox.toast("采样结束");
      twelveEcgStatus = TwelveEcgStatus.noSampling;
    }
    setState(() {});
  }

  void _onBounding(sender, e) {
    connectStatus = WorkerStatus.boundingDevice;
    setState(() {});
  }

  void _onBoundSuccess(sender, e) {
    tryReconnect();
    setState(() {});
  }

  void _onBoundFail(sender, e) {
    connectStatus = WorkerStatus.boundDeviceFail;
    setState(() {});
  }

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

  /// 设备连接中断
  void _onDisconnected(sender, e) async {
    print('设备连接中断');
    logger.i("设备连接中断:${worker.mac}");
    // await tryReconnect();
    errorCount = 0;
    connectStatus = WorkerStatus.disconnected;
    twelveEcgStatus = TwelveEcgStatus.noSampling;
    setState(() {});
  }

  /// 更新心率
  void _onHrValueUpdate(_, TwelveHeartExamData e) {
    setState(() {
      if (e.heartRate < 0) {
        _heart = "--";
      } else {
        _heart = e.heartRate.toString();
      }
      try {
        TwelveEcgViewController ecgViewController =
            Get.find<TwelveEcgViewController>();
        ecgViewController.addData(e.ecgPoints);
      } catch (e) {
        print('🥥🥥🥥🥥');
        print(e);
        print('🥥🥥🥥🥥');
      }
    });
  }

  void _onConclusion(_, TwelveHeartExamResult e) async {
    logger.i('心率更新接收结果：${e.heartRate}');
    _assess = e.resultConclusion.advice;
    _analyse12 = jsonEncode(e.resultConclusion.toJson());
    await ConclusionDialog.show(twelveHeartResult: e.resultConclusion);
    if (e.heartRate < 0) {
      _heart = "--";
    } else {
      _heart = e.heartRate.toString();
    }
    medicalController.diagnosisDataValue['TwelveHeart']?['HEART12'] =
        e.heartRate.toString();
    medicalController.diagnosisDataValue['TwelveHeart']?['ASSESS12'] = _assess;
    medicalController.diagnosisDataValue['TwelveHeart']?['Analyse12'] =
        _analyse12;
    await setEcgData();
    medicalController.saveCachedRecord();
    setState(() {});
  }

  void _openConclusion() async {
    TwelveHeartResultEntity resultConclusion =
        TwelveHeartResultEntity.fromJson(jsonDecode(_analyse12));
    await ConclusionDialog.show(twelveHeartResult: resultConclusion);
  }
}
