import 'dart:async';
import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import '../../services/application.dart';
import './event_bus.dart';

/// 执行 js 方法
typedef ExecuteJSMethod<T> = void Function(String method, {dynamic data});

class JsBridgeUtil {
  /// 将json字符串转化成对象
  static JsBridgeEntity parseJson(String jsonStr) {
    JsBridgeEntity jsBridgeModel = JsBridgeEntity.fromMap(jsonDecode(jsonStr));
    return jsBridgeModel;
  }

  /// 向 H5 开发接口调用
  static Future<void> executeMethod(context, JsBridgeEntity jsBridge, WebViewController ctl) async {
    switch (jsBridge.method) {

      /// 路由跳转
      case 'routeChange':
        Application.navigateTo(context, jsBridge.route);
        break;
      case 'showToast':
        AmosToast.show('${jsBridge.data}', context);
        break;

      /// 如果传递 success 则表示回调h5的 success 刷新方法
      case 'goBack':
        Application.goBack(context, result: '${jsBridge.success}');
        break;

      /// 接收数据
      case 'messageReceive':

        /// 具体消息数据，调用处自行处理
        EventData ed = jsBridge.data is String ? EventData.parseJson(jsBridge.data) : EventData.fromMap(jsBridge.data);
        DispatchEvents.fire(ed);
        break;

      /// 确认框
      case 'confirm':
        JsBridgeConfirmData jbcd;
        if (jsBridge.data is String) {
          jbcd = JsBridgeConfirmData.parseJson(jsBridge.data);
        } else if (jsBridge.data is Map) {
          jbcd = JsBridgeConfirmData.fromMap(jsBridge.data);
        }
        if (jbcd != null) {
          ConfirmBox.custom(context, title: jbcd.title ?? '提示', msg: jbcd.msg).then((bool flag) {
            if (flag) {
              if (jbcd.ok != null && jbcd.ok.isNotEmpty) {
                ctl.evaluateJavascript('${jbcd.ok}(${jbcd.okCallbackArgs})');
              }
            } else {
              if (jbcd.cancel != null && jbcd.cancel.isNotEmpty) {
                ctl.evaluateJavascript('${jbcd.cancel}()');
              }
            }
          });
        }

        /// 单 string
        else {
          ConfirmBox.custom(context, title: '提示', msg: '${jsBridge.data}');
        }
        break;
    }

    /// 成功回调
    if (jsBridge.success != null && jsBridge.success.isNotEmpty) {
      ctl.evaluateJavascript('${jsBridge.success}()');
    }
  }

  /// 向 H5 开发接口调用
  static Future<void> execute(context, String jsonStr, WebViewController ctl) async {
    JsBridgeEntity jsBridge = parseJson(jsonStr);
    executeMethod(context, jsBridge, ctl);
  }
}
