import axios from 'axios'
import utils from "utils/utils.js";
import {
  Message
} from 'element-ui';

axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
axios.defaults.shouldRetry = (error) => true;

const http = axios.create({
  timeout: 50000
})
// http request 拦截器
// 每次请求都为http头增加Authorization字段，其内容为Token
http.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json; charset=UTF-8'
    const token = utils.getCookie("token");
    if (token) {
      config.headers.common['Authorization'] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// http response 拦截器
http.interceptors.response.use(response => {
  let status = response.status
  if (status === 200) {
    if (response.data.code === -9) {
      utils.delCookie("token");
      localStorage.removeItem("initVuex");
      location.href = "/login"
    } else {
      return response.data
    }

  }

  return Promise.reject(data)
}, err => {
  var config = err.config;

  // 如果配置不存在或未设置重试选项，则拒绝
  if (!config || !config.retry) return Promise.reject(err);

  // 设置变量以跟踪重试计数
  config.__retryCount = config.__retryCount || 0;

  // 检查我们是否已经将重试的总数最大化
  if (config.__retryCount >= config.retry) {
    // Reject with the error
    return Promise.reject(err);
  }

  // 增加重试计数
  config.__retryCount += 1;

  // Create new promise to handle exponential backoff
  var backoff = new Promise(function (resolve) {
    setTimeout(function () {
      resolve();
    }, config.retryDelay || 1);
  });

  // Return the promise in which recalls axios to retry the request
  return backoff.then(function () {
    return axios(config);
  });
})

export default http
