import Request from '@/utils/luch-request/luch-request/index.js'
import serverConfig from './server_config.js'
const http = new Request()

http.setConfig((config) => { /* config 为默认全局配置*/
    config.baseURL = serverConfig.baseURL;
    config.header = {
        'Content-Type': 'application/json;charset=UTF-8'
    }
    return config
})
//请求前拦截
let loginPopupNum = 0;
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    config.header = {
        ...config.header,
    }
    //获取存储的token
    // const token = uni.getStorageSync('token');
    // config.header['X-Token'] = token;
    // 根据custom参数中配置的是否需要loading
    if (config.custom.load) {
        loginPopupNum ++
        uni.showLoading({
            title: '加载中...'
        });
    }
    return config
}, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
})

// 请求后拦截器
http.interceptors.response.use((response) => {
    setTimeout(()=> {
        loginPopupNum --
        if(loginPopupNum <= 0) {
            uni.hideLoading();
        }
    }, 30)
    if(Array.isArray(response.data) || response.data.success) {
        return response.data
    } else {
        setTimeout(()=> {
            uni.showToast({
                title: response.data.message,
                icon: 'none',
                duration: 2000
            })
        }, 60)
        return Promise.reject(response)
    }
}, (response) => {
    setTimeout(()=> {
        loginPopupNum --
        if(loginPopupNum <= 0) {
            uni.hideLoading();
        }
    }, 30)
    return Promise.reject(response)
})

export { http }