import 'dart:io';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/exam.dart';
import 'package:vitalapp/pages/check/models/form.dart';
import 'package:vitalapp/store/store.dart';

class ExaminationController extends GetxController {
  ExaminationController();
  final _examManager = Get.find<IExamManager>();
  late String patientCode;
  late String batchNumber;

  _initData() {
    update(["examination"]);
    patientCode = Store.user.currentSelectPatientInfo?.code ?? '';
    getBatchNumber();
  }

  Future<void> getBatchNumber() async {
    var cachedBatchNumber = await readCachedBatchNumber();
    if (cachedBatchNumber != null) {
      batchNumber = cachedBatchNumber;
    } else {
      await saveCachedBatchNumber();
    }
  }

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

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

  List<MenuItem> menuList = [
    MenuItem(label: "一般状况", value: 'ZZYBZK'),
    MenuItem(label: "辅助检查", value: 'FZJC'),
    MenuItem(label: "生活方式", value: 'SHFS'),
    MenuItem(label: "脏器及查体", value: 'ZQCT'),
    MenuItem(label: "现存主要健康问题", value: 'XCZYWT'),
    MenuItem(label: "住院及用药情况", value: 'ZYYYFMYGHYFJZS'),
    MenuItem(label: "健康评价及指导", value: 'JKPJJZD'),
  ];

  Future<void> createOrUpdateExam(key, templateCode, data) async {
    TextStorage template = TextStorage(
      fileName: key,
      directory: "patient/$patientCode/exam",
    );
    var result = await _examManager.createExam(CreateExamRequest(
      key: key,
      patientCode: patientCode,
      templateCode: templateCode,
      examData: data,
      batchNumber: batchNumber,
    ));

    if (result ?? false) {
      try {
        template.save(data);
        PromptBox.toast('保存成功');
      } catch (err) {
        PromptBox.toast('保存失败');
      }
    }
  }

  /// 检查数据是否为空
  Future<bool> checkExamEmpty() async {
    try {
      final root = await getExternalStorageDirectory();
      final dir = Directory("${root!.path}/patient/$patientCode/exam");
      if (await dir.exists()) {
        final files = dir.listSync();
        return files.isEmpty;
      } else {
        return true;
      }
    } catch (e) {
      return false;
    }
  }

  Future<void> deleteCached() async {
    saveCachedBatchNumber();
    TextStorage template = TextStorage(
      fileName: '',
      directory: "patient/$patientCode/exam",
    );
    final result = await template.deleteDirectory();
    if (result) {
      PromptBox.toast('本轮体检已结束');
      Get.back();
    }
  }

  @override
  void onReady() {
    _initData();
    super.onReady();
  }
}
