import 'dart:convert';

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_lib_report/converts/event_type.dart';
import 'package:flyinsono/architecture/app_parameters.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/keyboard.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/architecture/utils/web_parameter_helpler.dart';
import 'package:flyinsono/managers/server_config_manager.dart';
import 'package:flyinsono/pages/index.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:universal_html/html.dart' as html;
import 'index.dart';

class ReportTemplateController extends FControllerBase
    with EnterPressListenOnControllerMixin {
  ReportTemplateController();

  final state = ReportTemplateState();
  final onSelectImage = new FEventHandler<String>();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    _initparameters();
    _initTemolates();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  ///查找报告模板详情
  Future<ReportTemplateDTO?> findReportByCodeAsync(String id) async {
    try {
      if (id.isEmpty) return null;
      var result = await rpc.report.findReportTemplateByCodeAsync(
          FindReportTemplateByCodeRequest(
              languageCode: i18nBook.locale.toCodeString('-'),
              reportTemplateCode: id,
              token: Store.user.token));
      return result;
    } catch (e) {
      logger.e('ReportTemplateController saveTemplate:', e);
      print(e);
      return null;
    }
  }

  ///刷新
  Future<void> refershTemplates({int index: 0, bool isNeedBusy = true}) async {
    busy = isNeedBusy;
    await _initTemolates(index: index);
    busy = false;
  }

  ///选择不同模板
  ///[index] 模板位置
  Future<void> onSelectedTemplate(int index) async {
    state.isInitTemplates = false;
    state.selectTemplateIndex = index;
    final currentTemplate = state.templates[index];

    final template =
        await findReportByCodeAsync(currentTemplate.reportTemplateCode ?? '');
    if (template != null) state.selectedTemplate = template;
    if (template!.templatePreviewUrlList!.isEmpty) {
      state.isInitTemplates = false;
    } else {
      state.isInitTemplates = true;
    }
  }

  ///打开报告模板设计器
  Future<void> openTemplateDesigner(
    String templateName,
    ReportTemplateUsageTypeEnum reportTemplateUsageType,
    String templateCode,
  ) async {
    if (templateCode.isEmpty) {
      print('ReportTemplateController addReportTemplate failed');
      return;
    }
    router.back();
    await editTemplate(templateName, templateCode, reportTemplateUsageType);
  }

  ///编辑报告模板
  Future<void> editTemplate(
    String templateName,
    String templateId,
    ReportTemplateUsageTypeEnum reportTemplateUsageType, [
    bool isEdit = false,
  ]) async {
    String type = reportTemplateUsageType.index.toString();
    if (isEdit) {
      state.openMode = 'edit';
    } else {
      state.openMode = 'add';
    }
    if (FPlatform.isMacOS || FPlatform.isWindows) {
      final templateInfo = await findReportByCodeAsync(templateId);
      templateName = templateInfo == null
          ? templateName
          : templateInfo.reportTemplateName ?? '';
      final json =
          templateInfo == null ? '' : jsonEncode(templateInfo.toJson());

      if (LocalSetting.ins.isUseSecondWindow!) {
        await rpc.platform.openReportDesignerAsync(
          templateId,
          templateName,
          type,
          Store.user.token,
          json,
          state.isOrg,
          state.openMode,
        );
      } else {
        await rpc.platform.setTemplateJson(templateId, json);
        state.templateId = templateId;
        state.templateName = templateName;
        state.templateType = type;

        var homeController = Get.find<HomeController>();
        homeController.state.currentRouter =
            RouteNames.User.ReportTemplateDesigner;
        await router.to(RouteNames.User.ReportTemplateDesigner,
            id: NavIds.HOME);
      }
    } else {
      //if (Store.app.enableNewTab) {
      final window = html.window;
      final root = AppParameters.data.reportDesignerRoot;
      var languageCode = i18nBook.locale.toCodeString("-");
      var url =
          '$root/reportTemplateDesigner?id=$templateId&name=$templateName&type=$type&category=0&lang=$languageCode&isASROn=${ServerConfigManager.isASROn}';
      String openMode = isEdit ? 'edit' : 'add';
      if (state.isOrg) {
        url +=
            '&orgCode=${Store.user.rootOrganizationCode}&openMode=$openMode&templateType=1';
      } else {
        url += '&userCode=${Store.user.code}&openMode=$openMode&templateType=2';
      }
      print('open url:' + url);
      window.open(url, '_blank', '');
      // } else {
      //   state.templateId = templateId;
      //   state.templateName = templateName;
      //   state.templateType = type;
      //   var homeController = Get.find<HomeController>();
      //   homeController.state.currentRouter =
      //       RouteNames.User.ReportTemplateDesigner;
      //   await router.to(RouteNames.User.ReportTemplateDesigner,
      //       id: NavIds.HOME);
      // }
    }
  }

  ///删除报告模板
  Future<void> removeTemplate(String reportTemplateCode) async {
    bool result = false;
    if (!state.isOrg) {
      result = await rpc.report
          .removeReportTemplateAsync(RemoveReportTemplateRequest(
        token: Store.user.token,
        reportTemplateCode: reportTemplateCode,
      ));
    } else {
      result = await rpc.report
          .removeOrgReportTemplateAsync(RemoveReportTemplateRequest(
        token: Store.user.token,
        reportTemplateCode: reportTemplateCode,
      ));
    }
    if (!result) {
      PromptBox.toast(i18nBook.user.deleteFailed.t);
    } else {
      PromptBox.toast(i18nBook.user.deleteSuccess.t);
      refershTemplates();
    }
  }

  ///设置默认模板
  Future<void> setDefaultTemplate(int index) async {
    final reportTemplateCode = state.templates[index].reportTemplateCode;
    final result = await rpc.report.setUserDefaultReportTemplateAsync(
      SetUserDefaultReportTemplateRequest(
        reportTemplateCode: reportTemplateCode,
        token: Store.user.token,
        languageCode: i18nBook.locale.toCodeString('-'),
      ),
    );
    if (result) {
      state.defaultTemplateCode = reportTemplateCode ?? '';
      refershTemplates(index: index);
    }
  }

  ///获取默认模板
  Future<String> getDefaultTemplateCode() async {
    try {
      final result = await rpc.report.getDefaultReportTemplateContentAsync(
          GetDefaultReportTemplateContentRequest(
        token: Store.user.token,
        languageCode: i18nBook.locale.toCodeString('-'),
      ));
      return result.reportTemplateCode ?? '';
    } catch (e) {
      logger.e('ReportTemplateController getDefaultTemplateCode', e);
      return '';
    }
  }

  ///搜索
  void search() {
    busy = true;
    _initTemolates();
    busy = false;
  }

  ///初始化报告模板
  Future<void> _initTemolates({int index: 0}) async {
    try {
      if (!state.isOrg) {
        final defaultTemplateCode = await getDefaultTemplateCode();
        if (defaultTemplateCode.isNotEmpty) {
          state.defaultTemplateCode = defaultTemplateCode;
        }
      }
      PageResult<ReportTemplateDTO> result =
          await getTemplates(isDefault: true);
      final datas = result.pageData;
      if (datas != null) state.templates = datas;
      if (state.templates.isNotEmpty) {
        state.isInitTemplates = true;
        final template = await findReportByCodeAsync(
            state.templates[index].reportTemplateCode ?? '');
        if (template != null) {
          state.selectedTemplate = template;
          await onSelectedTemplate(index);
        }
      } else {
        state.isInitTemplates = false;
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> getPublishTemplates() async {
    var pages = await getTemplates(isDefault: false);
    state.publishTemplates = pages.pageData ?? [];
  }

  Future<PageResult<ReportTemplateDTO>> getTemplates({bool? isDefault}) async {
    PageResult<ReportTemplateDTO> result;
    if (!state.isOrg) {
      result = await rpc.report
          .getReportTemplatePageAsync(FindReportTemplatePagesRequest(
        token: Store.user.token,
        pageIndex: 1,
        pageSize: 100,
        languageCode: i18nBook.locale.toCodeString('-'),
        reportTemplateName: (isDefault == true) ? state.key : '',
      ));
    } else {
      result = await rpc.report
          .getOrgReportTemplatePageAsync(FindReportTemplatePagesRequest(
        token: Store.user.token,
        pageIndex: 1,
        pageSize: 100,
        languageCode: i18nBook.locale.toCodeString('-'),
        reportTemplateName: (isDefault == true) ? state.key : '',
      ));
    }
    return result;
  }

  ///初始化入参
  Future<void> _initparameters() async {
    var parameters = router.getParams(NavIds.HOME) ?? {};
    if (parameters.isEmpty) {
      parameters = ParameterHelper.parasmeters;
    }
    if (parameters.isNotEmpty) {
      state.isOrg = false;
      if (parameters.containsKey('isOrg')) {
        if (parameters['isOrg'] == 'true' || parameters['isOrg'] == 'True') {
          state.isOrg = true;
        }
      }
      state.templateType = parameters['templateType'] ?? '';
      state.templateName = parameters['templateName'] ?? '';
      state.templateId = parameters['templateId'] ?? '';
      state.openMode = parameters['openMode'] ?? 'add';
    }
  }

  @override
  void onEnterPressed() {
    search();
  }
}
