import axios from 'axios'
import store from '@/store'
import router from '@/router'
import setting from '@/config/setting'
import { Modal } from 'ant-design-vue'

// create an axios instance
const service = axios.create({
  baseURL: '/api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: process.env.NODE_ENV === 'development' ? 0 : 600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = setting.takeToken()
    if (token) {
      config.headers[setting.tokenHeaderName] = token
    }
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    // 登录过期处理
    if (response.data.code === 401) {
      if (response.config.url === setting.menuUrl) {
        goLogin()
      } else {
        Modal.destroyAll()
        Modal.info({
          title: '系统提示',
          content: '登录状态已过期, 请退出重新登录!',
          okText: '重新登录',
          onOk: () => {
            goLogin(true)
          }
        })
      }
      return Promise.reject(new Error(response.data.msg))
    }
    // token自动续期
    const access_token = response.headers[setting.tokenHeaderName]
    if (access_token) {
      setting.cacheToken(access_token)
    }
    return response.data
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

/**
 * 跳转到登录页面
 */
function goLogin(reload) {
  store.dispatch('user/removeToken').then(() => {
    if (reload) {
      location.replace('/login') // 这样跳转避免再次登录重复注册动态路由
    } else {
      const path = router.currentRoute.path
      return router.push({
        path: '/login',
        query: path && path !== '/' ? { form: path } : null
      })
    }
  })
}

export default service
