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 { getToken } 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 = getToken()

  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')
          store.dispatch('auth/changeAuthArrs', treeData)
          // const typeData = setType(treeData, 'up_auth_id', 'auth_id')
          const menusArray = parseMenuItem(treeData)
          const treeMenu = listToTree(menusArray, 'up_auth_id', 'auth_id')
          const dataMenu = _.unionBy(treeMenu, 'auth_id')
          const menus = parseMenu(dataMenu)

          if (PLATFROM_CONFIG.hasStaticRoutes) {
            const staticRoutes = await (await import('@/router/routes/routes-file-temp')).default
            setStaticRoutes(menus, staticRoutes)
          }

          store.dispatch('permission/setRoutes', menus)
          router.addRoutes(menus)
          next({ ...to, replace: true })
        } 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) {
  const menus = []
  data.map(item => {
    if (item.auth_type == 1) {
      menus.push({
        auth_id: item.auth_id,
        up_auth_id: item.up_auth_id,
        path: item.route_info,
        name: item.auth_ident,
        meta: {
          title: item.auth_name,
          elSvgIcon: item.show_icon ?? 'Fold',
          show_index: item.show_index,
          qid: item.queryTemplateID,
        },
        component: Layout,
        hidden: !item.is_show,
      })
    } else if (item.auth_type == 2) {
      menus.push({
        auth_id: item.auth_id,
        up_auth_id: item.up_auth_id,
        path: item.route_info,
        name: item.auth_ident,
        meta: {
          title: item.auth_name,
          elSvgIcon: item.show_icon ?? 'Fold',
          show_index: item.show_index,
          qid: item.queryTemplateID,
          auth_id: item.auth_id,
          up_auth_id: item.up_auth_id,
        },
        component: resolve => require(['@/views' + item.file_link], resolve),
        // component: () => import('./views/table/index.vue'),
        hidden: !item.is_show,
      })
    }
  })

  return menus
}

function setType (arr, parentKey, key) {
  const datas = []
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i][key] == arr[j][parentKey]) {
        if (arr[j].auth_type == 3) {
          datas.push(arr[j])
          arr[i].other = datas
        }
      }
    }
  }
  return arr
}

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,
  })
  if (allMenus[0].children && allMenus[0].children.length) {
    allMenus[0].redirect = allMenus[0].children[0].path
    allMenus[0].path = '/'
  } else {
    allMenus[0].redirect = allMenus[0].path
    allMenus[0].path = '/'
  }
  return allMenus
}

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