import axios from "axios";
import {Message} from "element-ui";
import router from "./router"

// 1、添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('Authorization')) {
      config.headers.Authorization = localStorage.getItem('Authorization');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

// 2、响应拦截器
axios.interceptors.response.use(success => {
  if (success.status && success.status === 200) {
    if (success.data.success === false) {
      success.data.message ? Message.error(success.data.message) : Message.error('操作失败！');
    }
    if (success.data.success === true && success.data.message !== '') {
      Message.success(success.data.message);
    }
    return success;
  }
}, error => {
  let r = null;
  let msg = '';
  let code = error.response.status;
  switch (code) {
    case 400:
      msg = '请求错误！'
      break;
    case 401:
      localStorage.removeItem('Authorization');
      msg = '未授权，请重新登录'
      r = '/login';
      break;
    case 403:
      msg = '拒绝访问'
      break;
    case 404:
      msg = '请求错误,未找到该资源'
      // window.location.href = "/NotFound"
      break;
    case 405:
      msg = '请求方法未允许'
      break;
    case 408:
      msg = '请求超时'
      break;
    case 500:
      if (error.response.data.message !== null) {
        msg = error.response.data.message;
      } else
        msg = '服务器出错!'
      break;
    case 501:
      msg = '服务器无法识别请求方法'
      break;
    case 502:
      msg = '网络错误'
      break;
    case 503:
      msg = '服务不可用'
      break;
    case 504:
      msg = '网络超时'
      break;
    case 505:
      msg = 'http版本不支持该请求'
      break;
    default:
      msg = '未知的错误，请联系管理员！'
      // r = '/login';
  }
  // 在某些特定情况下跳转页面
  if (r !== null) {
    router.replace(r);
  }
  Message.error({message: msg});
});

/**
 * 封装请求
 */
let base = '';
export const postApi = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params
  });
};

// get请求
export const getApi = (url, params) => {
  return axios({
    method: 'get',
    url: `${base}${url}`,
    data: params
  });
};

// put请求
export const putApi = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params
  });
};

// delete请求
export const deleteApi = (url, params) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`,
    data: params
  });
};
