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

const service = axios.create({
  baseURL: 'https://hjsk.zjszsk.com/clients/v1',
  // timeout: 5000,
  withCredentials: false // 默认 false,表示跨域请求时是否需要使用凭证
})

service.interceptors.request.use(config => {
  if (store.getters.token) config.headers.Authorization = store.getters.token
  return config
}, error => {
  console.log('请求拦截器报错 ↓')
  console.dir(error)
  console.log('请求拦截器报错 ↑')
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const { data, status, msg } = response.data
  // 处理登录接口账号密码输入错误也返回200
  if (status === 400) {
    Message({
      message: msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(new Error(msg))
  } else if (status === 401) {
    if (router.currentRoute.path === '/login') return
    store.dispatch('user/logoutAction')
    Message({
      message: msg,
      type: 'error',
      duration: 3 * 1000
    })
    router.replace(`/login?redirect=${router.currentRoute.path}`)
    return Promise.reject(new Error(msg))
  } else {
    return data
  }
}, error => {
  // 响应拦截器200以外的
  console.log('响应拦截器报错 ↓')
  console.dir(error)
  console.log('响应拦截器报错 ↑')
  if (error.response && error.response.status === 400) {
    // 处理某些页面多个请求多次401重复跳转问题，造成重新登录后不能正确跳转到上次访问页面问题
    if (router.currentRoute.path === '/login') return
    store.dispatch('user/logoutAction')
    // 错误提示
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 3 * 1000
    })
    router.replace(`/login?redirect=${router.currentRoute.path}`)
  }
  return Promise.reject(error)
})

export default service
