import axios from 'axios';
import { Notification, MessageBox, Message } from 'element-ui';
import { getToken } from '@/libs/base/util';
import { errorCode, successCode } from '@/utils/httpCode';
const ERR_MSG_DURATION = 2000;
const AXIOS_TIMEOUT = 60000;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_SERVER_URL,
  // 超时
  timeout: AXIOS_TIMEOUT
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const token = getToken()
    config.headers['Authorization'] = 'Bearer ' + token
    // if (token) {
    //   config.headers['Authorization'] = 'Bearer ' + token
    //   // config.headers['content-type' ] = 'application/x-www-form-urlencoded'
    // } else {
    //   // removeToken()
    // }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || successCode;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default'];
    const disableErrMsg = res.config.disableErrMsg;
    switch (code) {
      case successCode: {
        return res.data;
      }
      default: {
        if (!disableErrMsg) {
          Notification.error({
            title: msg
          });
        }
        return Promise.reject(res.data);
      }
    }
  },
  (error) => {
    console.log('err' + error);
    let { message } = error;
    const { response, config } = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Invalid URL')) {
      message = 'URL访问失败，请重新检查';
      MessageBox.confirm(
        message,
        '系统提示',
        {
          type: 'warning',
          confirmButtonText: '知道了',
          showCancelButton: false

        }
      );
    } else if (response) {
      const status = response.status;
      message = '系统接口:' + status + '异常';
    }
    Message({
      message: `${message}:${config.url}`,
      type: 'error',
      duration: ERR_MSG_DURATION
    });
    return Promise.reject();
  }
);

export default service;
