/**
 * 全站http配置
 *
 * axios 参数说明
 * isSerialize 是否开启form表单提交
 * isToken是否需要 token
 */
import axios from 'axios'
import store from '@/store/'
import router from '@/router/router'
import { serialize } from '@/util/util'
import { getToken } from '@/util/auth'
import website from '@/const/website.js'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { Message, MessageBox } from 'element-ui'
import errorCode from '@/const/errorCode'
import qs from 'qs'
axios.defaults.timeout = 60000
// 返回其他状态吗
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500 // 默认的
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})
// HTTPrequest拦截
axios.interceptors.request.use(
  config => {
    NProgress.start() // start progress bar
    const meta = config.meta || {}
    const isToken = (config.headers || {}).isToken === false
    const token = store.getters.token
    if (token && !isToken) {
      config.headers['Authorization'] = 'Bearer ' + token // tokentoken--['Authorization']为自定义key 请根据实际情况自行修改
    }

    // 设置灰度版本
    const grayVersion = process.env.VUE_APP_GRAY_VERSION
    if (grayVersion) {
      config.headers['VERSION'] = grayVersion
    }

    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data)
    }

    if (config.method === 'get') {
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// HTTPresponse拦截
axios.interceptors.response.use(
  res => {
    NProgress.done()
    const status = Number(res.status) || 200
    const statusWhiteList = website.statusWhiteList || []
    // const message = res.data.message || '未知错误'
    const message = res.data.msg || errorCode[status] || errorCode['default']
    // 如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res)
    // 如果是401则跳转到登录页面
    if (status === 401) store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))

    // 后台定义 424 针对令牌过去的特殊响应码
    if (status === 424) {
      MessageBox.confirm('令牌状态已过期，请点击重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          store.dispatch('FedLogOut').then(() => {
            // 刷新登录页面，避免多次弹框
            window.location.reload()
          })
        })
        .catch(() => {})
      return
    }

    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    }
    return res
  },
  error => {
    NProgress.done()
    return Promise.reject(new Error(error))
  }
)

export default axios
