class WxLogin {
    constructor() {
        this.loginUrl = 'http://8md9vz.natappfree.cc/auth/loginByGame.do';
        this.isLogined = false;
    }

    init(cb) {
        this.cb = cb || function () { }

        if (this.isLogined || window.wx === undefined) {
            this.cb();
            return;
        }

        this.isSupportInfoBtn = window.wx.createUserInfoButton ? true : false;

        let self = this;
        window.wx.login({
            success: (code) => {
                self.js_code = code.code;
                //如果支持用户信息按钮
                if (self.isSupportInfoBtn) {
                    window.wx.getSetting({
                        success: function (res) {
                            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                            if (res.authSetting['scope.userInfo']) {
                                self.getUserInfo()
                            } else {
                                self.createBtn()
                            }
                        }
                    })
                } else {
                    self.getUserInfo()
                }
            }
        })
    }

    getUserInfo() {
        window.wx.getUserInfo({
            withCredentials: true,
            success: (obj) => {
                this.login(obj, this.cb)
            }
        })
    }

    login(obj) {
        // window.wx.request({
        //     url: this.loginUrl,
        //     data: {
        //         nick: obj.userInfo.nickName,
        //         head: obj.userInfo.avatarUrl,
        //         thirdType: 1,
        //         js_code: this.js_code,
        //         encryptedData: obj.encryptedData,
        //         iv: obj.iv
        //     },
        //     success: this.cb
        // })
        this.cb();
        this.isLogined = true;
    }

    createBtn() {
        let self = this
        let button = window.wx.createUserInfoButton({
            type: 'text',
            text: '点击授权',
            style: {
                left: 200,
                top: 100,
                width: 160,
                height: 80,
                backgroundColor: '#B6ABAB',
                color: '#000000',
                textAlign: 'center',
                fontSize: 16,
                lineHeight: 80,
                borderRadius: 5
            }
        })
        button.onTap(function (res) {
            if (res.errMsg == 'getUserInfo:ok') {
                button.destroy();
                self.login(res, self.cb)
            }
        })
    }
}




module.exports = new WxLogin()