import axios from 'axios'
import { Base64 } from 'js-base64'
import website from '~src/config'
import router from '~src/router/index'
import { getToken } from '~src/api/util/auth'
import { toSerialize } from 'js-fast-way'
import { getStoreValue } from '~src/utils/storage'

//默认超时时间
axios.defaults.timeout = 0
//返回其他状态码
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500
}
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true

//http request拦截
axios.interceptors.request.use(config => {
    const meta = (config['meta'] || {})
    const isToken = meta['isToken'] === false
    config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
    //让每个请求携带token
    const token = getToken()
    if (token && !isToken) {
        config.headers[website.tokenHeader] = 'bearer ' + token
    }
    //headers中配置text请求
    if (config['text'] === true) {
        config.headers['Content-Type'] = 'text/plain'
    }
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta['isSerialize'] === true) {
        config.data = toSerialize(config.data)
    }
    config.metadata = { startTime: new Date() }
    return config
}, error => {
    return Promise.reject(error)
})

//http response 拦截
axios.interceptors.response.use(res => {
    //响应时间
    res.config.metadata.endTime = new Date()
    //获取状态码
    const status = res?.data?.code || res.status
    //如果是401则跳转到登录页面
    if (status === 401) {
        const isSource = getStoreValue('isSource')
        if (!isSource) {
            window.$message?.error('身份失效,请重新登录！')
            router.push({ path: '/login' }).then()
        } else {
            router.push({ name: 'app-auth' }).then()
        }
    }
    // 如果请求为非200, 自行catch逻辑处理
    if (status !== 200) {
        return Promise.reject(res)
    }
    return res
}, error => {
    return Promise.reject(new Error(error))
})

export default axios
