import axios from 'axios'
import { ElNotification } from 'element-plus'
import { getToken, setToken } from './token'

const request = axios.create({
  baseURL: '/api/'
})

request.interceptors.request.use(config => {
  const token = getToken()
  
  if (process.env.NODE_ENV !== 'production') {
    console.log('Request config: ', config)
  }

  if (token) {
    return {
      ...config,
      headers: {
        ...(config.headers || {}),
        'X-Authorization-JWT': token,
      }
    }
  }

  return config
}, error => {
  console.error('Request error')
  console.error(error)
})

request.interceptors.response.use(response => {
  const { data, headers } = response

  const token = headers['X-Authorization-JWT'] || headers['x-authorization-jwt'] || headers['X-AUTHORIZATION-JWT']

  if (token) {
    setToken(token)
  }

  if (data.code === 1000) {
    return data.data
  } else {
    ElNotification.error({message: data.message})
    return Promise.reject(data)
  }
}, error => {
  console.error('Response error')
  console.error(error)
  if (error.response) {
    // 非 200 返回
  }
})

export default request
