/* 全局路由钩子 */
import router from '@/router'
import store from '@/store'

router.beforeEach((to, from, next) => {
  // console.log(to)
  if (from.name || to.path === '/404') {
    next()
  } else if (to.path === '/') {
    next({ path: '/list', query: to.query })
  } else {
    const { id, uin } = to.query
    /* 打开加载状态 */
    store.commit('SET_ISPAGELOADING', true)
    /* 预设uin值为地址栏uin */
    store.commit('SET_UIN', uin)
    /* 如不存在id和uin信息，则拒绝访问 */
    if (id && uin) {
      /* 拉取抽奖（场次）信息 */
      store.dispatch('getSessionList', { id, uin }).then(res => {
        // 判断是否自动进入抽奖页
        if (to.path === '/list' && res.data.playConfig.length < 2) {
          router.replace({ path: '/index', query: { ...to.query, sessionId: res.data.playConfig[0].id } })
          return
        }
        next()
      })
      return
    }
    next({ path: '/404' })
  }
})
