import { transformURL } from './utils';
import LoadingComponent from '@ant-design/pro-layout/es/PageLoading';
import {
    dynamic
} from '@wisdom-utils/runtime';
import { matchPath, Route, Switch} from 'react-router';
import React, { Suspense, Fragment } from 'react';
export const isURL = function(url) {
  // eslint-disable-next-line no-useless-escape
  return /^(http|https)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(url);
};

const DEFAULT_APPLICATION = 'civweb4';
/* eslint-disable */
export const guid = function(prefix) {
  let date = new Date().getTime();
  if (window.performance && typeof window.performance.now === 'function') {
    date += performance.now();
  }
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(
    c,
  ) {
    const r = (date + Math.random() * 16) % 16 | 0;
    date = Math.floor(date / 16);
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
  });
  return prefix + uuid.replace(/-/g, '.') + new Date().getTime();
};

function getParams(pathname) {
  let ret = {};
  const url = pathname ? pathname : decodeURIComponent(window.location.pathname);
  if (url.indexOf('|') > -1) {
      const params = url.split('|')[1];

      params.split('&').map(item => ret[item.split("=")[0]] = item.split("=")[1])
      return ret;
  }
  return ret;

}

function isAbsoluteURL(url) {
  return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};

const level = 0;
const getURL = url => {
  const i = url.indexOf('#');
  const href = i >= 0 ? url.slice(0, i) : url;
  return href;
};

const generRotes = (widgets, parent, level = 0) => {

  const ret = [];
  if(!widgets || widgets.length === 0){
    return
  }
  (widgets).forEach((item, index) => {

    if (item.hasOwnProperty('widgets') && item.widgets !== null && Array.isArray(item.widgets) && item.widgets.length > 0) {
      const _level_ = level + 1;
      const path = `/civweb/${guid('web_console')}`;
      const subKey = guid('panda');
      const alias = DEFAULT_APPLICATION;
      const convertURL = transformURL(item.icon.replace(/\s*/g, ''));
      const icon = (item && item.icon && item.icon !== null &&
        isAbsoluteURL(convertURL) ? convertURL: /(\\|\/)/.test(convertURL) ?
          window.globalConfig.transformDevAssetsBaseURL(transformURL(item.icon.replace(/\s*/g, ''))): item.icon
      ) || '';
      ret.push({
        name: item.label,
        level: _level_,
        path,
        component: 'BasicLayout',
        parent,
        alias: alias,
        hideInMenu: item.hideInMenu || false,
        routes: generRotes(
          item.widgets,
          Object.assign({}, item, { path, key: subKey }),
          _level_,
          item.label
        ),
        extData: {
          ...item,
          icon: icon,
        },
      });
    } else {
      const baseURL = item.product || DEFAULT_APPLICATION;
      if(item.hasOwnProperty('url') &&  item.url === '') return;
      let url = item.hasOwnProperty('url') && item.url !== undefined && item.url !== '' ? `/${baseURL}/${item.url.replace(/\s*/g, '')}`
        : !item.hasOwnProperty('url')
          ? guid('web_console')
          : '';
      if (url.includes('url=')) {
        url = url.split('url=')[1];
        url = getURL(url);
      }

      if(isURL(item.url)) {
        url = item.url
      }
      url = transformURL(url);
      //url = url.replace(/[(\\|)|(&)]widget=[0-9]*/, '')
      const convertURL = item.icon && transformURL(item.icon.replace(/\s*/g, ''));
      const icon = (item && item.icon && item.icon !== null &&
        isAbsoluteURL(convertURL) ? convertURL: /(\\|\/)/.test(convertURL) ?
          window.globalConfig.transformDevAssetsBaseURL(transformURL(item.icon.replace(/\s*/g, ''))): item.icon
      ) || '';

      const l = level ? level + 1 : -1;
      let common = {
        name: item.label,
        level: l,
        component: 'BasicLayout',
        path: baseURL !== '' ? transformURL(url) : '',
        href: url,
        target: isURL(url) ? '_blank' : '',
        key: guid('panda'),
        hideInMenu: item.label === '系统菜单组' ? true: item.hideInMenu,
        //l > 3 ? true: item.hideInMenu || false,
        alias: item.product || DEFAULT_APPLICATION,
        extData: {
          ...item,
          icon,
        },
        parent,
      };
      if(/iframe/.test(url)) {
        url = url.replace(/\/report/, '');

        common = {
          name: item.label,
          level: l,
          component: dynamic({ loader: () =>
            import ( /* webpackChunkName: "p__[request]" */ `@/pages/${component}.js`), loading: LoadingComponent }),
          path: baseURL !== '' ? transformURL(url) : '',
          href: url,
          target: isURL(url) ? '_blank' : '',
          key: guid('panda'),
          hideInMenu: item.label === '系统菜单组' ? true: item.hideInMenu,
          //l > 3 ? true: item.hideInMenu || false,
          alias: item.product || DEFAULT_APPLICATION,
          extData: {
            ...item,
            icon,
          },
          params: getParams(url),
          parent,
        }
      }
      ret.push(common);
    }
  });
  return ret;
};
export const transformWidgets = (widgets) => {
  if(!widgets || widgets.length === 0) {
    return []
  }
  return widgets.map(item => {
    const widgets = item.widgets;
    const homepage = window.globalConfig.homepage;
    const homePageConvertArray = homepage.split("/");
    const findIndex = widgets && widgets.findIndex(item => item.label === '系统菜单组');
    if(findIndex === -1 && homePageConvertArray[0] !== 'civweb4') {
      const index = widgets.findIndex(item => item.label === '首页');
      if(index === -1) {
        widgets.push({
          label: "首页",
          icon: '',
          product: homePageConvertArray[0],
          shortName: "首页",
          hideInMenu: true,
          url: homePageConvertArray.slice(1, homePageConvertArray.length).join("/")
        });
      }
      item.widgets = Array.from(new Set(widgets));
    }

    return item;
  });
}
export function simpleNormalizeChildren(children) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children);
    }
  }
  return children;
}

export const generFlatRoutes = (widgets, parent, subSystem, modulePkg) => {
  const treeKeys = [];
  const flatMenu = [];
  if(!widgets || Array.isArray(widgets) && widgets.length === 0) {
    return [];
  }
  (widgets || []).forEach(item => {
    if (item.hasOwnProperty('routes')) {
      const route = generFlatRoutes(item.routes, item, item.name, modulePkg);
      flatMenu.push(simpleNormalizeChildren(route));
    } else {
      flatMenu.push({
        ...item,
        origin: item,
        moduleName: modulePkg[item.alias],
        treeKeys,
        subSystem,
        parent,
      });
    }
  });
  return simpleNormalizeChildren(flatMenu);
};

export function RouteWithSubRoutes(route) {
  return (
    <Route path={route.path} render={props => (<route.component {...props} route={route} routes={route.routes} params={route.params}/>)}></Route>
  )
}
function matchRoutes(routes, pathname, branch) {
    if (branch === void 0) {
      branch = [];
    }

    routes.some(function (route) {
      var match = route.path ? matchPath(pathname, route) : branch.length ? branch[branch.length - 1].match // use parent match
      : Router.computeRootMatch(pathname); // use default "root" match

      if (match) {
        branch.push({
          route: route,
          match: match
        });

        if (route.routes) {
          matchRoutes(route.routes, pathname, branch);
        }
      }

      return match;
    });
    return branch;
  }

function renderRoutes(routes, extraProps, switchProps) {
    if (extraProps === void 0) {
      extraProps = {};
    }

    if (switchProps === void 0) {
      switchProps = {};
    }

    return routes ? React.createElement(Switch, switchProps, routes.map(function (route, i) {
      return React.createElement(Route, {
        key: route.key || i,
        path: route.path,
        exact: route.exact,
        strict: route.strict,
        render: function render(props) {
          return route.render ? route.render(Object.assign({}, props, {}, extraProps, {
            routes: route.routes,
            params: route.params,
            route: route,
            rootPrefix: 'panda-console-base'
          })) : React.createElement(route.component, Object.assign({}, props, extraProps, {
            route: route,
            routes: route.routes,
            params: route.params,
            rootPrefix: 'panda-console-base'
          }));
        }
      });
    })) : null;
}

export {
  renderRoutes,
  matchPath
}

export default generRotes;
