import { RouteRecordRaw } from 'vue-router';
import { getComponent } from '/nerv-base/router/helper/view-helper';
import { ModuleMenu } from '/nerv-base/router/types';
import { RouteMenu, sortMenu } from '/nerv-base/router/helper/menu-helper';
import { isNumber } from 'lodash-es';
const transForm = (data) => {
  return JSON.stringify(data || []);
};
export function transformRouteToMenu(route: RouteRecordRaw, parentCode = '') {
  const { children, ...extend } = route;
  if (extend.component) {
    const component = getComponent(extend.component.toString());
    component && (extend.component = component as any);
  }
  const code: any = route.meta?.code || route.name || '';
  if (!extend.meta) extend.meta = {};
  if (extend.meta.index === undefined || !isNumber(extend.meta.index)) {
    extend.meta.index = 999;
  }

  const _menu: ModuleMenu = {
    code,
    icon: (route.meta?.icon || ' ') as string,
    sort: (isNumber(route.meta?.index) ? route.meta?.index : 999) as number,
    label: (route.meta?.title || ' ') as string,
    type: (route.meta?.type || 'menus') as string,
    // name: dealOp(route) as string,
    backApi: dealBackApi(route) as Recordable[],
    parentCode,
    extend: {
      keepAlive: (route.meta?.keepAlive || false) as boolean,
      // itemList: route.meta?.itemList || null,
    },
    route: extend,
  };
  if (children) {
    _menu.menus = transformRoutes(children, code);
  }
  return _menu;
}
function dealBackApi(e: any) {
  if (e.meta?.hideChildren) {
    if (e.children !== undefined) {
      return transForm(e.children[0].meta?.backApi);
    } else {
      return transForm(e.meta?.backApi);
    }
  }
  return transForm(e.meta?.backApi);
}

function dealOp(e: any) {
  if (e.meta?.type === 'op') {
    return e.name;
  } else {
    return '';
  }
}

export function transformRoutes(routes: RouteRecordRaw[], parentCode = '') {
  const list = [];
  for (let i = 0, l = routes.length; i < l; i++) {
    if (routes[i].meta?.operates && !routes[i].meta?.hideResource) {
      routes[i].meta?.operates.forEach((item) => {
        const info = {
          sort: 999,
          type: 'op',
          code: item.code,
          name: '',
          label: item.title,
          backApi: item.backApi,
          parentCode: parentCode,
        };
        list.push(info);
      });
    }
    if (routes[i].name !== `${parentCode}Index` && !routes[i].meta?.hideResource) {
      list.push(transformRouteToMenu(routes[i], parentCode));
    }
  }
  return sortMenu(list);
}
