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

import { Message } from 'element-ui';
/**
 * 兼容 errorCode:1 ||  code:'0' 为正确返回的接口
 *
 */
let __DEVELOPMENT = process.env.NODE_ENV === 'development';
let __PRODUCTION = process.env.NODE_ENV === 'production';
const service = axios.create();

service.defaults.timeout = 30000;
if (__DEVELOPMENT) {
  service.defaults.withCredentials = true;
}

service.interceptors.request.use(
  config => {
    return config;
  },
  err => {
    if (__DEVELOPMENT) {
      console.log('>>>>>>>>>> request error >>>>>>>>>>');
    }
    return Promise.reject(err);
  }
);

service.interceptors.response.use(
  response => {
    const { data, config } = response;
    let err;
    const { errorCode, code } = data;
    switch (errorCode) {
      case 1:
        return data;
      case 401:
        Message({
          message: '登录失效',
          type: 'error'
        });
        __PRODUCTION && (window.location.href = '/gic-web/#/login');
        break;
      case undefined:
        break;
      default:
        Message({
          message: data.message,
          type: 'error'
        });
        err = new Error(`${data.message}: ${config.url}`);
        if (__DEVELOPMENT) {
          console.log('>>>>>>>>>> response data error >>>>>>>>>>');
        }
        return Promise.reject(err);
    }
    switch (code) {
      case '0':
        return data.result;
      case '401':
        Message({
          message: '登录失效',
          type: 'error'
        });
        __PRODUCTION && (window.location.href = '/gic-web/#/login');
        break;
      default:
        Message({
          message: data.message,
          type: 'error'
        });
        err = new Error(`${data.message}: ${config.url}`);
        if (__DEVELOPMENT) {
          console.log('>>>>>>>>>> response data error >>>>>>>>>>');
        }
        return Promise.reject(err);
    }
  },
  err => {
    const status = err.response.status;
    switch (status) {
      case 400:
        err.message = '请求错误';
        break;
      case 401:
        err.message = '未授权，请登录';
        __PRODUCTION && (window.location.href = '/gic-web/#/login');
        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;
    }
    if (__DEVELOPMENT) {
      console.log('>>>>>>>>>> response error >>>>>>>>>>');
    }
    Message({
      message: '系统异常',
      type: 'error'
    });
    return Promise.reject(err);
  }
);

export function request(config, options = {}) {
  const defaultConfig = {
    headers: {
      'Content-Type': 'application/json',
      sign: localStorage.getItem('sign') || ''
    },
    params: {},
    data: {}
  };
  config = Object.assign(defaultConfig, config);
  if (config.url.match(/requestProject/) === null) {
    config.url = config.url + '?requestProject=marketing';
  }

  // if (config.useName) {
  //   if (config.method.toLowerCase() === 'post') {
  //     config.data.requestProject = 'marketing';
  //   } else if (config.method.toLowerCase() === 'get') {
  //     config.params.requestProject = 'marketing';
  //   }
  // }

  if (config.useForm) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.data = qs.stringify(config.data);
  }
  return service(config);
}
