import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/cachedRecord.dart';
import 'package:vitalapp/managers/interfaces/device.dart';
import 'package:vitalapp/managers/interfaces/diagnosis.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';
import 'package:vitalapp/pages/medical/models/item.dart';
import 'package:vitalapp/pages/medical/state.dart';
import 'package:vitalapp/store/store.dart';

class MedicalController extends FControllerBase {
  String patientCode = '';
  Map<String, dynamic> diagnosisDataValue = {};

  late String appDataId;
  final state = MedicalState();

  final _diagnosisManager = Get.find<IDiagnosisManager>();
  final _cachedRecordManager = Get.find<ICachedRecordManager>();
  final _deviceManager = Get.find<IDeviceManager>();
  final _medicalMenus = [
    MedicalItem(key: DeviceTypes.TEMP, diagnosticItem: '体温'),
    MedicalItem(key: DeviceTypes.SUGAR, diagnosticItem: '血糖'),
    MedicalItem(key: DeviceTypes.NIBP, diagnosticItem: '血压'),
    MedicalItem(key: DeviceTypes.SPO2, diagnosticItem: '血氧'),
    MedicalItem(key: DeviceTypes.WEIGHT, diagnosticItem: 'BMI'),
  ];

  @override
  Future<void> onLoad() async {
    patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
    Get.put(MedicalController());
    var cachedAppDataId = await readCachedAppDataId();
    if (cachedAppDataId != null) {
      appDataId = cachedAppDataId;
    } else {
      await saveCachedAppDataId();
    }
    getAccessTypes();
    return super.onLoad();
  }

  Future<void> getAccessTypes() async {
    List<String> accessTypes = await _deviceManager.getAccessTypes();
    for (var element in _medicalMenus) {
      if (accessTypes.contains(element.key)) {
        state.medicalMenuList.add(element);
      }
    }
  }

  Future<DeviceModel?> getDevice(String type) async {
    List<DeviceModel> devices = await _deviceManager.getDeviceList();
    return devices.firstWhereOrNull((element) => element.type == type);
  }

  Future<void> readCachedRecord() async {
    String? value = await _cachedRecordManager.readCachedRecord(
      state.currentTab,
      patientCode,
      'ZLZS',
    );
    if (value == null) {
      return;
    }
    diagnosisDataValue[state.currentTab] = jsonDecode(value);
  }

  Future<bool?> saveCachedAppDataId() async {
    appDataId = const Uuid().v4().replaceAll('-', '');
    TextStorage cachedRecord = TextStorage(
      fileName: 'appDataId',
      directory: "patient/$patientCode",
    );
    return cachedRecord.save(appDataId);
  }

  Future<String?> readCachedAppDataId() async {
    TextStorage cachedRecord = TextStorage(
      fileName: 'appDataId',
      directory: "patient/$patientCode",
    );
    return cachedRecord.read();
  }

  Future<void> saveCachedRecord() async {
    await _cachedRecordManager.saveCachedRecord(
      state.currentTab,
      patientCode,
      'ZLZS',
      jsonEncode(
        diagnosisDataValue[state.currentTab],
      ),
    );
  }

  Future<void> createDiagnosis() async {
    CreateDiagnosisRequest diagnosisRequest = CreateDiagnosisRequest(
      patientCode: patientCode,
      appDataId: appDataId,
      diagnosisTime: DateTime.now(),
      diagnosisData: jsonEncode(diagnosisDataValue[state.currentTab]),
      key: state.currentTab,
    );
    saveCachedRecord();
    final result =
        await _diagnosisManager.createDiagnosisAsync(diagnosisRequest);
    if (result.isNotEmpty) {
      PromptBox.toast('保存成功');
      final index = state.medicalMenuList
          .indexWhere((element) => element.key == state.currentTab);
      if (index < 4) {
        state.currentTab = state.medicalMenuList[index + 1].key;
      } else {
        Get.back();
      }
    }
  }
}
