// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        openId:null,
        js_code:null,
        encryptedData:null,
        iv:null,
        mainMenu:cc.Node,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {  
        if(window.wx!=undefined){
            wx.getSystemInfo({
                success:(res)=>{
                    Global.os = res.platform=="android"?2:1;
                }
            })
            var self = this;
            wx.login({
                success:function (res) {
                    self.js_code = res.code;
                    self.onLoginSuccess();
                }
            })
        }else{
            console.log("wx不存在");
        }
    },

    start () {

    },

    onLoginSuccess(code){

        console.log("onLoginSuccess");
        wx.getSetting({
            success: (res)=> {
                console.log("getSetting success");
                var authSetting = res.authSetting;
                if (authSetting['scope.userInfo'] === true) {
                    // 用户已授权，可以直接调用相关 API
                    this.authorizeSuccess();
                } else if (authSetting['scope.userInfo'] === false){
                    this.showModal();
                // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
                } else {
                    // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
                    this.authorize();
                }
            }
        });
    },

    authorize(){
        wx.authorize({
            scope: 'scope.userInfo',
            success:()=>{
                this.authorizeSuccess();
            },
            fail: (res)=> {
                // iOS 和 Android 对于拒绝授权的回调 errMsg 没有统一，需要做一下兼容处理
                if (res.errMsg.indexOf('auth deny') > -1 ||     res.errMsg.indexOf('auth denied') > -1 ) {
                    // 处理用户拒绝授权的情况
                    this.openSetting();
                }    
            }
        })
    },

    showModal(){
        wx.showModal({
            title:"游戏需要得您的用户信息",
            content:"请手动打开设置里的用户信息授权",
            showCancel:false,
            confirmText:"确认",
            success:(result)=>{
                if(result.confirm){
                    this.openSetting();
                }
            }
        })
    },

    openSetting(){
        wx.openSetting({
            success:(authSetting)=>{
                if(authSetting.scope.userInfo){
                    authorizeSuccess();
                }else{

                }
            }
        });
    },

    authorizeSuccess(){
        console.log("获取用户信息");
        var self = this;
        wx.getUserInfo({
            withCredentials:true,
            success: function(res){
                self.loginServer(res);
            },
            fail: function(res){
                // iOS 和 Android 对于拒绝授权的回调 errMsg 没有统一，需要做一下兼容处理
                if (res.errMsg.indexOf('auth deny') > -1 ||     res.errMsg.indexOf('auth denied') > -1 ) {
                    // 处理用户拒绝授权的情况
                }
            }
        })
    },

    loginServer(res){
        var self = this;
        var userInfo = res.userInfo;
        wx.request({
            url:Global.loginUrl,
            data:{
                nick:userInfo.nickName,
                head:userInfo.avatarUrl,
                thirdType:1,
                js_code:self.js_code,
                encryptedData:res.encryptedData,
                iv:res.iv,
                channel:Global.channel,
                os:Global.os,
                ver:Global.ver,
            },
            success:(response)=>{
                if(response!=null){
                    console.log(response);
                    if(response.data&&response.data.code==0){
                        var data = response.data.data;
                        var user = data.user;
                        Global.user = {
                            token:data.token,
                            uid:user.id,
                            openId:user.openId,
                            nick:userInfo.nickName,
                            avatarUrl:userInfo.avatarUrl,
                            gender:userInfo.gender,
                            gold:user.coin,
                            score:user.score,
                            revivedCount:user.revivedCount
                        };
                        this.node.active = false;
                        Global.showLoginPage = false;
                        Global.dealAddReviveBoth();

                        wx.getStorage({
                            key:'skinId',
                            success:(res)=>{
                                Global.bottleSkinId = res.data.bottleSkinId||-1;
                                Global.arrowSkinId = res.data.arrowSkinId||-1;
                                Global.bottleSkinIndex = res.data.bottleSkinIndex||0;
                                Global.arrowSkinIndex = res.data.arrowSkinIndex||0;
                            }
                        })
                    }
                }else{
                    console.log("返回为空");
                }
            },
            fail:function(res){
                console.log(res);
                wx.showModal({
                    title:'登录失败',
                    confirmText:'重试',
                    success:(res)=>{
                        if(res.confirm){
                            cc.director.loadScene('MainMenu');
                        }else{
                            wx.exitMiniProgram();
                        }
                    },
                })
            }
        })
    },
});
