import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
// import { getToken } from '@/'

/* eslint-disable-next-line */
// const BASEURL = process.env.NODE_ENV !== 'production' ? window.location.origin : '';

/* eslint-disable-next-line */
const isPro = process.env.NODE_ENV === 'production';
const BASEURL = isPro ? window.location.origin : 'https://four.gicdev.com';

axios.defaults.baseURL = BASEURL;

const request = (opt, params) => {
  params = Object.assign({}, params);
  opt = Object.assign({}, opt);
  let requestConfig = {
    // 请求路径
    url: '',
    params: '',
    data: '',
    // 请求type
    method: 'get',
    // request body 是否使用 formData格式
    useFormData: false,
    // response 是否使用 code === '0000' 验证
    useIntercept: true,
    // 设置headers
    headers: {}
  };
  requestConfig = Object.assign(requestConfig, opt);
  if (requestConfig.useFormData) params = qs.stringify(params);
  switch (requestConfig.method.toLowerCase())  {
    case 'get':
      requestConfig.params = params;
      break;
    case 'post':
      requestConfig.data = params;
      break;
    default:
      requestConfig.data = params;
      break;
  }
  return new Promise((resolve, reject) => {
    axios(requestConfig).then(res => {
      let resp = res.data;
      if (!requestConfig.useIntercept || resp.code === '0000') {
        return resolve(resp);
      };
      if (resp.message) {
        Message({
          message: resp.message,
          type: 'warning',
          duration: 3000
        });
      }
      reject(resp);
    }).catch(error => {
      const response = error.response || {};
      const { data, status } = response;
      if (status === 401) {
        let url = isPro ? '../operation-platform/' : 'https://four.gicdev.com/operation-platform/';
        window.location.href = url;
      }
      if (data && data.message) {
        Message({
          message: data.message,
          type: 'warning'
        });
      }
      reject(error);
    });
  });
};

export { axios, request };
