/**
 * 网络请求模块
 * @author andy
 * @param {*} cmd 接口名称
 * @param {*} method 请求方法
 * @param {*} params 请求参数
 * @param {*} handleStatus 是否需要单独处理错误码
 */
const request = (cmd, method = 'POST', params = {}, handleStatus = false) => {
    return new Promise((resolve, reject) => {
        const getHeader = (method) => {
            const userInfo = global.tools.memory.getData('USER_INFO') || {};
            const header = {
                'token': userInfo.token || '',
                'openid': userInfo.openid || ''
            };
            if (method && method.toUpperCase() === 'POST') {
                // header['content-type'] = 'application/x-www-form-urlencoded';
                header['content-type'] = 'application/json';
            }
            return header;
        };
        const env = global.config.ENV;
        const requestUrl = env.toUpperCase() === 'PRD' ? global.config.REQUEST_URL : global.config.REQUEST_DEV_URL;
        wx.request({
            url: `${requestUrl}${cmd}`,
            header: getHeader(method),
            method,
            data: params,
            success: res => {
                res = res.data;
                if (res.status && res.status === 105) {
                    // token失效
                    global.memory.setData('USER_INFO', {}, {
                        localSave: true
                    });
                    return global.router.goto({
                        path: global.config.LAUNCH_PAGE,
                        type: global.ROUTER_TYPE.CLOSE_ALL
                    });
                } else {
                    if (handleStatus || !res.status) {
                        resolve(res);
                    } else if (res.message) {
                        global.wx.showToast({
                            title: res.message
                        });
                    } else {
                        global.wx.showToast({
                            title: '服务不可用，请稍后再试'
                        });
                    }
                }
            },
            fail: reject
        });
    });
};
export default request;