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';

///诊断配置缓存
mixin _CheckFinderMixin {
  String _cache = "";

  /// 全部数据
  get allMap => json.decode(_cache);

  /// 所有检查项
  dynamic getChectList(Enum patientType) {
    return patientType == OrganizationPatientTypeEnum.Person
        ? json.decode(_cache)["ExamInfo"]!.keys.toList().where(
              (e) => e != 'BaseInfo',
            )
        : json.decode(_cache)["AnimalExamInfo"]!.keys.toList().where(
              (e) => e == 'Routine',
            );
  }
}

///检查配置服务
class CheckService extends GetxService with _CheckFinderMixin {
  static const _CHECK_FILENAME = "examine_configurations.conf";
  TextStorage _checkStorage = TextStorage.createInstance(_CHECK_FILENAME);
  var _version = "";

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

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

  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;
    }
  }
}
