import { FILTER_FOLER_REG } from './constants';

export const guid = function(prefix) {
  let date = new Date().getTime();
  if (window.performance && typeof window.performance.now === 'function') {
    date += performance.now();
  }
  let 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 generRotes = (widgets, parent) => {
  let ret = [];
  widgets.forEach(item => {
    if (item.hasOwnProperty('widgets')) {
      ret.push({
        name: item.label,
        path: `/civweb/${guid('web_console')}`,
        component: 'BasicLayout',
        routes: generRotes(item.widgets, item),
        extData: { ...item },
      });
    } else {
      const baseURL = FILTER_FOLER_REG.test(item.url) ? 'civweb4' : 'civweb5';
      const url = item.hasOwnProperty('url')
        ? `/${baseURL}/${item.url.replace(/\s*/g, '') +
            (item.url.indexOf('?') > -1
              ? `&fromSource=${guid('panda')}`
              : `?fromSource=${guid('panda')}`)}`
        : guid('web_console');
      ret.push({
        name: item.label,
        component: 'BasicLayout',
        path: url,
        key: guid('panda'),
        extData: { ...item },
      });
    }
  });
  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) => {
  let flatMenu = [];
  (widgets || []).forEach(item => {
    if (item.hasOwnProperty('routes')) {
      const route = generFlatRoutes(item.routes, item);
      flatMenu.push(simpleNormalizeChildren(route));
    } else {
      flatMenu.push({
        ...item,
        parent: parent,
      });
    }
  });
  return simpleNormalizeChildren(flatMenu);
};

export default generRotes;
