import 'dart:convert';

import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/storage/text_storage.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

///病人检查服务
class PatientCheckService extends GetxService with _CheckFinderMixin {
  static const _CHECK_FILENAME = "patient_configurations.conf";
  TextStorage _checkStorage = TextStorage.createInstance(_CHECK_FILENAME);
  var _version = "";

  ///初始化
  Future<void> init(bool? isChange) async {
    _version = "0.9";
    // 创建实例
    final list = await _checkStorage.fetch();
    if (list == null || isChange!) {
      _cache = "";
      await checkUpdate();
    } else {
      _cache = list;
    }
  }

  Future<bool> _saveData(String check) async {
    try {
      final saved = await _checkStorage.save(check);
      return saved;
    } catch (e) {
      logger.e("ConfigService save data error.", e);
      return false;
    }
  }

  ///检查更新
  ///判断是否更新本地缓存
  Future<bool> checkUpdate() async {
    try {
      final result = await rpc.organization.getOrganizationSettingAsync(
        GetUserOrganizationSettingRequest(
          version: _version,
          token: Store.user.token,
          settingType: OrganizationSettingTypeEnum.Patient,
        ),
      );
      if (result.settingVersion != _version && result.settingData != null) {
        _version = result.settingVersion!; // TODO: save db
        // _cache.clear();
        _cache = result.settingData!;
        await _saveData(_cache);
        return true;
      }
    } catch (e) {
      logger.e("PatientCheckService - call `checkUpdate` error.", e);
    }
    return false;
  }
}

mixin _CheckFinderMixin {
  String _cache = "";

  /// 所有病人需检查的项目
  dynamic getChectList() {
    return json.decode(_cache)["PatientInfo"] ??
        json.decode(_cache)["AnimalInfo"];
  }
}
