import axios from 'axios';
import { getToken, removeToken } from 'service/auth';
import { Message } from 'iview';

let domain = window.CONFIG.url;

// 创建axios实例
export const service = axios.create({
  timeout: 1800000,
  headers: {
    post: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  },
  baseURL: domain
});

export const serviceForm = axios.create({
  timeout: 1800000,
  headers: {
    post: {
      'Content-Type': 'multipart/form-data'
    }
  },
  baseURL: domain
});

// http request 拦截器
let request = function(config) {
  const token = getToken();
  // 判断是否存在token，如果存在的话，则每个http header都加上token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  // 配置取消请求
  if (window._source) {
    config.cancelToken = window._source.token;
  }
  return config;
};

let request_err = function(err) {
  Message.error('请求超时');
  return Promise.reject(err);
};

// http response 拦截器
let response = function(res) {
  const data = res.data;
  const message = data.message || '未知错误';

  if (res.status) {
    switch (res.status) {
      case 200:
        if (data.code !== 0) {
          Message.error(message);
        }
        break;
    }
  }
  return data;
};

let response_err = function(err) {
  if (err.response) {
    const data = err.response.data;
    const message = data.message ? data.message : '未知错误';
    switch (err.response.status) {
      case 401:
        if ([40001, 40002, 40003, 40008].includes(data.code)) {
          // 40001未登录、40002未激活、40003已禁用、40008token未传递
          localStorage.clear();
          removeToken();
          vm.$router.replace({ path: '/login', query: { redirect: encodeURIComponent(vm.$route.fullPath) } });
          Message.error(message);
        }
        break;
      case 500:
        Message.error('服务器忙，请稍后再试');
        break;
      default:
        Message.error(message);
        break;
    }
  }
  return Promise.resolve(err);
};

service.interceptors.request.use(request, request_err);
service.interceptors.response.use(response, response_err);

serviceForm.interceptors.request.use(request, request_err);
serviceForm.interceptors.response.use(response, response_err);

axios.interceptors.response.use(response, response_err);

window.axios = axios;
