// eslint-disable-next-line
import { notFoundRouter, constantRouterComponents } from '@/config/router.config'
//import store from '../store'
import storage from 'store'
import getRouterComponent from 'plg-platform-setting'


/**
 * 根级菜单
 */
let rootRouter = {
  key: '',
  name: '首页',
  path: '/',
  meta: { title: '首页' },
  component: 'BasicLayout',
  children: []
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = ({ menus }) => {
  return new Promise((resolve, reject) => {
    menus = menus.filter((x) => {
      if (x.type == 0) {
        if (x.path == '/home') {
          rootRouter.redirect=x.path
        }
        return true;
      }
      return false;
    })
    try {
      const childrenNav = []
      // 后端数据, 根级树数组,  根级 PID
      listToTree(menus, childrenNav, '0')
      rootRouter.children = childrenNav
      const routers = generator([rootRouter])
      routers.push(notFoundRouter)
      resolve(routers)
    } catch (err) {
      reject(err)
    }
  })
}

// const menuLang = param => {
//   const lang = localStorage.getItem('app_language')
//   const langData = i18n.getLocaleMessage(lang)
//   let key = param
//   let text = langData[key]
//   return text
// }

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { hiddenHeaderContent } = item.meta || {}
    const {
      menuId,
      name,
      parentId,
      menuOrder,
      number,
      hidden,
      hideChildren,
      target,
      icon,
      keepAlive,
      iframePath,
      leaf
    } = item

    if (target === '_blank') {
      let _token = storage.get('token'),
        _expire = storage.get('expire')
      if (_token && _expire) {
        item.path = `${item.path}?token=${_token}&expire=${_expire}`
      }
    }
    if (getRouterComponent&&!constantRouterComponents[item.component]) {
      constantRouterComponents[item.component] = getRouterComponent(item)
    }
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
      name: name,
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component:
        constantRouterComponents[item.component || item.key] ||
        (() => {
          return import(/* webpackChunkName: "[request]" */ `@/views${item.component}`).catch(res => {
            //console.error(res)
            return import(`@/global_page/exception/404`)
          })
        }),

      meta: {
        title: name,
        icon: icon || undefined,
        hiddenHeaderContent: hiddenHeaderContent,
        target: target === '_blank' ? target : undefined,
        menuId: menuId,
        path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
        iframe: target === 'iframe',
        keepAlive: keepAlive,
        iframePath: iframePath
      },
      menuId: menuId,
      parentId: parentId,
      target: target,
      number: number,
      leaf: leaf,
      menuOrder: menuOrder
    }
    // 是否设置了隐藏菜单
    if (hidden) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param {list} array 源数组
 * @param {tree} array 树
 * @param {parentId} string 父级ID (如果是数字强制转字符串) 默认顶级ID为 "0"
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId == parentId) {
      const child = {
        ...item,
        key: item.number || item.name,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.menuId)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      tree.push(child) // 加入到树中
    }
  })
}
