import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import Cookies from 'js-cookie'
import { getToken } from '@/utils/auth'
import { loginOut } from '@/api/user'

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

const whiteList = ['/login', '/resetpassword', '/help', '/echarts', '/login2'] // no redirect whitelist

// eslint-disable-next-line prettier/prettier
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title

  // determine whether the user has logged in
  // const hasToken = getToken()
  const hasToken = store.getters.id || getToken()
  const isWeChat = Cookies.get('isWeChat')
  if (to.query.courseid !== '' && to.query.courseid !== undefined) {
    console.log(to.query.courseid)
    await store.commit('SET_COURSEID', to.query.courseid)
  }
  if (to.query.testid !== '' && to.query.testid !== undefined) {
    await store.commit('SET_TESTID', to.query.testid)
  }
  const shareCourseId =
    window.location.href.indexOf('?shareCourseId=') !== -1
      ? window.location.href.split('?shareCourseId=')[1].toString()
      : ''
  if (shareCourseId) {
    await store.commit('SET_SHARECOURSEID', shareCourseId)
  }
  if (hasToken) {
    await store.commit('user/SET_ID', hasToken)
    if (to.path === '/login' || to.path === '/login2') {
      // if is logged in, redirect to the home page
      store.commit('user/SET_ID', hasToken)
      if (isWeChat === '1') {
        next({ path: '/' })
      } else {
        const queryParams = new URLSearchParams({
          redirect_uri: to.query.url,
          // 可以添加其他需要的参数
          timestamp: Date.now().toString()
        }).toString()
        const redirect_uri = to.query.url ? encodeURIComponent(queryParams) : ''
        const isApp = to.query.isApp ? to.query.isApp : '2'
        if (isApp === '2' && redirect_uri) {
          window.location.href = `weixin://dl/business/?appid=wxf8a72764a38a40b2&path=pages/index/index&query=${redirect_uri}`
        } else if (redirect_uri) {
          window.location.href = redirect_uri
        } else {
          next({ path: '/appStoreCopy' })
        }
      }
      NProgress.done()
    } else {
      const userinfo = store.getters.userinfo && Object.keys(store.getters.userinfo).length > 0
      console.log('store.getters', store.getters)
      console.log('store.getters.userinfo', store.getters.userinfo)
      console.log('isWeChat', isWeChat)
      console.log('userinfo', userinfo)
      // console.log('to', {...to} )
      if (userinfo) {
        console.log(store)
        if (isWeChat === '1' || to.path === '/appStoreCopy' || to.path === '/searchL' || to.path === '/userInfoPage') {
          next()
        } else if (isWeChat === '2') {
          const courseId = store.getters.courseId
          const testId = store.getters.testId
          const shareCourseId = store.getters.shareCourseId
          if (courseId || testId || shareCourseId) {
            Cookies.set('isWeChat', '1')
            loginOut().then(async res => {
              await store.dispatch('user/logout')
              await store.commit('user/SET_ID', '')
              next(`/login2?redirect=${to.path}`)
            })
          } else {
            Cookies.set('isWeChat', '2')
            next('/appStoreCopy')
          }
        } else {
          next()
        }
        NProgress.done()
      } else {
        try {
          // 获取用户信息
          console.log(store)
          const data = await store.dispatch('user/getInfo')
          await store.commit('user/SET_USERINFO', data)
          const courseId = store.getters.courseId
          const testId = store.getters.testId
          const shareCourseId = store.getters.shareCourseId
          await store.commit('SET_TESTID', '')
          await store.commit('SET_COURSEID', '')
          await store.commit('SET_SHARECOURSEID', '')
          // // 根据角色生成可访问的路线图
          if (courseId) {
            next({ ...to, query: { courseid: courseId, userid: hasToken }, replace: true })
          } else if (testId) {
            next({ ...to, query: { courseid: testId, userid: hasToken }, replace: true })
          } else if (shareCourseId) {
            next({
              path: '/courseDetail',
              query: { courseid: shareCourseId, urlType: 1, userid: hasToken },
              replace: true
            })
          } else {
            next({ ...to, replace: true })
          }
        } catch (error) {
          // remove token and go to login page to re-login
          // await store.dispatch('user/resetToken')
          // Notify({ type: 'danger', message: error || '发生异常' })
          console.error(error)
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // next()
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      const courseId = store.getters.courseId
      const testId = store.getters.testId
      const shareCourseId = store.getters.shareCourseId

      // 检查是否是微信授权回调
      if (courseId || testId || shareCourseId) {
        next(`/login2?redirect=${to.path}`)
        NProgress.done()
      } else if (window.location.href.indexOf('login') !== -1 && window.location.href.indexOf('login2') === -1) {
        // 微信授权回调，允许访问
        next('/login')
        NProgress.done()
      } else {
        //   // other pages that do not have permission to access are redirected to the login page.
        next(`/login`)
        NProgress.done()
      }
    }
  }
})

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