import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import { SUCCESS_CODE, origin } from '@/config';
// import Store from '@/store';
/**
 * 请求白名单
 * 展示左侧菜单但却没有选中的子应用id时这些请求将不会进行过滤
 */
// const whiteList = [
//   '/gic-auth-web/get-login-user-info',
//   '/api-marketing/enterprise-serve-info',
//   '/gic-auth-web/login-user-menu-of-app',
//   '/api-welfare/area/member-cards',
//   '/gic-auth-web/login-collaborator-operation-item',
//   '/gic-auth-web/login-user-operation-item-of-app',
//   '/gic-auth-web/login-collaborator-menu-of-app',
//   '/gic-auth-web/login-user-operation-item',
//   '/application-center-web/business/cooperation-application/find-list',
//   '/gic-auth-web/get-app-by-code'
// ];
// import { getToken } from '@/'
// rest: 支持restfulapi url里传动态参数
// alertError：是否全局弹出message，默认弹出true


/**
 * http状态码处理
 * @param {*} code ui目前只处理如下code
 */
function handlerErr(code) {
  if (process.env['NODE_ENV'] === 'development') { // eslint-disable-line
    return;
  }
  switch (code) {
    case 404:
      window.location.href = origin + '/damo-system/404';
      break;
    case 403:
      window.location.href = origin + '/damo-system/403';
      break;
    case 500:
      window.location.href = origin + '/damo-system/500';
      break;
  }
}

axios.defaults.baseURL = origin;
const request = (opt, params, restObj) => {
  // if ((!Store.state.project || (Store.state.project.includes('card') && !Store.state.currentAreaId)) && !whiteList.includes(opt.url) ) {
  //   // 有左侧但没有选中子应用id || 禁用
  //   return new Promise((resolve, reject) => {
  //     reject();
  //   });
  // }

  params = Object.assign({}, params);
  opt = Object.assign({}, opt);
  if (opt.rest) {
    // 需要重置url restful
    delete opt.rest;
    let url = opt.url;
    Object.keys(restObj).map(v => {
      url = url.replace(`{${v}}`, restObj[v]); // 替换url中{}对应的key
    });
    opt.url = url;
  }

  // 是否全局弹出message 默认true弹出
  const alertError = opt.alertError !== undefined ? opt.alertError : true;
  delete opt.alertError;

  let requestConfig = {
    // 请求路径
    url: '',
    params: '',
    data: '',
    // 请求type
    method: 'get',
    // request body 是否使用 formData格式
    useFormData: false,
    // response 是否使用 code === SUCCESS_CODE 验证
    useIntercept: true,
    // 设置headers， 但是好像没效果，以后再说吧
    headers: {}
  };
  requestConfig = Object.assign(requestConfig, opt);
  if (opt.export) {
    // 导出的数据接口
    // 后端要listParams放query里，excel参数放body json里
    requestConfig.params = params.listParams;
    requestConfig.data = params.excel;
  } else if (opt.file) {
    // 上传内容包括file
    let formData = new FormData();
    Object.keys(params).forEach(v => {
      formData.append(v, params[v]);
    });
    requestConfig.data = formData;
  } else {
    if (requestConfig.useFormData) params = qs.stringify(params);
    switch (requestConfig.method.toLowerCase())  {
      case 'get':
        requestConfig.params = params;
        break;
      case 'post':
        requestConfig.data = params;
        break;
      // case 'put':
      //   requestConfig.params = params;
      //   break;
      // case 'delete':
      //   requestConfig.params = params;
      //   break;
      default:
        requestConfig.data = params;
        break;
    }
  }

  return new Promise((resolve, reject) => {
    // try {
    axios(requestConfig).then(res => {
      let resp = res.data;
      // code = '6666'为未登录或者登录失效状态
      if (resp.code == '6666') {
        let origin = window.location.origin;
        if (origin.indexOf('localhost') >= 0 || origin.indexOf('192.168') >= 0) {
          origin = 'https://four.gicdev.com';
        }
        // eslint-disable-next-line
        if (process.env['NODE_ENV'] !== 'development') {
          window.location.href = `${origin}/damo-system/login`;
        }
      }
      if (requestConfig.useIntercept && resp.code != SUCCESS_CODE) {
        if (alertError) {
          Message({
            message: (resp.message || '数据加载失败').slice(0, 300),
            type: 'warning'
          });
        }
        return reject(resp);
      }
      resolve(resp);
    }).catch(error => {
      if (error) {
        handlerErr(error.response.status);
      }
      Message({
        message: (error.response.data.message || '数据加载失败').slice(0, 300),
        type: 'warning'
      });
      reject(error);
    });

  });
};

export { axios, request };
