import router from './router'
import store from './store'
import { Message } from '@zjlib/element-ui2'
import { getToken } from '@/utils/auth' // get token from cookie
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'
import RouterView from '@/views/routerView.vue'
import IframeView from '@/views/iframeView.vue'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const _import = require('./router/_import_' + process.env.NODE_ENV) // 获取组件的方法
const whiteList = ['/login'] // no redirect whitelist
const lay = {
  path: '/',
  component: Layout,
  children: []
}

import { pages } from './settings'

// 递归找最后一级页面
function getc(obj) {
  if (!obj.children || !obj.children.length) {
    return obj
  } else {
    return getc(obj.children[0])
  }
}

router.beforeEach(async (to, from, next) => {

  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/getInfo')
          await store.dispatch('user/getRouter')
          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }

          var userInfo = JSON.parse(localStorage.getItem('greemall_user'))
          var moduleObj = {
            // 辅材配件
            auxiliaryFittings: userInfo.moduleMaterialPart,
            // 维保
            engineeringMaintenance: userInfo.moduleWb,
            // 延保
            valueAddedService: userInfo.moduleYb,
          }

          // 设置路由
          lay.children = []
          for (var route of store.getters.menus) {
            if (moduleObj[route.code] !== false) {
              lay.children.push(...buildRoute(route))
            }
          }
          lay.redirect = getc(lay).path
          router.addRoutes([lay])
          global.antRouter = []
          for (var route of store.getters.menus) {
            if (moduleObj[route.code] !== false) {
              global.antRouter.push(...buildRoute(route, '', false))
            }
          }
          next({
            ...to,
            replace: true
          })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next('/login')
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

function buildRoute(route, parentUrl = '', bool = true) {
  const { url, moduleName, icon, moduleId, code, type, fullUrl, status, isCache } = route
  var item = {}
  var itemparent = null
  item.path = ~[3, 4].indexOf(type) ? fullUrl : parentUrl + url
  item.name = ~[3].indexOf(type) ? fullUrl : code
  item.type = type
  item.status = status
  item.meta = {
    url,
    title: moduleName,
    icon: icon,
    moduleId,
    status: status,
    isCache: isCache
  }
  if (route.children && route.children.length) {
    if (type == 2) {
      var childrenPage = (route.children || []).filter(item => item.type == 2)
      if (childrenPage.length) {
        itemparent = {
          ...item,
          status: false,
          meta: {
            url: `/${code}_children`,
            isCache: 0,
            status: false,
            roles: [],
            roleItems: []
          },
          component: RouterView,
          children: []
        }
        childrenPage.map(child => {
          itemparent.children.push(...buildRoute(child, `${parentUrl}/${code}_children`, bool))
        })
      }

      try {
        item.component = _import(`${fullUrl}/index`)
        item.component.name = item.name
      } catch (e) {
        console.log(e)
      }

      const roles = []
      const roleItems = []
      for (var role of route.children.filter(item => item.type == 3)) {
        roleItems.push({
          code: role.code,
          moduleName: role.moduleName
        })
        roles.push(role.code)
      }
      item.meta.roles = roles
      item.meta.roleItems = roleItems

      if (!pages.find(ite => ite.path === item.path)) {
        item.path = `${item.path}${bool?'/:pageName?/:pageType?/:pageCode?/:pagePam?':''}`
        pages.push(item)
      }

    } else if (type == 1) {
      item.component = RouterView
      item.children = []
      route.children.filter(itema => itema.type !== 3).map(child => {
        item.children.push(...buildRoute(child, item.path, bool))
      })
    }
  } else {
    if (type == 4) {
      item.component = IframeView
      if (!pages.find(ite => ite.path === item.path)) {
        pages.push(item)
      }
    } else if (type == 2) {
      try {
        item.component = _import(`${fullUrl}/index`)
        item.component.name = item.name
        if (!pages.find(ite => ite.path === item.path)) {
          item.path = `${item.path}${bool?'/:pageName?/:pageType?/:pageCode?/:pagePam?':''}`
          pages.push(item)
        }

      } catch (e) {
        console.log(e)
      }
    }
  }
  return itemparent ? [item, itemparent] : [item]
}
