
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, '.');
};
// web5 web4路由菜单生成

// 重写菜单生成, web4和web5分开
const getPosition = (level, index) => `${level}-${index}`;
const getKey = (key, pos) => {
  if (key !== null && key !== undefined) {
    return key;
  }
  return pos;
};
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;
      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: (item && item.icon && item.icon !== null && item.icon.replace(/\s*/g, '')) || '',
        },
      });
    } else {
      const baseURL = item.product || DEFAULT_APPLICATION;
      let url = item.hasOwnProperty('url') && item.url !== undefined ? `/${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
      }

      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: (item && item.icon && item.icon !== null && item.icon.replace(/\s*/g, '')) || '',
        },
        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;
