const $ = global;
const auth = {
    reload() {
        return $.tools.router.goto({
            path: $.config.LAUNCH_PAGE,
            type: $.ROUTER_TYPE.CLOSE_ALL
        });
    },
    setSession(data) {
        $.tools.memory.setData('USER_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('login', 'POST', {
                    'code': wxRes.code
                }).then(res => {
                    auth.setSession(res.data);
                    resolve(res.data);
                }).catch((err) => {
                    reject(err);
                });
            } else {
                reject(wxRes);
            }
        });
    }
};
new $.Page({
    onLoad() {
        $.wx.showToast({
            title: '加载中'
        }, 'loading');
        this.doAuth();
    },
    doAuth() {
        auth.login()
            .then((userInfo) => {
                this.doRedirect(userInfo);
            });
    },
    doRedirect() {
        $.router.goto({
            path: '/pages/home/index',
            type: $.ROUTER_TYPE.CLOSE_ALL
        });
    }
})