import 'package:flutter/material.dart';

import 'package:zhiying_comm/zhiying_comm.dart';

typedef Widget CreatePage(Map<String, dynamic> model);

/* 页面生成工厂, 用于生成flutter端公共跳转页面，native端页面生成PlatforView等等 */
class PageFactory {
  static Map<String, CreatePage> pageCreater = Map();

  /**
   * @description: 注册路由
   * @param {name} SkipUIIdentifier
   * @return:
   */
  static void regist(String name, CreatePage creater) {
    if (pageCreater.containsKey(name)) {
      return;
    }
    pageCreater[name] = creater;
  }

  /**
   * @description: 创建页面
   * @param {String} name注册的SkipUIIdentifier
   * @return:
   */
  static Widget create(String name, Map<String, dynamic> model) {
    if (pageCreater.containsKey(name)) {
      return pageCreater[name](model);
    }

    String tempName = _getSkipSuffix(name);
    if (!EmptyUtil.isEmpty(tempName) && pageCreater.containsKey(tempName)) {
      return pageCreater[tempName](model);
    }

    return EmptyPage();
  }


  // ⚠️ 由于使用了跳转标志带有后缀,所以需要判断是否带有后缀，如果带有并且是数字，则清除后缀获取page
  static String _getSkipSuffix(String name) {
    String tempName;
    try {
      String suffixStr = name.substring(name.lastIndexOf('.') + 1, name.length);
      tempName = name.substring(0, name.lastIndexOf('.'));
      Logger.log('sufix  = $suffixStr , prefix = $tempName');
      int suffixNum = int.parse(suffixStr);
      Logger.log('suffixNum = $suffixNum}');
    } catch (e) {
      tempName = null;
      Logger.debug(e);
    }
    return tempName;
  }

  /**
   * @description: 是否注册页面
   * @param {bool}
   * @return:
   */
  static bool hasRegisted(String name) {
    if (pageCreater.containsKey(name)) {
      return true;
    }

    String tempName = _getSkipSuffix(name);
    if (pageCreater.containsKey(tempName)) {
      return true;
    }
    return false;
  }
}
