/**
 * HTTP 请求 axios dto封装
 */
import axios from 'axios'
import global from './config'
import loading from './loading'

// Axios 全局配置
const httpJson = axios.create()
httpJson.defaults.baseURL = process.env.VUE_APP_BASE_URL
httpJson.defaults.withCredentials = true
// 添加请求拦截器
httpJson.interceptors.request.use(
  config => {
    let tk = localStorage.getItem('accessToken');
    if (tk) {
      config.headers = {
          'Content-Type': 'application/json'
      };
      config.headers.accessToken = tk;
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回数据处理
// 返回格式 {code:业务码 , data: 内容 ， msg: 描述}
httpJson.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case '-2':
        global.logout()
        location.reload();
        break
      case '1':
        return response.data.data
      default:
        loading.toast.show(response.data.code, response.data.msg)
    }
  },
  error => {
    if (error.response.status === 401) {
      console.log('unauthorized, logging out ...')
    }
    return Promise.reject(error)
  }
)
export default httpJson
