import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_comm/pages/empty_page/empty_page.dart';

class NativeUtil {
  // 工厂模式
  factory NativeUtil() => _getInstance();
  static NativeUtil get instance => _getInstance();
  static NativeUtil _instance;

  MethodChannel _methodChannel;
  NativeUtil._internal() {
    // 初始化
    _methodChannel = MethodChannel('zhiying_comm://method');
  }
  static NativeUtil _getInstance() {
    if (_instance == null) {
      _instance = new NativeUtil._internal();
    }
    return _instance;
  }

  static Future<Map<String, dynamic>> _invokeChannel(String method,
      {Map<String, dynamic> params}) async {
    var res;
    try {
      res = await NativeUtil.instance._methodChannel.invokeMethod(method, params);
    } catch (e) {
      res = {'Failed': e.message};
    }

    print(res);
    return Map<String, dynamic>.from(res);
  }

  // 通过原生webview打开url
  static Future openUrl(BuildContext context, String url) {
    Map<String, dynamic> params = Map<String, dynamic>();
    params['url'] = url ?? '';
    params['SkipUIIdentifier'] = 'pub.flutter.url';
    NativeUtil.openPage(context, params);
  }

  // 公共跳转方法
  static Future openPage(BuildContext context, Map<String, dynamic> params) {
    return Navigator.of(context)
        .push(MaterialPageRoute(builder: (BuildContext context) {
      if (!params.containsKey('SkipUIIdentifier')) {
        return EmptyPage();
      }
      return PageFactory.create(params['SkipUIIdentifier'], params);
    }));
  }

  //跳转原生普通页面，非公共跳转
  static Future openNativePage(NativeRouter router, {Map params}) {
    String method = enumToString(router);
    return NativeUtil._invokeChannel('openNativePage', params: {
      'method': method,
      'params': params == null ? {} : Map<String, dynamic>.from(params)
    });
  }


  static Future<Map<String, dynamic>> getSetting() async {
    return NativeUtil._invokeChannel('getSetting');
  }


//  static Future<Map<String, dynamic>> onPagePop(bool isTop) async {
//    NativeUtil._invokeChannel('pageDidPop',
//        params: new Map<String, dynamic>.from({'isTop': isTop}));
//  }
//
//  static Future<Map<String, dynamic>> onPagePush(bool isTop) async {
//    NativeUtil._invokeChannel('pageDidPush',
//        params: new Map<String, dynamic>.from({'isTop': isTop}));
//  }

  static Future<Map<String, dynamic>> invokeMethod(
      String method, Map<String, dynamic> params) {
    Map<String, dynamic> request = {"method": method, "params": params};
    return NativeUtil._invokeChannel('invokeMethod', params: request);
  }
}
