import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getCodeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'
import { setTree, listToTree } from '@/utils/validate'
import * as _ from 'lodash'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

function setStaticRoutes (menus, staticRoutes) {
  staticRoutes.forEach(route => {
    const routeIndex = menus.findIndex(
      permissionRoute => permissionRoute.name === route.name
    )
    if (routeIndex > -1) {
      menus[routeIndex] = {
        ...menus[routeIndex],
        component: route.component,
        children: route.children,
      }
    }
  })
}

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getCodeToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          const treeData = await store.dispatch('user/getMenuInfo')
          if (Array.isArray(treeData) && treeData.length) {
            const nd = treeData.filter(item => item.pageconfigurationid)
            store.dispatch('auth/changeAuthArrs', nd)
            // const typeData = setType(treeData, 'up_auth_id', 'auth_id')
            const menusArray = parseMenuItem(nd)
            const treeMenu = listToTree(menusArray, 'up_auth_id', 'auth_id')
            const dataMenu = _.unionBy(treeMenu, 'auth_id')
            const menus = parseMenu(dataMenu)
            store.dispatch('permission/setRoutes', menus)
            router.addRoutes(menus)
            next({ ...to, replace: true })
          } else {
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})


function parseMenuItem (data) {
  //pagetype 1模块  2页面  3按钮 4表格 5树形  6弹窗
  const menus = []
  data.map(item => {
    if (item.pagetype == 'module') {
      menus.push({
        auth_id: item.pageconfigurationid,
        up_auth_id: item.superiorid,
        path: "/" + item.pageroute,
        name: item.pagename,
        meta: {
          title: item.pagename,
          elSvgIcon: item.pageicon || 'el-icon-s-order',
          show_index: item.displayorder,
          qid: item.serviceid,
        },
        component: Layout,
        hidden: item.isdisplay == 1 ? false : true,
      })
    } else if (item.pagetype == 'page') {
      menus.push({
        auth_id: item.pageconfigurationid,
        up_auth_id: item.superiorid,
        path: "/" + item.pageroute,
        name: item.pagename,
        meta: {
          title: item.pagename,
          elSvgIcon: item.pageicon || 'el-icon-s-order',
          show_index: item.displayorder,
          qid: item.serviceid,
          auth_id: item.pageconfigurationid,
          up_auth_id: item.superiorid,
          pagecode: item.pagecode,
          superiorcode: item.pagecode
        },
        component: resolve => require(['@/views' + item.pageaddress], resolve),
        // component: () => import('./views/table/index.vue'),
        hidden: item.isdisplay == 1 ? false : true,
      })
    }
  })

  return menus
}

function parseMenu (arr) {
  const menus = arr
  const newMenus = menus.flat()
  const allMenus = newMenus.length
    ? newMenus.sort((a, b) => a.meta.show_index - b.meta.show_index)
    : []
  // allMenus.map(item => {
  //   item.children = (item.children && item.children.length) ? item.children.sort((a, b) => a.meta.show_index - b.meta.show_index) : item.children
  // })
  allMenus.push({
    path: '/:pathMatch(.*)',
    redirect: '/404',
    hidden: true,
  })
  return allMenus
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
