import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:zhiying_comm/pages/login_page/login_page.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class RouterUtil {
  /*公共跳转
  * skipModel 跳转参数
  * data 额外参数
  * */
  static Future route(SkipModel skipModel, Map<String, dynamic> data,
      BuildContext context) async {
    if (skipModel.skipIdentifier == null || skipModel.skipIdentifier == '') {
      print('skipIdentifier 参数不存在，无法跳转页面');
      return Future.error('skipIdentifier 参数不存在，无法跳转页面');
    }
    print('skipIdentifier: ${skipModel.skipIdentifier}');

    if (skipModel?.requiredLogin == '1') {
      UserInfoModel user =
          await Provider.of<UserInfoNotifier>(context, listen: false)
              .getUserInfoModel();
      print(user.toString());
      if (user?.token == null || user.token == '') {
        print('need login...');
        return RouterUtil.goLogin(context);
      }
    }

    Widget page = EmptyPage();
    if (PageFactory.hasRegisted(skipModel.skipIdentifier)) {
      page = PageFactory.create(skipModel.skipIdentifier, data);
    } else {
      var result = await NetUtil.post(
          '/api/v1/mod/${skipModel.skipIdentifier.toString()}',
          method: NetMethod.GET);
      Logger.debug(result);
      page = PageFactory.create('index', Map<String, dynamic>.from(result));
    }
    return Navigator.of(context)
        .push(CupertinoPageRoute(builder: (BuildContext context) {
      return page;
    }));
  }

  // 跳转登录
  static Future goLogin(BuildContext context) {
    return Navigator.of(context)
        .push(CupertinoPageRoute(builder: (BuildContext context) {
      return LoginPage();
    }));
  }

  static Future openWebview(String url, BuildContext context) {
    if (url == null || url == '') {
      Logger.error('跳转链接不能为空');
      return Future.error('跳转链接不能为空');
    }
    SkipModel model = SkipModel();
    model.skipIdentifier = 'pub.flutter.url';
    model.url = url;
    RouterUtil.route(model, null, context);
  }
}
