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

//获取当前url

var URL = process.env.VUE_APP_BASE_API
console.log(URL,'===========URL')
console.log(process.env.VITE_DOMAIN,'===========VITE_DOMAIN')
console.log(this.$DOMAIN,'======this.$DOMAIN=====')
//获取当前url
if(URL.indexOf('/')==0 && URL.length==1){
  URL= window.location.protocol + "//"+window.location.host+URL
  console.log(URL,'===========URL')
}
  const service = axios.create({
    baseURL: URL, // 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(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      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 => {
    if (error.response.data.code === 10000) {
      MessageBox.confirm('你已经注销登陆,你可以取消或重新登陆', '确认注销', {
        confirmButtonText: '重新登陆',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    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.response.data.errors[0], type: 'error', duration: 5 * 1000 })
    //   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
