const $ = global;
const auth = {
    /***
     * reload小程序（返回首页）
     */
    reload() {
        return global.tools.router.goto({
            path: global.config.LAUNCH_PAGE,
            type: global.ROUTER_TYPE.CLOSE_ALL
        });
    },
    setSession(data) {
        global.tools.memory.setData('AUTH_INFO', data, {
            localSave: true
        });
    },
    /***
     * 登录微信小程序
     */
    login() {
        return new Promise((resolve, reject) => {
            wx.login({
                success: (wxRes) => {
                    auth._loginToServer(wxRes)
                        .then(res => {
                            resolve(res);
                        })
                        .catch(err => {
                            reject(err);
                        });
                },
                fail: (err) => {
                    $.wx.showToast({
                        title: '登录失败',
                        icon: 'warn'
                    });
                    reject(err);
                }
            });
        });
    },
    /**
     * 在后台登录
     * @param {微信登录结果} wxRes
     */
    _loginToServer(wxRes) {
        return new Promise((resolve, reject) => {
            if (wxRes.code) {
                $.request('default/token', 'POST', {
                    'code': wxRes.code
                }).then(res => {
                    console.log('登录成功');
                    res.data.code = wxRes.code;
                    auth.setSession(res.data);
                    resolve(res.data);
                }).catch((err) => {
                    console.log('后台登录失败');
                    reject(err);
                });
            } else {
                console.log('登录失败');
                reject(wxRes);
            }
        });
    }
};
export default {
    auth,
    doRedirect(p = '') {
        $.request('default/info', 'POST', {}, true).then(res => {
            let path;
            if (res.ret === 0) {
                path = '/pages/auth/index';
            } else {
                path = p || '/pages/nearby/index';
                $.tools.memory.setData('USER_INFO', res.data, {
                    localSave: true
                });
            }
            $.router.goto({
                path,
                type: $.ROUTER_TYPE.CLOSE_ALL
            });
        });
    }
}