import 'package:fis_common/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/web_parameter_helpler.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/js_platform/methods.dart';
import 'package:flyinsono/managers/interfaces/report.dart';
import 'package:flyinsono/managers/interfaces/server_config.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/user/report_template/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

import 'base.dart';

/// 保存报告模板
class SaveReportTemplateHandler extends MethodHandlerBase {
  SaveReportTemplateHandler() : super(TargetMethodName.SaveReportTemplate);

  @override
  void execute(List<String> args) {
    _saveTemplate(
      args[0],
      args[1],
      args[2],
      args[3],
      args[4],
      args[5],
      int.parse(args[6]),
      args[7],
    );
  }

  ///保存模板
  Future<void> _saveTemplate(
    String id,
    String name,
    String type,
    String templateJson,
    String reportDatasJson,
    String openMode,
    int templateType,
    String languageCode,
  ) async {
    bool result = false;
    ReportTemplateTypeEnum reportTemplateType = ReportTemplateTypeEnum.Default;
    try {
      final controller = Get.find<ReportTemplateController>();
      reportTemplateType = controller.state.isOrg
          ? ReportTemplateTypeEnum.Organization
          : ReportTemplateTypeEnum.Personal;
    } catch (e) {}
    if (openMode == 'edit') {
      result = await rpc.report.updateReportTemplateAsync(
        UpdateReportTemplateRequest(
            token: Store.user.token,
            reportTemplateCode: id,
            reportTemplateName: name,
            reportTemplateJson: templateJson,
            reportDatasJson: reportDatasJson),
      );
    } else {
      var res = await rpc.report.addReportTemplateAsync(
        AddReportTemplateRequest(
          reportTemplateName: name,
          reportTemplateJson: templateJson,
          reportDatasJson: reportDatasJson,
          token: Store.user.token,
          reportTemplateType: reportTemplateType,
          languageCode: languageCode,
        ),
      );
      result = res.isNotEmpty;
    }
    if (result) {
      try {
        final controller = Get.find<ReportTemplateController>();
        controller.refershTemplates(isNeedBusy: false);
      } catch (e) {
        logger.e('SaveReportTemplateHandler _saveTemplate ex: ' + e.toString());
      }
      if (FPlatform.isWindows || FPlatform.isMacOS) {
        Future.delayed(Duration(milliseconds: 200), () {
          PromptBox.success(i18nBook.user.saveSuccess.t);
        });
      }
    } else {
      logger.e('ReportTemplateController saveTemplate result failed by name: ' +
          name);
    }
  }
}

/// 刷新报告列表
class RefershReportsHandler extends MethodHandlerBase {
  RefershReportsHandler() : super(TargetMethodName.RefershReports);

  @override
  void execute(List<String> args) {
    try {
      final currentRouter = router.getCurrentNameByNavId(NavIds.HOME);
      if (currentRouter == RouteNames.Remedical.ConsultationRecordView) {
        Get.find<IReportManager>().onSubmitReport.emit(this, true);
        return;
      }
      logger.i('RefershReportsHandler start');
      final controller = Get.find<ConsultationController>();
      controller.inspectionRecordsController
          .getCheckLists(controller.state.patientCode);
      controller.patientInfoController
          .getPatientInfo(controller.state.patientCode);

      controller.inspectionReportController.findPatientReportsAsync();
      logger.i('RefershReportsHandler end');
    } catch (e) {
      logger.e('_refershReports ex', e);
    }
  }
}

/// 打开报告编辑页面
class OpenReportEditPageHandler extends MethodHandlerBase {
  OpenReportEditPageHandler() : super(TargetMethodName.OpenReportEditPage);

  @override
  Future<void> execute(List<String> args) async {
    await Global.initLanguageByPlatform();
    Map<String, String> parameters = {};
    parameters['token'] = args[0];
    parameters['patientCode'] = args[1];
    parameters['reportCode'] = args[2];
    parameters['recordCode'] = args[3];
    parameters['referralRecordCode'] = args[4];
    parameters['consultationCode'] = args[5];
    ParameterHelper.parasmeters = parameters;
    router.offAll(RouteNames.Remedical.ReportEdit, parameters: parameters);
  }
}

/// 打开报告预览页面
class OpenReportPreviewPageHandler extends MethodHandlerBase {
  OpenReportPreviewPageHandler()
      : super(TargetMethodName.OpenReportPreviewPage);

  @override
  Future<void> execute(List<String> args) async {
    await Global.initLanguageByPlatform();
    Map<String, String> parameters = {};
    parameters['token'] = args[0];
    parameters['reportCode'] = args[1];
    parameters['recordCode'] = args[2];
    parameters['isFromEditor'] = args[3];
    ParameterHelper.parasmeters = parameters;
    router.offAll(RouteNames.Remedical.ReportPreview, parameters: parameters);
  }
}

/// 打开报告设计页面
class OpenReportDesignerPageHandler extends MethodHandlerBase {
  OpenReportDesignerPageHandler()
      : super(TargetMethodName.OpenReportDesignerPage);

  @override
  Future<void> execute(List<String> args) async {
    await Global.initLanguageByPlatform();
    Map<String, String> parameters = {};
    parameters['templateId'] = args[0];
    parameters['templateName'] = args[1];
    parameters['templateType'] = args[2];
    parameters['token'] = args[3];
    parameters['isOrg'] = args[4];
    parameters['openMode'] = args[5];
    print(parameters);
    var token = parameters['token'] ?? '';
    if (token.isNotEmpty) {
      Store.user.setToken(token);
      var manager = Get.find<IUserInfoManager>();
      await manager.getUserInfoAsync();
      await Get.find<IServerConfigManager>().getAllServerConfig();
    }

    ParameterHelper.parasmeters = parameters;
    router.offAll(RouteNames.User.ReportTemplateDesigner,
        parameters: parameters);
  }
}
