const app = getApp();

// 小程序登录
function appLogin() {
    return new Promise(function (resolve, reject) {
        uni.login({
            success(res) {
                if (!res.code) {
                    uni.hideLoading();
                    uni.showModal({
                        content: res.errMsg,
                        showCancel: false
                    });
                }
                resolve(res);
            },
            fail() {
                uni.hideLoading();
                uni.showModal({
                    content: '小程序登录失败',
                    showCancel: false
                });
                reject();
            }
        });
    });
}

// 小程序授权
function authorization(data) {
    return new Promise(async function (resolve, reject) {
        const res = await app.$vm.$u.api.loginWechatAuth(data)
        if (res) {
            if (res.code == 200 && res.data) {
                app.setUserData(res.data)
                resolve(res);
            } else {
                reject(res);
            }
        } else {
            uni.showModal({
                title: '请求失败',
                content: res.message
            });
        }
    });
}

// 小程序注册
function signup(data) {
    return new Promise(async function (resolve, reject) {
        const res = await app.$vm.$u.api.loginWechatAuth(data)
        if (res) {
            if (res.code == 200 && res.data) {
                app.setUserData(res.data)
                resolve(res);
            } else {
                uni.showModal({
                    title: '用户授权失败',
                    content: res.message,
                    showCancel: false
                });
                reject(res);
            }
        } else {
            uni.showModal({
                title: '请求失败',
                content: res.message
            });
        }
    });

}


module.exports = {
    appLogin: appLogin,
    authorization: authorization,
    signup: signup
}