import axios from 'axios';
import store from '../store'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui';
import {
  getToken
} from '../utils/auth'

let loadingInstance = {};
const $service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60000
});
$service.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      lock: true,
      text: '拼命加载中',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    if (store.getters.token) {
      config.headers.token = getToken()
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });
$service.interceptors.response.use(
  response => {
    const res = response.data;
    setTimeout(() => {
      loadingInstance.close();
    });
    if (res.code !== 10000) {
      Message({
        message: res.message || '异常～',
        type: 'error',
        duration: 2000
      });
      if (res.code === 403) {
        MessageBox.confirm('您没有权限访问此接口', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
      }
      if (res.code === 401 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm('登录超时或未登录，请登录～', {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(response);
    } else {
      return res;
    }
  },
  error => {
    loadingInstance.close();
    Message({
      message: error.message || '异常～',
      type: 'error',
      duration: 2000
    });
    return Promise.reject(error);
  }
);

export default $service;
