import 'dart:convert';

import 'package:fis_jsonrpc/rpc.dart';
import 'package:vnoteapp/architecture/storage/text_storage.dart';
import 'package:vnoteapp/managers/interfaces/template.dart';
import 'package:vnoteapp/rpc.dart';
import 'package:vnoteapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';

class TemplateManager implements ITemplateManager {
  /// 获取系统模板设置

  @override
  Future<SyncSettingsDTO?> syncSetting(SyncSettingRequest request) async {
    try {
      request.token = Store.user.token;
      final result = await rpc.systemSetting.syncSettingAsync(request);
      return result;
    } catch (e) {
      logger.e("TemplateManager query patient paged list error.", e);
      return null;
    }
  }

  @override
  Future<TemplateDTO?> getTemplateDetail(GetTemplateRequest request) async {
    try {
      request.token = Store.user.token;
      final result = await rpc.template.getTemplateDetailAsync(request);
      return result;
    } catch (e) {
      logger.e("TemplateManager query patient paged list error.", e);
      return null;
    }
  }

  @override
  Future<bool?> saveTemplate() async {
    try {
      Map<String, String> currentTemplateIndex = {};
      SyncSettingRequest syncSettingRequest = SyncSettingRequest();
      var syncSettingsDTO = await syncSetting(syncSettingRequest);
      for (TemplateDTO i in syncSettingsDTO?.templates ?? []) {
        TemplateDTO? templateDTO = await getTemplateDetail(
          GetTemplateRequest(
            code: i.code!,
          ),
        );
        TextStorage template = TextStorage(
          fileName: i.code!,
          directory: "template",
        );
        currentTemplateIndex[templateDTO!.key!] = templateDTO.code!;
        await template.save(jsonEncode(templateDTO.toJson()));
      }

      /// 模板索引
      TextStorage templateRelation = TextStorage(
        fileName: "templateRelation",
        directory: "template",
      );
      await templateRelation.save(jsonEncode(currentTemplateIndex));
      return true;
    } catch (e) {
      logger.e("TemplateManager saveTemplate error.", e);
      return null;
    }
  }

  @override
  Future<String?> readTemplate(String fileName) async {
    try {
      TextStorage t = TextStorage(fileName: fileName, directory: "template");
      final str = await t.read();
      return str;
    } catch (e) {
      logger.e("TemplateManager readTemplate error.", e);
      return null;
    }
  }
}
