import axios from 'axios'
import { VueAxios } from './axios'
import qs from 'qs'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  // baseURL: 'http://192.168.50.126:5000/api',
  baseURL: 'http://localhost:5000/api',
  // baseURL: 'http://117.62.238.129:5000/api',
  // baseURL: 'http://120.48.81.85:15002/api',
  timeout: 3600000, // 请求超时时间
  maxBodyLength: 5 * 1024 * 1024,
  withCredentials: false,
  paramsSerializer: {
    serialize: params => {
      if (params && params.sorter) {
        params.sorter = JSON.stringify(params.sorter)
      }
      return qs.stringify(params, { indices: false })
    }
  },
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    console.error('response => ', data)
    // const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      this.$notify.error({
        title: 'Forbidden',
        message: data.message,
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      this.$notify.error({
        title: 'Unauthorized',
        message: 'Authorization verification failed',
      })
      /*if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }*/
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  /*const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    config.headers.Authorization = token
  }*/
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

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

export default request

export {
  installer as VueAxios,
  request as axios
}
