import axios from 'axios'
// import qs from 'qs'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
// 配置跨域请求允许
axios.defaults.headers['Access-Control-Allow-Origin'] = process.env.VUE_APP_BASE_API
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['api-key'] = getToken()
    }
    // if (config.method === 'post') {
    //   config.headers['Content-Type'] = 'multipart/form-data'
    //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    //   config.data = qs.stringify(config.data)
    // }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)
// response interceptor
function loginout() {
  MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
    confirmButtonText: '重新登录',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    store.dispatch('user/resetToken').then(() => {
      location.reload() // 为了重新实例化vue-router对象 避免bug
    })
  })
}
service.interceptors.response.use(
  response => {
    const res = Object.prototype.toString.call(response.data) === '[object Object]' ? response.data : {}
    if (res.status_code === 200 || res.status_code === 201) {
      return res
    } else {
      Message({
        message: res.message || res.info || res.status || 'Error',
        type: 'error',
        duration: 5000
      })
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.status_code === 50008 || res.status_code === 50012 || res.status_code === 50014 || (res.status_code === 401 && res.info === '登录失效')) {
        loginout()
      }
      return Promise.reject(new Error(res.message || res.info || res.status || 'Error'))
    }
  },
  error => {
    // 接口登陆失效status_code401  账号异地登录msg_code1002
    if (Object.prototype.toString.call(error.response) === '[object Object]' && Object.prototype.toString.call(error.response.data) === '[object Object]' && (error.response.data.status_code === 401 && error.response.data.info === '登陆失效') || error.response.data.msg_code === 1002) {
      loginout()
    } else {
      Message({
        message: Object.prototype.toString.call(error.response) === '[object Object]' && Object.prototype.toString.call(error.response.data) === '[object Object]' && error.response.data.info ? error.response.data.info : error,
        type: 'error',
        duration: 5000
      })
    }
    return Promise.reject(error)
  }
)

export default service
