const Api = require('./Api');

class LoginApi {

    static login(js_code, wxRes, cb) {

        let url = "/auth/loginByGame.do";

        let data = {
            nick: wxRes.userInfo.nickName,
            head: wxRes.userInfo.avatarUrl.replace('132', '96'),
            gender: wxRes.userInfo.gender,
            js_code: js_code,
            encryptedData: wxRes.encryptedData,
            iv: wxRes.iv
        }

        Api.httpGet({
            url: url,
            data: data,
            success: (response) => {
                console.log('login response: ' + JSON.stringify(response));
                var user = response.user;
                Global.user = {
                    token: response.token,
                    uid: user.id,
                    openId: user.openId,
                    nick: wxRes.userInfo.nickName,
                    avatarUrl: wxRes.userInfo.avatarUrl,
                    gender: wxRes.userInfo.gender,
                };
                cc.sys.localStorage.setItem('GlobalUser', Global.user);
                cb();
            },
            fail: (errCode, errMsg) => {
                console.log('login error code: ' + errCode, 'login error msg: ' + errMsg);
            },
        });
    }


    static getUserInfoPromise() {
        let data = {
            targetUid: Global.user.uid
        };

       return Api.httpGetPromise('/user/getInfo.do',data);
    }

    static getUserInfo(success, fail) {

        let requestBody = {
            url: '/user/me.do',
            data: {},
            success: success,
            fail: fail,
        }
        Api.httpGet(requestBody);
    }
}

module.exports = LoginApi;
