import axios from 'axios'
import Router from '@/router/index';
import { getToken, removeToken } from '@/libs/auth'
import loading from '@/libs/loading'
import permission from '@/libs/permission'
import { Notify } from 'quasar'

// create an axios instance
const service = axios.create({
  baseURL: '/manager', // api的base_url
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (!permission.check(config)) {
    Notify.create({
      message: "No request permission"
    })
    throw "403"
  }
  config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  loading.show(config)
  let token = getToken()
  if (token) {
    config.headers['Authorization'] = '' + token// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    loading.hide(response.config)
    const res = response.data;
     if (res.code == 200) {
      return response
    }

    if (res.code == 401) {
      Notify.create({
        message: "当前用户已在其它地点登录，页面跳转登录页！"
      })
      if(res.code==401){
          removeToken();
          setTimeout(() => {
            Router.push({
              name: "login"
            });
          }, 1000)
      }
      return Promise.reject('error');
    } else {
       Notify.create({
        message: res.data || '系统错误'
      })
      return Promise.reject('error');
    }
  },
  error => {
    loading.hide(error.config)
    if (error.response && error.response.status === 401) {
      removeToken();
      if (error.config.url.indexOf("logout") === -1) {
        Notify.create({
          message: "登录信息已过期,请重新登录!"
        })
      }
      setTimeout(() => {
        Router.push({
          name: "login"
        });
      }, 1000)

    } else if (error.response && error.response.status === 500) {
      Notify.create({
        message: '系统错误!',
        position: 'bottom-right'
      })
    } else if (error.message.indexOf("timeout")>-1) {
      Notify.create({
        message: '请求服务器超时!',
        position: 'bottom-right'
      })
    }
    else if (error == "403") {

    } else {
      Notify.create({
        message: '网络错误!',
        position: 'bottom-right'
      })
    }
    return Promise.reject(error)

  })

export default service



