import baseUrl from "../config/config.js";
// 带 Token 请求
const httpTokenRequest = (opts) => {
    uni.onNetworkStatusChange(function(res) {
        if (!res.isConnected) {
            uni.showToast({
                title: '网络连接不可用！',
                icon: 'none'
            });
        }
        return false
    });

    let token = uni.getStorageSync('token');

    if (token == '' || token == undefined || token == null) {
        uni.reLaunch({
            url: '/pages/login/login'
        });
    } else {
        let httpDefaultOpts = {
            url: baseUrl + opts.url,
            data: opts.data,
            method: opts.method || 'GET',
            header: opts.method == 'get' ? {
                'X-Access-Token':  token,
                'X-Requested-With': 'XMLHttpRequest',
                "Accept": "application/json",
                "Content-Type": "application/json; charset=UTF-8"
            } : {
                'X-Access-Token': token,
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            dataType: 'json',
        }
        let promise = new Promise(function(resolve, reject) {
            uni.request(httpDefaultOpts).then(
                (res) => {
                    if (res.statusCode == 200) {
                        //默认api接口正常返回0，不正常返回1，并给出错误提示
                        if (res.data.code == 0) {
                            resolve(res)
                        }else{
                            resolve(res)
                            uni.showToast({
                                icon:'none',
                                title:res.data.message
                            })
                        }
                    } else {
                        if (res.statusCode == 401) {
                            uni.showModal({
                                title: '提示',
                                content: '无权访问',
                                success: function (res) {
                                    if (res.confirm) {
                                        uni.reLaunch({
                                            url: '/pages/login/login'
                                        });
                                        uni.clearStorageSync();
                                    }
                                }
                            });
                            uni.clearStorageSync();
                        } else {
                            resolve(res)
                        }
                    }
                }
            ).catch(
                (response) => {
                    reject(response)
                }
            )
        })
        return promise
    }
};

// 导出去
export default httpTokenRequest;
