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

// Axios 全局配置
const httpJson = axios.create()
httpJson.defaults.baseURL = global.baseURL
httpJson.defaults.withCredentials = true
// 添加请求拦截器
httpJson.interceptors.request.use(
  config => {
    if (!global.getLn()) {
      // window.location.href = global.ssoURL
    }
    const header = global.headersJson
    // 无法获取情况下，设置登录 COOKIE
    if (process.__TOKEN__) {
      header.Cookie = 'uid=' + process.__TOKEN__
    }
    config.headers = header
    config.transformRequest = global.transformRequestJSON
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回数据处理
// 返回格式 {code:业务码 , data: 内容 ， msg: 描述}
httpJson.interceptors.response.use(
  response => {
    console.log('----response---响应结果---', response)
    switch (response.data.code) {
      case '-2':
        global.logout()
        // window.location.href = global.ssoURL
        break
      case '1':
        return response.data.data
      default:
        loading.toast.show(response.data.code, response.data.msg)
    }
  },
  error => {
    console.log('--error---', error)
    if (error.response.status === 401) {
      console.log('unauthorized, logging out ...')
    }
    return Promise.reject(error)
  }
)
export default httpJson
