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

// 自定义 Axios 全局配置

const instance = axios.create()
instance.defaults.baseURL = global.baseURL
instance.defaults.withCredentials = true
// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    if (!global.getLn()) {
      const windowHref = window.location.href
      if (windowHref.indexOf('qrCode') === -1) {
        window.location.href = global.ssoURL
      }
    }
    config.headers = global.headersJson
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回数据处理
// 返回格式 {code:业务码 , data: 内容 ， msg: 描述}
instance.interceptors.response.use(
  response => {
    console.log(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 => {
    if (error.response.status === 401) {
      console.log('unauthorized, logging out ...')
    }
    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 const https = instance
