import request from "@/request/request"
import auth from "@/utils/auth"

let isrefreshing = false

//待刷新token任务列表
let queue = []

//不刷新Token白名单
let urls = ['/api/auth/refresh','/api/auth/login','/api/auth/register']

/**
 * 运行任务队列
 * @param {*} token 
 */
function runqueque(token) {
    queue.forEach(element => element(token))
    queue = []
}

/**
 * 处理accessToken自动刷新
 * @param {*} response 
 * @returns 
 */
export function handlerefresherror(response) {
    const { config, data, status } = response
    if ((data.code == 2009 || status == 401 && !urls.includes(config.url)) && !config._retry) {
        config._retry = true
        if (!isrefreshing) {
            isrefreshing = true
            return request.post('/api/auth/refresh', {
                userid: auth.getUserId(),
                refreshtoken: auth.getRefreshToken()
            })
                .then(r => {
                    if (r.code != 1000) {
                        window.location.href = '/auth/login'
                        return Promise.reject(r)
                    }
                    const { token, refreshToken } = r.data
                    auth.setAccessToken(token)
                    auth.setRefreshToken(refreshToken)
                    runqueque(token)
                    // 用新 token 重做原始请求
                    config.headers['Authorization'] = `Bearer ${token}`
                    return request(config)
                })
                .catch(err => {
                    auth.clear()
                    window.location.href = '/auth/login'
                    return Promise.reject(err)
                })
                .finally(() => isrefreshing = false)
        }

        // 刷新中：队列化
        return new Promise((resolve, reject) => {
            queue.push(token => {
                config.headers['Authorization'] = `Bearer ${token}`
                resolve(request(config))
            })
        })
    } else {
        return response
    }
}