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

// Axios 全局配置
const http = axios.create()
http.defaults.baseURL = global.baseURL
http.defaults.withCredentials = true
// 添加请求拦截器
http.interceptors.request.use(
  config => {
    if (!global.getLn()) {
      window.location.href = global.ssoURL
    }
    const header = global.headers
    // 无法获取情况下，设置登录 COOKIE
    if (process.__TOKEN__) {
      header.Cookie = 'uid=' + process.__TOKEN__
    }
    config.headers = header
    config.transformRequest = global.transformRequest
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回数据处理
// 返回格式 {code:业务码 , data: 内容 , msg: 描述}
http.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)
    return Promise.reject(error)
  }
)
http.open = function(url, data, target) {
  const form = document.createElement('form')
  form.action = global.baseURL + url
  form.method = 'post'
  form.target = target || '_self'
  if (data) {
    for (const key in data) {
      const input = document.createElement('textarea')
      input.name = key
      input.value =
        typeof data[key] === 'object' ? JSON.stringify(data[key]) : data[key]
      form.appendChild(input)
    }
  }
  form.style.display = 'none'
  document.body.appendChild(form)
  form.submit()
}

export default http
