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',
        'platform_code': serverConfig.platform_code,
        'platform_name': serverConfig.platform_name,
        'platform_short_code': serverConfig.platform_short_code
    }
    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(response.data.success) {
        return response.data
    } else {
        setTimeout(()=> {
            uni.showToast({
                title: response.data.content,
                icon: 'none',
                duration: 2000
            })
        }, 60)
        return Promise.reject(response)
    }
}, (response) => {
    setTimeout(()=> {
        loginPopupNum --
        if(loginPopupNum <= 0) {
            uni.hideLoading();
        }
    }, 30)
    //未登录时清空缓存跳转
    if(response.statusCode == 401){
        let token = uni.getStorageSync('token')
        if(token) {
            return new Promise((gloabResolve, gloabReject)=> {
                http.get('/jwt/refreshCustomerWxToken', {
                    params: {
                        token
                    }
                }).then(({content}) => {
                    uni.setStorageSync('token', content.body.token);
                    const config = response.config
                    if(config.method === "POST") {
                        let cb =  new Promise((resolve, reject)=> {
                            http.post(config.url, {...config.params}, {custom: config.custom})
                            .then(res=> { resolve(res) })
                            .catch(err=> { reject(err) })
                        })
                        gloabResolve(cb)
                    }
                    if(config.method === "GET") {
                        let cb =  new Promise((resolve, reject)=> {
                            http.get(config.url, {...config.params}, {custom: config.custom})
                            .then(res=> { resolve(res) })
                            .catch(err=> { reject(err) })
                        })
                        gloabResolve(cb)
                    }
                }).catch(err => {
                    gloabReject(err)
                })
            })
        } else {
            uni.showToast({
                title: '请登录',
                icon: 'error',
                duration: 2000
            })
        }
    } else {
        return Promise.reject(response)
    }
})

export { http }