import axios from 'axios'
import { Notification, MessageBox } from 'element-ui'
// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:9091", // api 的 base_url
  timeout: 100000 // 请求超时时间
})
let dinuo_a="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMTAwMTkiLCJleHAiOjE2MDY4NjY2MDQsImlhdCI6MTYwMzI2NjYwNH0.MtiPeogLKnrmVl5BLKkxYQBauqEOl0zIinO1rHgz6MVdmqAif2FytQfopkstlunHrCkI7jAQ2MXD0kah26UbYQ"
let admin_a="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIwMTAwMTkiLCJleHAiOjE2MDY4NjY2MDQsImlhdCI6MTYwMzI2NjYwNH0.MtiPeogLKnrmVl5BLKkxYQBauqEOl0zIinO1rHgz6MVdmqAif2FytQfopkstlunHrCkI7jAQ2MXD0kah26UbYQ"
// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = window.commonApi.getTokenInfo()
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(

  response => {
    const code = response.status
    if (code < 200 || code > 300 ||response.data.code !== 200) {
      Notification.error({
        title: response.data.message
      })
      return Promise.reject('error')
    } else {
      return response.data.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('timeout')>=0) {
        Notification.error({
          title: '请求超时',
          duration: 2500
        })
        return Promise.reject(error)
      }
	  if(error.toString().indexOf("Network Error")>=0){
		  // MessageBox.confirm(
		  //   '登录状态过期了哦，您可以继续留在该页面，或者重新登录',
		  //   '系统提示',
		  //   {
		  //     confirmButtonText: '重新登录',
		  //     cancelButtonText: '取消',
		  //     type: 'warning'
		  //   }
		  // ).then(() => {
		  //   store.dispatch('LogOut').then(() => {
		  //     location.reload() // 为了重新实例化vue-router对象 避免bug
		  //   })
		  // })
	  }
    }
    if (code === 401) {
      MessageBox.confirm(
        '登录状态过期了哦，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code === 403) {
      router.push({ path: '/401' })
      return Promise.reject(error)
    } else {
      const errorMsg = error.response.data.message
      if (errorMsg !== undefined) {
        Notification.error({
          title: errorMsg,
          duration: 2500
        })
      }
      return Promise.reject(error)
    }
  }
)
export default service
