// import Vue from 'vue'
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 { loadMicroModule } from '@/utils/util'
// import { promiseLimit, loadMicroModule } from '@/utils/util'
// import { modules, microModules } from './modules'
// import { Loading } from 'element-ui'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

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

// let isAddRoutes = false
let componentLoadFlag = false
// const isAddDeeUi = false
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // const m = localStorage.getItem('moduleName')
  // if (m) {
  //   to.query.appName = m
  // }
  sessionStorage.setItem('lasterPageRouter', from.fullPath)
  /* has no token*/
  const hasToken = getToken()
  if (!componentLoadFlag) {
    const components = await window.System.import('./dee-ui/dee_ui.js?queryKey=' + process.env.QUERY_KEYS) // eslint-disable-line
    try {
      componentLoadFlag = true
      components.default.init()
    } catch {
      //
    }
  }
  if (to.query.showMenu === 'false' || to.query.showMenu === false) {
    store.dispatch('app/closeSideBar', { withoutAnimation: false })
  }
  if (!hasToken) {
    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()
    }
  } else {
    document.title = getPageTitle(to.meta.title)
    const PromiseList = []
    const hasWorkSpacesList = store.getters.workSpacesList && store.getters.workSpacesList.length > 0
    if (!hasWorkSpacesList) {
      PromiseList.push(store.dispatch('menu/setWorkSpacesList'))
      // await store.dispatch('menu/setWorkSpacesList')
    }
    const userInfo = store.getters.userInfo
    if (!userInfo) {
      PromiseList.push(store.dispatch('user/getUserInfo'))
      // store.dispatch('user/getUserInfo')
    }
    const hasAllApp = store.getters.allApp && store.getters.allApp.length > 0
    if (!hasAllApp) {
      PromiseList.push(store.dispatch('menu/setAllApp'))
      // await store.dispatch('menu/setAllApp')
    }
    const hasTheme = store.getters.theme
    if (!hasTheme) {
      PromiseList.push(store.dispatch('theme/getTheme'))
      // await store.dispatch('theme/getTheme')
    }
    const hasMenu = store.getters.menusData && store.getters.menusData.length > 0
    if (!hasMenu) {
    // 重新调用 判断用户菜单权限
      PromiseList.push(store.dispatch('menu/getMenus'))
      // await store.dispatch('menu/getMenus')
    }
    // 首次注册routes、加载模块
    const routesObj = store.getters.routesObj
    if (!routesObj) {
      PromiseList.push(store.dispatch('routes/registerRoutes'))
      // await store.dispatch('routes/registerRoutes')
    }
    // store.dispatch('tagsView/setCachedMenuPages')
    // const modelLoadingInstance = Loading.service({
    //   fullscreen: true,
    //   background: 'rgba(0, 0, 0, 0.0)'
    // })
    if (PromiseList.length) {
      await Promise.all(PromiseList)
    }
    const currentModuleRoute = to.query.redirect ? findModuleRoute(to.query.redirect, to.query) : findModuleRoute(to.path, to.query)
    if (store.getters.routeMenuData[to.path] && !store.getters.routeMenuData[to.path].permFlag) {
      next({ path: '/404', replace: true })
    } else if (
      currentModuleRoute &&
      !Vue.prototype.$loadModule.hasOwnProperty(currentModuleRoute) // eslint-disable-line
    ) {
      await loadMicroModule(currentModuleRoute)
      next({ ...to, replace: true })
    } else {
      // 判断画布页面是否注册路由
      // 画布配置的页面路由都会以 /page开头
      if (!to.name && to.path.startsWith('/page/')) {
        const pageKey = to.path.split('/')[2] // 页面key值
        // 获取页面信息、包括布局信息
        const pageInfo = await store.dispatch('layout/getPageInfo', pageKey)
        router.addRoutes([
          {
            path: to.path,
            name: 'canvasPage' + pageKey,
            meta: { title: '中心页面', keepAlive: pageInfo && !pageInfo.noCached },
            component: {
              template: `<dee-as-page page-key="${pageKey}"></dee-as-page>`,
              name: 'canvasPage' + pageKey
            },
            hidden: true
          }
        ])
        next({ ...to })
      } else if (!to.name && to.path.startsWith('/configured-page/')) { // 加载通用的自定义组件
        const pathArray = to.path.split('/')
        const pathFour = pathArray[4] ? decodeURIComponent(pathArray[4]).split('/').slice(-2).join('-').split('-').map(el => { return el.charAt(0).toUpperCase() + el.slice(1) }).join('') : ''

        /*
          pathArray[2]:页面所在的微前端工程
           pathArray[3]:页面的路径
           pathArray[4]:对象的id
        */
        router.addRoutes([
          {
            path: to.path,
            name: 'configuredPage' + pathArray[2] + pathArray[3] + pathFour,
            meta: { title: '配置页面', keepAlive: true },
            component: {
              template: `<dee-configured-page page-type="${pathArray[2]}" server-name="${pathArray[3]}" self-component-path="${pathArray[4]}" id="${pathArray[5] || ''}"></dee-configured-page>`,
              name: 'configuredPage' + pathArray[2] + pathArray[3] + pathFour
            },
            hidden: true
          }
        ])
        next({ ...to })
      } else {
        // if (to.meta.keepAlive && store.getters.visitedViews) {
        //   for (const key in store.getters.visitedViews) {
        //     const findHasRoute = store.getters.visitedViews[key].find(el => {
        //       return el.path === to.path
        //     })
        //     if (findHasRoute) {
        //       if (findHasRoute.fullPath !== to.fullPath) {
        //         store.dispatch('tagsView/delCachedView', to)
        //       }
        //       break
        //     }
        //   }
        // }
        next()
      }
    }
  }
})

function findModuleRoute(path, query) {
  if (path === '/') return null
  let result = null

  const module = path.split('/')[1]

  if (module && store.getters.routesObj[module]) {
    result = module
    // const currentRoute = store.getters.routesObj[module].find((r) => r.route === path)
    // if (currentRoute) {
    //   result = currentRoute
    // }
  }
  if (store.getters.menusObj) {
    if (store.getters.menusObj[path]) {
      store.dispatch('menu/activeModel', {
        appId: query.menuRootAppId || store.getters.menusObj[path].menuRootAppId || store.getters.menusObj[path].dxApplicationId,
        pageInfo: store.getters.menusObj[path]
      })
    }
    //  else if (path === '/dee-task-center/workflow/task-center/home') {
    //   store.dispatch('menu/activeModel', {
    //     appId: 'todoTask',
    //     pageInfo: {
    //       path: '/dee-task-center/workflow/task-center/home'
    //     }
    //   })
    // }
  }
  return result
}

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