/*
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-16 16:37:05
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-02 11:13:04
 */
import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import { origin, succCode, notAuthCode } from '@/config/index.js';

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

axios.defaults.baseURL = origin;
axios.defaults.withCredentials = true;
const request = (opt, params, config) => {
  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: {}
  };
  Object.assign(requestConfig, opt, config);
  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 (resp.code == notAuthCode) {
        window.location.href = `${origin}/haoban-4/login`;
        return reject(resp);
      }
      if (requestConfig.useIntercept && resp.code != succCode) {
        Message({
          message: resp.message || '未知错误',
          type: 'warning'
        });
        return reject(resp);
      }
      resolve(resp);
    }).catch(error => {
      let response = error.response || {};
      let data = response.data || {};
      Message({
        message: data.message || '未知错误',
        type: 'warning'
      });
      reject(error);
    });
  });
};

export { axios, request };
