import Vue from 'vue'
import axios from 'axios' // 引入axios

const service = axios.create({
  // baseURL: process.env.API_BASE_URL, // 公共请求地址
  timeout: 6000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use((config) => {
  // Vue.ls本地储存token
  // const token = Vue.ls.get(ACCESS_TOKEN)
  // const locale = Vue.ls.get(LANG)
  var access_token = ''
  if (JSON.parse(localStorage.getItem("tokenkey"))) {
    access_token = JSON.parse(localStorage.getItem("tokenkey")).access_token
  }

  if (access_token) {
    // 添加token请求头
    config.headers[AUTHORIZATION] = 'bearer' + access_token
  }
  config.headers.Locale = locale
  return config
}, error => Promise.reject(error))

// 响应拦截器
service.interceptors.response.use(
  response => {
    hideLoading();
    if (response.status === 200) {
      return response.data;
    } else {
      Promise.reject();
    }
  },
  error => {
    hideLoading();
    if (error.response.status === 401) {
      // if(doms == undefined){
      message({
        type: "error",
        message: "您的token已过期，请重新登录！"
      })
      // refreshTokenRequst('',function(data){
      //   console.log(data)
      // })
      setTimeout(function() {
        redirectLogin();
      }, 500)
      // }
    } else if (error.response.status === 400 && error.response.data.message == "Username or password is incorrect") {
      message({
        type: "error",
        message: "账号或密码错误"
      })
    }else{			
			  message({
			    type: "error",
			    message: error.response.data.message
			  })			
		}
    return Promise.reject(error.response.data);
  })

// as关键字设置别名
export {
  service as axios
}
