import axios from 'axios'
import {history} from './router.config'

const replaceLogin = () => history.replace('/login')
let token = sessionStorage.getItem('token')
token || replaceLogin()


axios.defaults.baseURL = '/api/'
axios.interceptors.request.use(request => {
  if (request.url === '/login' || request.url === '/logout') {
    request.baseURL = process.env.NODE_ENV === 'development' ? '/test': ''
  }

  if (!token && request.url !== '/login') {
    replaceLogin()
    return Promise.reject('1')
  }

  request.headers.Authorization = token
  return request
})

axios.interceptors.response.use(response => {
  if (response.data.code === 401) {
    sessionStorage.removeItem('token')
    token = null;
    replaceLogin()
  }

  return response
})

export const setToken = (t: any) => {
  token = t
  sessionStorage.setItem('token', t)
}


export const removeToken = (t: any) => {
  token = null
  sessionStorage.removeItem('token')
}

export default axios