/*eslint-disable*/
import axios from 'axios';
import store from '../store/index';
import router from '../router';
import { Message } from 'element-ui';
// axios 配置
// axios.defaults.timeout = 5000;
// let adminUrl = 'http://www.gicdev.com'
// let adminUrl = process.env.NODE_ENV === 'production' ? '':'localhost:8080/'
let adminUrl = process.env.NODE_ENV === 'production' ? '' : 'http://www.gicdev.com';

let request;

request = axios.create({
  baseURL: adminUrl,
  withCredentials: true, //跨域凭证
  timeout: 30000,
  headers: {
    //  'Content-Type': 'application/x-www-form-urlencoded'
    sign:''
    },
});

// http request 拦截器
request.interceptors.request.use(
  config => {
    config.params = {
      requestProject: 'integral-mall',
      ...config.params
    };
    if (store.state.token) {
      config.headers.Authorization = `token ${store.state.token}`;
    }
    if(localStorage.getItem('sign')) {
      config.headers.sign = localStorage.getItem('sign')
    }else{
      config.headers.sign = ''
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// http response 拦截器
request.interceptors.response.use(
  response => {
    const { data, config } = response;
    let err;
    const { errorCode } = data;
    switch (errorCode) {
      case 0:
        return response;
      case 401:
        Message({
          message: '登录失效',
          type: 'error',
        });
        window.location.href = window.location.origin + '/gic-web';
        break;
      case undefined:
        break;
      default:
        Message({
          message: data.message,
          type: 'error',
        });
        err = new Error(`${data.message}: ${config.url}`);
 
        return Promise.reject(err);
    }
  },
  error => {
    console.log('===>');
    console.log(error);
    const status = err.response.status;
    switch (status) {
      case 400: err.message = '请求错误'; break;
      case 401: err.message = '未授权，请登录';
         store.commit(types.LOGOUT);
         window.location.href = window.location.origin + '/gic-web';
        break;
      case 403: err.message = '拒绝访问'; break;
      case 404: err.message = `请求地址出错: ${err.response.config.url}`; break;
      case 408: err.message = '请求超时'; break;
      case 500: err.message = '服务器内部错误'; break;
      case 501: err.message = '服务未实现'; break;
      case 502: err.message = '网关错误'; break;
      case 503: err.message = '服务不可用'; break;
      case 504: err.message = '网关超时'; break;
      case 505: err.message = 'HTTP版本不受支持'; break;
      default: break;
    }
 
    Message({
      message: '系统异常',
      type: 'error',
    });
    return Promise.reject(err);
  }
);

export default request;
