/*
 * @Author: lijianzhang
 * @Date: 2018-11-02 14:12:15
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2019-02-22 14:20:19
 */
import Axios from 'axios';
import merge from 'lodash/merge';
import { REQUEST_RUL } from '../_utils/constant';
const CancelToken = Axios.CancelToken;
const baseURL = REQUEST_RUL;
const request = Axios.create({
  baseURL,
  withCredentials: true,
  timeout: 30 * 1000 // 超时限制 30秒

});
const STATUS_CODES = {
  '401': 'User not authenticated'
};
request.interceptors.response.use(res => {
  if (res.headers['x-pagination']) {
    try {
      res.pagination = JSON.parse(res.headers['x-pagination']);
    } catch (error) {
      throw new Error('无效的 pagination 数据');
    }
  }

  return res;
}, err => {
  if (err.message === 'Network Error') throw new Error('网络加载失败，请检查您的网络设置');
  if (!err.response) throw err;

  if (STATUS_CODES[err.response.status]) {
    throw new Error(STATUS_CODES[err.response.status]);
  } else {
    throw new Error(err.response.data.message || err.response.data);
  }
});
const post = request.post.bind(request);

request.post = (url, data = {}, config = {}) => {
  let cancel;
  const cancelToken = new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  });
  const promise = post(url, data, merge(config, {
    cancelToken
  }));
  promise.cancel = cancel;
  return promise;
};

request.setBaseURL = function (url) {
  request.defaults.baseURL = url;
};

export default request;