import axios from 'axios';
import { Message } from 'element-ui';
import store from '../store'
import router from '../router'

// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// axios.defaults.headers['Origin'] = location.hostname

// TODO 修改依据 后台返回的对应地址 配置相应的请求地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  withCredentials: true,
  timeout: 15000000,
});

service.interceptors.request.use(
  config => config,
  (error) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response) => {
    if (response.data.code === '200') {
      return response.data.data;
    } else if (response.data.message) {
      if (response.data.message.length > 20) {
        return Promise.reject({ message: response.data.message })
      }
      Message({
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
      return Promise.reject({ message: response.data.message })
    }
    return Promise.reject(response.data.code, response.data);
  },
  (error) => {
    if (error.response && error.response.status === 403) {
      store.dispatch('user/logout').then(() => {
        router.push(`/login?redirect=${router.currentRoute.fullPath}`)
      })
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000,
        showClose: true
      })
    }
    return Promise.reject(error)
  },
);

export default service;
