import store from '@/store';

const commonUrl = 'http://116.62.129.2/CSWX'; //公共路径
// const commonUrl = "http://sf.jtfw8.com/WXXCX";
//http://116.62.129.2/CSWX 测试环境

function postRequest(url, data) {
    var promise = new Promise((resolve, reject) => {
        let header = {
            appid: 'wx08df2ca62f3e1766'
        };
        const token = uni.getStorageSync('token');
        console.log("POST请求:  ", url, data)
        if (token) {
            header.token = token;
        }
        uni.request({
            url: commonUrl + url,
            data: data,
            method: 'POST',
            header: header,
            success: function(res) {
                console.log("POST请求响应：", res)
                if (res.data.code === 201) {
                    store.dispatch('user/logout').then(() => {
                        uni.switchTab({
                            url: '/pages/index/index'
                        });
                    });
                }
                resolve(res.data);
            },
            error: function(e) {
                reject('网络出错');
            }
        });
    });
    return promise;
}

// get请求封装
function getRequest(url, data) {
    var promise = new Promise((resolve, reject) => {
        console.log("GET请求:  ", url, data)
        uni.request({
            url: commonUrl + url,
            data: data,
            method: 'GET',
            dataType: 'json',
            header: {
                appid: 'wx08df2ca62f3e1766',
                token: uni.getStorageSync('token')
            },
            success: function(res) {
                console.log("GET请求响应：", res)
                if (res.data.code === 201) {
                    store.dispatch('user/logout').then(() => {
                        uni.switchTab({
                            url: '/pages/index/index'
                        });
                    });
                    return;
                }
                resolve(res.data);
            },
            error: function(e) {
                reject('网络出错');
            }
        });
    });
    return promise;
}

module.exports = {
    post: postRequest,
    get: getRequest
};
