/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  { path: '/404', component: _import('common/404'), name: '404', meta: { title: '404未找到' } },
  { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' } }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { path: '/visi-dataset', component: _import('modules/visi/dataset'), meta: { title: '首页' } },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    { path: '/home', component: _import('common/home'), name: 'home', meta: { title: '首页' } },
    // { path: '/dataset', component: _import('common/dataset'), name: 'dataset', meta: { title: '数据集' } },
    { path: '/theme', component: _import('common/theme'), name: 'theme', meta: { title: '主题' } },
    { path: '/demo-echarts', component: _import('demo/echarts'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: false } },
    { path: '/demo-ueditor', component: _import('demo/ueditor'), name: 'demo-ueditor', meta: { title: 'demo-ueditor', isTab: false } },

    // 创建数据集的路由
    { path: '/datasetstatus1-create', component: _import('modules/visi/create1'), name: 'create1', meta: { title: '创建静态数据集', isTab: false } },
    { path: '/datasetstatus2-create', component: _import('modules/visi/create2'), name: 'create2', meta: { title: '创建动态数据集', isTab: false } },
    { path: '/datasetstatus3-create', component: _import('modules/visi/com/single-file-upLoad'), name: 'create3', meta: { title: '创建单文件数据集', isTab: false } },
    { path: '/datasetstatus4-create', component: _import('modules/visi/com/dir-upLoad'), name: 'create4', meta: { title: '创建文件夹数据集', isTab: false } },


    // 创建算法的路由
    { path: '/normalalg-create', component: _import('modules/alg/algcreate1'), name: 'algcreate1', meta: { title: '创建传统算法', isTab: false } },
    { path: '/intelalg-create', component: _import('modules/alg/algcreate2'), name: 'algcreate2', meta: { title: '创建智能算法', isTab: false } },

    // 创建训练任务的路由
    { path: '/mission-create', component: _import('modules/alg/train-create'), name: 'traincreate', meta: { title: '创建算法任务', isTab: false } },
    { path: '/mission-create-tradition', component: _import('modules/alg/train-create-tradition'), name: 'traincreatetradition', meta: { title: '创建训练任务', isTab: false } },

    // 查看算法版本的路由
    { path: '/versions', component: _import('modules/version/version'), name: 'version', meta: { title: '查看算法版本', isTab: false } },
    { path: '/versions-edit', component: _import('modules/version/version-edit'), name: 'versionedit', meta: { title: '编辑算法版本', isTab: false } },
    { path: '/start-train', component: _import('modules/version/start-train'), name: 'starttrain', meta: { title: '创建训练任务', isTab: false } },
    // 查看文件列表的路由
    { path: '/versions-filetest', component: _import('modules/version/filetest'), name: 'filetest', meta: { title: '查看文件列表', isTab: false } },
    // 查看传统算法文件列表的路由
    { path: '/versions-trafilelist', component: _import('modules/version/trafilelist'), name: 'trafilelist', meta: { title: '查看文件列表', isTab: false } },
    // 编辑文件的路由
    { path: '/versions-editfile', component: _import('modules/version/file-edit'), name: 'fileedit', meta: { title: '编辑文件', isTab: false } },
    // 编辑传统算法文件的路由
    { path: '/versions-edittrafile', component: _import('modules/version/trafile-edit'), name: 'trafileedit', meta: { title: '编辑文件', isTab: false } },
    // 查看模板文件的路由
    { path: '/algs-whatchtemfile', component: _import('modules/alg/templs-file-watch'), name: 'whatchtemfile', meta: { title: '查看模板文件', isTab: false } },
    // 查看算法库文件的路由
    { path: '/algs-whatchmodelfile', component: _import('modules/alg/models-file-watch'), name: 'whatchmodelfile', meta: { title: '查看算法库文件', isTab: false } },
    // 查看训练任务的路由
    { path: '/train-watch', component: _import('modules/alg/train-watch'), name: 'trainwatch', meta: { title: '编辑文件', isTab: false } },
    // 训练任务tensorboard图像对比的路由
    { path: '/train-compare', component: _import('modules/alg/train-compare'), name: 'traincompare', meta: { title: '算法任务tensorboard图像对比', isTab: false } },
    // 数据探测路由
    { path: '/snoop-measure', component: _import('modules/snoop/measure'), name: 'measure', meta: { title: '创建度量标准', isTab: false } },
    { path: '/snoop-job', component: _import('modules/snoop/job'), name: 'job', meta: { title: '创建调度任务', isTab: false } },
    { path: '/visi-previewcsv', component: _import('modules/visi/previewcsv'), name: 'previewcsv', meta: { title: '预览csv', isTab: false } },
    { path: '/design-create', component: _import('modules/visi/design-graph1'), name: '/design-create', meta: { title: '实验设置', isTab: false } }
  ],
  beforeEnter (to, from, next) {
    let token = Vue.cookie.get('Algtoken')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    http({
      url: http.adornUrl('/sys/menu/nav'),
      method: 'get',
      params: http.adornParams()
    }).then(({data}) => {
      if (data && data.code === 0) {
        fnAddDynamicMenuRoutes(data.menuList)
        router.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
        sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
        next({ ...to, replace: true })
      } else {
        sessionStorage.setItem('menuList', '[]')
        sessionStorage.setItem('permissions', '[]')
        next()
      }
    }).catch((e) => {
      console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
      router.push({ name: 'login' })
    })
  }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType (route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: false,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: { name: '404' } }
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

export default router
