import { transformURL } from './utils';

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 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) {
    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_,
        ),
        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);
      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
      ) || '';

      const l = level ? level + 1 : -1;
      const common = {
        name: item.label,
        level: l,
        component: 'BasicLayout',
        path: baseURL !== '' ? transformURL(url) : '',
        href: url,
        target: isURL(url) ? '_blank' : '',
        key: guid('panda'),
        hideInMenu: l > 3 ? true: item.hideInMenu || false,
        alias: item.product || DEFAULT_APPLICATION,
        extData: {
          ...item,
          icon,
        },
        parent,
      };
      ret.push(common);
    }
  });
  return ret;
};
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) => {
  const treeKeys = [];
  const flatMenu = [];
  (widgets || []).forEach(item => {
    if (item.hasOwnProperty('routes')) {
      const route = generFlatRoutes(item.routes, item, item.name);
      flatMenu.push(simpleNormalizeChildren(route));
    } else {
      flatMenu.push({
        ...item,
        treeKeys,
        subSystem,
        parent,
      });
    }
  });
  return simpleNormalizeChildren(flatMenu);
};

export default generRotes;
