import Vue from 'vue';
import axios from 'axios';
import store from '@/store';
import { Message } from 'element-ui';
import {
  VueAxios
} from './axios';
import notification from 'ant-design-vue/es/notification';
import {
  ACCESS_TOKEN
} from '@/store/mutation-types';

// 创建 axios 实例
const service = axios.create({
   baseURL: 'http://36.110.39.213:8082', // api base_url
  // baseURL: 'http://103.249.252.109:38081', // api base_url`
  // baseURL: 'http://39.155.253.71:48081', // api base_url`
  // baseURL: '/api', // api base_url`
  timeout: 6000 // 请求超时时间
});

const err = (error) => {
  if (error.response) {
    const data = error.response.data;
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.msg
      });
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      });
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  } else {
    location.reload();
  }
  return Promise.reject(error);
};

// request interceptor
service.interceptors.request.use(config => {
  console.log(store.state.user.userToken);
  const userToken = store.state.user.userToken;
  if (userToken) {
    config.headers['Authorization'] = userToken; // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use((response) => {
  if (response.data.code && response.data.code == 401) {
    Message({
      message: '无权限',
      type: 'error',
      duration: 3 * 1000
    });
  }
  return response.data;
}, err);

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service);
  }
};

export {
  installer as VueAxios,
  service as axios
};
