import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { SERVER_URL } from '@/utils/configs'

//获取当前url

// var aa = process.env.VUE_APP_BASE_API
var aa = SERVER_URL
console.log(aa,'===')
//获取当前url
// if(aa.indexOf('/')==0 && aa.length==1){
//   // aa= window.location.protocol + "//"+window.location.host+aa
//   aa= window.location.protocol + "//"+window.location.host+aa
// }
  const service = axios.create({
    baseURL: aa, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 60000 ,// request timeout
  })
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'  //此处是增加的代码,设置请求头的类型
    if (process.env.VUE_APP_BASE_API !== '/dev-api') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
      config.withCredentials = false
    }

    if (store.getters.token) {
      if (process.env.VUE_APP_BASE_API === '/dev-api') {
        config.headers['X-Token'] = getToken()
      } else {
        config.headers['Authorization'] = 'Bearer ' + getToken()
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {

    // console.log(res)
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      console.log(response.errors,'res')
      // return
      // Message({ message: '操作失败1', type: 'error', duration: 5 * 1000 })
      if (res.code === 10000 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('你已经注销登陆,你可以取消或重新登陆', '确认注销', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if (res.code === 20002) {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      if (res.code === undefined) {
        return res
      } else {
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    // console.log('err===============' +  JSON.stringify(error.response)) // for debug
    let config = error.config
    if (!config) {
      Message({ message: error.msg, type: 'error', duration: 5 * 1000 })
      return Promise.reject(error)
    }
    // 设置请求超时次数
    config.__retryCount = config.__retryCount || 0
    if (config.__retryCount >= 3) {
      // Message({ message:error.message, type: 'error', duration: 5 * 1000 })
      Message({ message:'操作失败'+error.response.data.errors[0], type: 'error', duration: 5 * 1000 })
      // Message.error((error && error.data && error.data.msg) || '请求超时')
      return Promise.reject(error)
    }
    config.__retryCount += 1
    let backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve()
      }, config.retryDelay || 1)
    })
    return backoff.then(() => {
      return service(config)
    })
    // Message({
    //   message: "操作错误!"+error.response.data.errors[0],
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // return Promise.reject(error)
  }
)

export default service