/// 所有 h5 地图公共模块
///
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';

import './../../consts/url_const.dart';
import './native_bridge.dart';

/// 地图基类，作战地图相关的所有地图 h5 功能
class H5MapBase extends StatefulWidget {
  const H5MapBase({Key key, this.onCreated, this.h5Url = URLConst.MAP_H5_URL}) : super(key: key);

  final Function onCreated;

  /// h5 地图 URL
  final String h5Url;

  @override
  _H5MapBaseState createState() => _H5MapBaseState();
}

class _H5MapBaseState extends State<H5MapBase> {
  WebViewController webViewController;

  @override
  Widget build(BuildContext context) {
    print('h5 base map url:${widget.h5Url}');
    if (widget.h5Url == null || widget.h5Url.isEmpty) {
      return Container();
    }
    return Container(
        height: MediaQuery.of(context).size.height,
        child: WebView(
            // initialUrl: 'https://www.amap.com/',
            initialUrl: '${widget.h5Url}',
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController wvc) {
              webViewController = wvc;
              widget.onCreated(wvc);
            },

            /// 路由委托（可以通过在此处拦截url实现 JS 调用 Flutter部分）；
            navigationDelegate: (NavigationRequest request) {
              /// 通过拦截 url 来实现 js 与 flutter 交互
              if (request.url.startsWith('js://webview')) {
                AmosToast.show('JS调用了Flutter By navigationDelegate', context);
                print('blocking navigation to $request}');

                /// 阻止路由替换，不能跳转，因为这是js交互给我们发送的消息
                return NavigationDecision.prevent;
              }

              /// 允许路由替换
              return NavigationDecision.navigate;
            },

            /// 与h5 通信
            javascriptChannels: <JavascriptChannel>{
              _pageChange(context),
              _publickChanel(context),
            }));
  }

  JavascriptChannel _pageChange(BuildContext context) {
    return JavascriptChannel(
        name: 'PageChange',
        onMessageReceived: (JavascriptMessage jm) {
          String jsonStr = jm.message;
          JsBridgeUtil.execute(context, jsonStr, webViewController);
        });
  }

  /// 公共通道
  JavascriptChannel _publickChanel(BuildContext context) {
    return JavascriptChannel(
        name: 'CommonChanel',
        onMessageReceived: (JavascriptMessage jm) {
          String jsonStr = jm.message;
          JsBridgeUtil.execute(context, jsonStr, webViewController);
        });
  }

  void executeJs(String method, {dynamic data}) {
    webViewController.evaluateJavascript('$method()');
  }
}
