import axios from 'axios';
import { message } from 'antd';
import get from 'lodash/get';
import { history } from 'umi';

const globalMsg = 'globalMsg';

export const getToken = (k = 'token', prefix = 'AFAJWT ') => {
  const token =
    localStorage.getItem(k) != undefined ? localStorage.getItem(k) : 'no_token';
  // console.log(' prefix, k ： ', prefix, k, token); //
  return prefix + token;
};

// axios.defaults.headers.common['Authorization'] = getToken()

const instance = axios.create({
  baseURL: '/',
  timeout: 60000
});

const operationSuccess = (response) => {
  const method = get(response, 'config.method', '').toLocaleLowerCase();
  // const url = get(response, 'config.url', '');
  // if (url.includes('/mlsource/setting/')) {
  //   return;
  // }
  switch(method) {
    case 'post':
      message.success('操作成功');
      break;
    case 'delete':
      message.success('删除成功');
      break;
    case 'put':
      message.success('更新成功');
      break;
    default:
      break;
  }
}

instance.interceptors.request.use(config => {
  // config.headers.Authorization = getToken();
  return config;
})

instance.interceptors.response.use(function (response) {
  operationSuccess(response);
  return response.data;
}, function (error) {
  if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
    message.error({
      content: '请求超时，系统异常！',
      key: globalMsg,
    });
    return;
  }
  const {status, config} = error.response;
  // if (status === 401 ||
  //   status === 403
  // ) {
  //   return router.push('/login');
  // }
  if (!location.pathname.includes('/login') && get(error, 'response.data.code') === 104000) {
    location.href = '/login'
    return Promise.reject(error)
  }

  if (status === 400) {
    message.error(get(error, 'response.data.msg_show', '出现异常'));
  } else if (status === 404) {
    message.error('请求出现错误');
  } else {
    message.error({
      content: '系统繁忙，请稍后再试',
      key: globalMsg,
    });
  }
  return Promise.reject(error);
});

export default instance;

export const getFile = (url) => {
  const key = 'getFile';
  message.info({
    content: '获取文件中',
    key,
  });
  return axios.get(url, {
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    timeout: 600 * 1000
  }).then(res => {
    message.success({
      content: '获取文件成功',
      key,
    });
    return res;
  }).catch(err => {
    message.error({
      content: '获取文件失败',
      key,
    });
    return false;
  });
}
