import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

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

const whiteList = ['/login','/wxTest','/dataBoardNew'] // no redirect whitelist

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

  const hasToken = store.getters.token
  let loginType = window.topU ? window.topU.U.UF.Cookie.get("cocoroboLoginType") : window.parent.U ? window.parent.U.UF.Cookie.get("cocoroboLoginType") : '';
  let cocorobo = window.topU ? window.topU.U.UF.Cookie.get("cocorobo") : window.parent.U ? window.parent.U.UF.Cookie.get("cocorobo") : '';
  if (hasToken && cocorobo && loginType != 1) {
    if (to.path === '/login') {
      console.log('111111111111');
      const userinfo = store.getters.userinfo && Object.keys(store.getters.userinfo).length > 0
      console.log(userinfo);   
      // 如果已登录，重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const userinfo = store.getters.userinfo && Object.keys(store.getters.userinfo).length > 0
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单中，直接进入
        next()
      }else if (userinfo) {
        next()
      } else {
        try {
          // 获取用户信息
          const data = await store.dispatch('user/getInfo')
          await store.commit('user/SET_USERINFO', data)

          await store.dispatch('user/getschPerInfo')

          let mergedList =  [
						"3823a6a5-1b6e-11f0-a66a-005056924926",
						"292e34dc-1b6e-11f0-a66a-005056924926",
						"21d6b367-1b6e-11f0-a66a-005056924926",
						"1a1a172d-1b6e-11f0-a66a-005056924926",
						"1197f86b-1b6e-11f0-a66a-005056924926",
						"f235659b-1b6d-11f0-a66a-005056924926",
						"d87b62d3-1b6d-11f0-a66a-005056924926",
						"c25ea59b-1b6d-11f0-a66a-005056924926",
					]

          if(data.type == 1 && data.role == 1 && data.rrole == 1 && mergedList.includes(data.org)){
            next({ path:'/KanBan', replace: true })
          }else {
            next({ ...to, replace: true })
          }
        } catch (error) {
          // 如果获取用户信息失败，重置 token 并重定向到登录页面
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没有 token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单中，直接进入
      next()
    } else {
      // 其他没有权限访问的页面重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

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