import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { tansParams } from '@/utils/zk'
const service = axios.create({
  // baseURL: httpurl.devServer.proxy['/api'].target+'/api',
  baseURL:process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// request interceptor
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
service.interceptors.request.use(
  config => {
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      console.log(config,'config.params')
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    if (store.getters.token) {
      config.headers['Authorization'] = store.getters.token
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 1) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    }else if(res.code === -3){
      Message({
        message: '登录过期!',
        type: 'error',
      })
      window.location.href = '/login'
    }
     else {
      return res
    }
  },

  error => {
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
