import 'package:eitc_erm_dental_flutter/entity/db/local_patient_info.dart';
import 'package:eitc_erm_dental_flutter/sp_util.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';

///数据库工具
class DbUtil {
  static DbUtil? _instance;

  static DbUtil get instance => _instance ??= DbUtil._();

  late Isar _isar;

  DbUtil._();

  ///初始化
  Future<dynamic> init() async {
    _isar = await Isar.open([LocalPatientInfoSchema],
        name: "dental",
        directory: (await getApplicationSupportDirectory()).path);
    return true;
  }

  ///获取咨询人列表
  Future<List<LocalPatientInfo>> getLocalPatientList() async {
    String userId = await SpUtil.getUserId();
    return _isar.localPatientInfos.filter().userIdEqualTo(userId).findAll();
  }

  ///添加或更新单个咨询人
  Future<Id> putLocalPatient(LocalPatientInfo info) {
    return _isar.writeTxn(() => _isar.localPatientInfos.put(info));
  }

  ///添加或更新多个咨询人
  Future<List<int>> putLocalPatients(List<LocalPatientInfo> list) {
    return _isar.writeTxn(() => _isar.localPatientInfos.putAll(list));
  }

  ///删除所有咨询人
  Future<int> deleteAllLocalPatients() async {
    String userId = await SpUtil.getUserId();
    return _isar.writeTxn(() =>
        _isar.localPatientInfos.filter().userIdEqualTo(userId).deleteAll());
  }

  ///删除咨询人
  Future<bool> deleteLocalPatinetById(Id id) {
    return _isar.writeTxn(() => _isar.localPatientInfos.delete(id));
  }

  ///根据服务器ID查找咨询人
  Future<LocalPatientInfo?> getLocalPatinetByServerId(String serverId) {
    return _isar.localPatientInfos
        .filter()
        .serverIdEqualTo(serverId)
        .findFirst();
  }

  ///查找咨询人
  Future<LocalPatientInfo?> getLocalPatinet(
      String name, String idCard, String relation) async {
    String userId = await SpUtil.getUserId();
    return _isar.localPatientInfos
        .filter()
        .userIdEqualTo(userId)
        .and()
        .nameEqualTo(name)
        .and()
        .idCardEqualTo(idCard)
        .and()
        .relationEqualTo(relation)
        .findFirst();
  }

  ///根据ID获取咨询人
  Future<LocalPatientInfo?> getLocalPatientById(Id id) {
    return _isar.localPatientInfos.get(id);
  }
}
