import axios from 'axios'
import { Message } from '../lib/index'

function getToken() {
    let token = sessionStorage.getItem('token')
    return 'Bearer ' + token
}



const service = axios.create({
    baseURL: '/api',
    headers: {
        post: {
            'Content-Type': 'application/json'
        },
        Authorization: getToken()
    }
})

service.setToken = (token, refresh_token) => {
    sessionStorage.setItem('token', token)
    sessionStorage.setItem('refresh_token', refresh_token)
    service.defaults.headers['Authorization'] = getToken()
}

let isRefreshing = false
let requestConfigArr = []

// 请求拦截
service.interceptors.request.use(
    config => {
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error.response)
    }
)

// 响应拦截
service.interceptors.response.use(
    response => {


        let { status, message, data } = response.data

        let type = Object.prototype.toString.call(response.data).slice(8, -1)
        if (type == 'Blob') {
            return response
        }


        if (status === 0 && message) {
            Message.success(message)
        }
        if (status !== 0) {
            Message.error(message)
        }

        return data
    },
    error => {
        error.response
        console.log('error ----- ', error)

        if (error.response?.status == 401) {

            if (!isRefreshing) {
                isRefreshing = true
                refreshToken({ refreshToken: sessionStorage.getItem('refresh_token'), "grant_type":"refresh_token" }).then(response => {
                    service.setToken(response.access_token, response.refresh_token)
                    error.config.headers.Authorization = getToken()
                    requestConfigArr.forEach(fn => fn())
                    requestConfigArr = []
                    isRefreshing = false
                    return service.request(error.config)
                })

            } else {
                return new Promise(resolve => {
                    requestConfigArr.push(() => {
                        error.config.headers.Authorization = getToken()
                        resolve(service.request(error.config))
                    })
                })
            }

        }

        return Promise.reject(error)
    }
)

export default service
