import axios from 'axios';
import qs from 'qs';

const service = axios.create();

service.defaults.timeout = 30000;
 
service.interceptors.request.use((config) => {
  return config;
}, (err) => {
  return Promise.reject(err);
});

service.interceptors.response.use((response) => {
  const { data } = response;
  // let err;
  const { errorCode, code } = data;
  if( errorCode==0||code==0){
    return data.result;
  }else{
    // err = new Error(data.message || '系统异常');
    return Promise.reject(data);
  }
}, (err) => {
  const status = err.response.status;
  switch (status) {
    case 400: err.message = '请求错误'; break;
    case 401: err.message = '未授权，请登录'; 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;
  }
  return Promise.reject(err);
});

export function request (config) {
  const defaultConfig = {
    headers: {
      'Content-Type': 'application/json'
    },
    params: {},
    data: {},
  };
  if (config.url.match(/requestProject/) === null) {  // 仅仅提供演示作用，如果用不到，删掉
    config.url = config.url + '?';
  }
  config = Object.assign(defaultConfig, config);
  if (config.useForm) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.data = qs.stringify(config.data);
  }
  return service(config);
}

export function getRequest(url,params){
  return request({
    method: 'get',
    url,
    params,
  });
}

export function postRequest(url,params){
  return request({
    method: 'post',
    url,
    data: params,
  });
}

