var common = require('./common.js');
var storage = require('./storage.js');
var config = require('./config.js');

// 检查token是否失效 如失效 清除缓存 提示重新登录
// 402: 解析token出错  403: token格式错误  404: 公共声明中缺少必要字段  405: token验证失败
function _checkTokenValid(res) {
    if (
        res.data.code === 402 ||
        res.data.code === 403 ||
        res.data.code === 404 ||
        res.data.code === 405 ||
        res.data.code === 300 ||
        res.data.code === 302 ||
        res.data.code === 303 ||
        res.data.code === 304 ||
        res.data.code === 305 ||
        res.data.code === 306
    ) {
        uni.clearStorageSync();
        uni.reLaunch({
            url: '/pages/login/login'
        });
        // wx.navigateTo({
        //   url: '/pages/login/login',
        // })
        // wx.showModal({
        //   title: '错误',
        //   content: '鉴权认证过期，请重新登录',
        //   showCancel: false
        // })
        return false;
    }
    return true;
}
function getRequest(url, data, successCallBack, failCallBack) {
    if (!failCallBack) {
        failCallBack = function () {};
    }
    if (url.indexOf('?') > 0) {
        url = url + '&' + common.obj2UrlQuery(data);
    } else {
        url = '?' + common.obj2UrlQuery(data);
    }
    uni.request({
        url: url + '?token=' + storage.getApiToken(),
        method: 'GET',
        success: function (res) {
            uni.hideLoading();
            if (_checkTokenValid(res)) {
                successCallBack(res);
            }
        },
        fail: function (res) {
            uni.hideLoading();
            uni.showModal({
                title: '错误',
                content: '网络错误',
                showCancel: false
            });
            if (failCallBack) {
                failCallBack(res);
            }
        }
    });
}
function postRequest(url, data, successCallBack, failCallBack) {
    if (!failCallBack) {
        failCallBack = function () {};
    }
    uni.request({
        url: url + '?token=' + storage.getApiToken(),
        data: data,
        header: {
            'content-type': 'application/json'
        },
        method: 'POST',
        success: function (res) {
            //wx.hideLoading();
            if (_checkTokenValid(res)) {
                successCallBack(res);
            }
        },
        fail: function (res) {
            uni.hideLoading();
            failCallBack(res);
        }
    });
}
function getApi(url, data, successCallBack, failCallBack) {
    getRequest(url, data, successCallBack, failCallBack);
}
function postApi(url, data, successCallBack, failCallBack) {
    postRequest(url, data, successCallBack, failCallBack);
}
module.exports = {
    getRequest: getRequest,
    postRequest: postRequest,
    getApi: getApi,
    postApi: postApi
};
