/**
 * HTTP 请求 axios 封装
 */
import Qs from "qs";
import axios from 'axios'
import global from './config'
import loading from './loading'

// Axios 全局配置
const http = axios.create()
http.defaults.baseURL = process.env.VUE_APP_BASE_URL
http.defaults.withCredentials = true
// 添加请求拦截器
http.interceptors.request.use(
  config => {
    let tk = localStorage.getItem('accessToken');
    if (tk) {
      config.headers =  {
          'Content-Type': 'application/x-www-form-urlencoded'
      };
      config.headers.accessToken = tk;
    }
    config.transformRequest =  [
        // 后面数组中的函数必须返回一个字符串，或 ArrayBuffer，或 Stream
        function (data) {
            return Qs.stringify(data);
        }
    ]
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回数据处理
// 返回格式 {code:业务码 , data: 内容 ， msg: 描述}
http.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 => {
    return Promise.reject(error)
  }
)
export default http
