// eslint-disable-next-line
import * as loginService from '@/api/menu'

// 前端路由表 (基于动态)
const constantRouterComponents = {
  '404': () => import('@/views/404'),
  Base: () => import('@/views/common/Base'),
  // 你需要动态引入的页面组件
  // 系统管理
  transport: () => import('@/views/system/transport'),
  salesStore: () => import('@/views/system/salesStore'),
  employee: () => import('@/views/system/employee'),
  jurisdiction: () => import('@/views/system/jurisdiction'),
  menuManagement: () => import('@/views/system/menuManagement'),
  // 生产管理
  cylinderFile: () => import('@/views/manufacture/cylinderFile'),
  cylinderSpecification: () => import('@/views/manufacture/cylinderSpecification'),
  warehouse: () => import('@/views/manufacture/warehouse'),
  tankFilling: () => import('@/views/manufacture/tankFilling'),
  vehicle: () => import('@/views/manufacture/vehicle'),
  loadingGun: () => import('@/views/manufacture/loadingGun'),
  aerationInspection: () => import('@/views/manufacture/aerationInspection'),
  wanderAbout: () => import('@/views/manufacture/wanderAbout'),
  equipment: () => import('@/views/manufacture/equipment'),
  cylinderCondition: () => import('@/views/manufacture/cylinderCondition'),
  // 客户中心
  agentOrdering: () => import('@/views/customer/agentOrdering'),
  orderProcessing: () => import('@/views/customer/orderProcessing'),
  customerFiling: () => import('@/views/customer/customerFiling'),
  entrySecurity: () => import('@/views/customer/entrySecurity'),
  complaints: () => import('@/views/customer/complaints'),
  // 销售管理
  orderManagement: () => import('@/views/marketing/orderManagement'),
  commodity: () => import('@/views/marketing/commodity'),
  salesScheme: () => import('@/views/marketing/salesScheme'),
  allocation: () => import('@/views/marketing/allocation'),
}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  name: '404',
  path: '*',
  redirect: '/404',
  hidden: true
}

// 根级菜单
const rootRouter = {
  name: 'index',
  path: '/',
  component: () => import('@/views/common/Base'),
  redirect: '/home',
  children: [{
    path: '/home',
    name: 'home',
    component: () => import('@/views/page/Home'),
  }]
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    loginService
      .getMenuRole(token)
      .then(res => {
        const result = res.data
        // console.log('generatorDynamicRouter response:', result)

        function getFlatArr(arr) {
          return arr.reduce((a, item) => {
            let flatArr = [...a, item];
            if (item.children) {
              flatArr = [...flatArr, ...getFlatArr(item.children)];
            }
            return flatArr;
          }, []);
        }
        let dataArr = []
        let arrList = getFlatArr(result);
        arrList.forEach(item => {
          let arrList1 = {}
          arrList1.meta = {
            title: item.title,
            icon: item.icon,
            show: true,
          }
          if (item.visible == '1') {
            arrList1.meta.show = true
          } else {
            arrList1.meta.show = false
          }
          arrList1.component = item.component
          arrList1.id = item.id
          arrList1.name = item.name
          arrList1.parentId = item.parentId
          if (item.parentId == 0) {
            arrList1.redirect = item.redirect
          }
          dataArr.push(arrList1)
        })
        const menuNav = []
        const childrenNav = []
        listToTree(dataArr, childrenNav, 0)
        childrenNav.forEach((item) => {
          menuNav.push(item)
        })
        // console.log('menuNav', menuNav)
        const routers = generator(menuNav)
        routers.push(notFoundRouter)
        routers.push(rootRouter)
        // console.log('routers', routers)
        resolve(routers)
      }).catch(err => {
        reject(err)
      })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const {
      title,
      show,
      hideChildren,
      hiddenHeaderContent,
      target,
      icon
    } = item.meta || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件 :方案1
      // 该路由对应页面的 组件 :方案2 (动态加载)
      component: constantRouterComponents[item.component || item.key] || (() => import(
        `@/views/${item.component}`)),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: title,
        icon: icon || undefined,
        // hiddenHeaderContent: hiddenHeaderContent,
        // target: target,
        // permission: item.name
      }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      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) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

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