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

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

export const baseURL = process.env.NODE_ENV === 'development' ? '/api' : '/api'

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

  if (!token && request.url !== '/admin/login') {
    replaceLogin()
    return Promise.reject('未登录无法请求')
  }

  request.headers.token = token
  return request
})

axios.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.status === 5001 || response.data.code === 5001) {
    sessionStorage.removeItem('token')
    token = null;
    replaceLogin()
    throw new Error('当前用户未登录')
  }

  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