import axios from 'axios'
import router from './router'

var root = process.env.VUE_APP_BASE_API

axios.interceptors.request.use(config => {
  // --请求之前重新拼装url--
  config.url = root + config.url
  if (
    config.url === '/url/v1/login/reg' ||
    config.url === '/url/v1/login/login'
  ) {
    // 如果是登录和注册操作，则不需要携带header里面的token
  } else {
    if (localStorage.token) {
      config.headers = {
        Authorization: localStorage.token
      }
    }
  }
  return config
})

axios.interceptors.response.use(
  response => {
    if (response.data.errno === 999) {
      router.replace('/')
      console.log('token过期')
    }
    return response
  },
  error => {
    return error
  }
)

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (localStorage.token) {
      // 获取当前的token是否存在
      console.log('token存在')
      next()
    } else {
      alert('请先登录！')
      console.log('token不存在')
      next({
        path: '/login', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 如果不需要权限校验，直接进入路由界面
    next()
  }
})

export default axios
