
import utils from "../Network/netUtils";

cc.Class({
    extends: cc.Component,

    properties: {
        addCount: 0,
        progressTag: false
    },

    onLoad() {
        cc.audioEngine.stopAll();
        // this.progressTag = false;
        // this.oldprogressTag = -99;
        // cc.loader.onProgress = (completeCount, totalCount) => {
        //     if (this.progressTag) {
        //         this.progress = (1 * completeCount / totalCount).toFixed(1);
        //         console.log("进度条", this.progress + '%', this.progressNode);
        //         if (this.progressNode != null) {
        //             this.progressNode.getComponent(cc.ProgressBar).progress = this.progress;
        //         }
        //     }
        // };

        //如果不是微信环境
        if (typeof wx === 'undefined') {
            // console.log('cc.sys.platform:', cc.sys.platform);
            this.h5();
            return;
        }
        this.wxEnv();

    },
    start() {
        //预加载
        cc.director.preloadScene('MyCityScene - 004', (completedCount, totalCount, item) => {
            // let progress = (completedCount / totalCount).toFixed(1);
            // console.log("进度条", progress + '%');
            // if (this.progressNode != null) {
            //     this.progressNode.getComponent(cc.ProgressBar).progress = progress;
            // }
            // if(completedCount / totalCount>0){
            // }
        }, () => {
            //onLoaded
            cc.log('Next scene preloaded');
            // cc.director.loadScene('MyCityScene - 004', function () {
            // this.progressTag = false;
            // }.bind(this));
        });
    },

    loginButton() {
        let self = this;
        UtilsPrefabs.init(self.node).addPrefabs(UtilsPrefabs.getPrefabsPath(UtilsPrefabs.LOGINPREFABSNAME.playButton), null, (node) => {

            node.width *= 2;
            node.height *= 2;
            node.setPosition(0, -230);

            node.on(cc.Node.EventType.TOUCH_START, () => {
                node.destroy();
                //显示载入loading
                self._showLoading();
                // () => {
                //     //获取游戏数据
                //     self._gotoScene();//跳转场景
                // }
            })

        })
    },
    h5() {
        let self = this;
        UtilsPrefabs.init(self.node).addPrefabs(UtilsPrefabs.getPrefabsPath(UtilsPrefabs.LOGINPREFABSNAME.login), null, (node) => {
            // UtilsPrefabs.init(self.node).addPrefabs(UtilsPrefabs.getPrefabsPath(UtilsPrefabs.LOGINPREFABSNAME.playButton), null, (node) => {

            //     node.width *= 2;
            //     node.height *= 2;
            //     node.setPosition(0, -230);

            //     node.on(cc.Node.EventType.TOUCH_START, () => {
            //         node.destroy();
            //         self._showLoading();//显示载入loading
            //         //全局函数
            //         //获取游戏数据
            //         self._gotoScene();//跳转场景
            //     })

            // })
        })
    },
    wxEnv() {
        // let self = this;
        // cc.audioEngine.stopAll();
        // this.progressTag = false;
        // this.oldprogressTag = -99;
        // cc.loader.onProgress = (completeCount, totalCount) => {
        //     if (this.progressTag) {
        //         this.progress = (1 * completeCount / totalCount).toFixed(1);
        //         // console.log("进度条", this.progress + '%', this.progressNode);
        //         if (this.progressNode != null) {
        //             this.progressNode.getComponent(cc.ProgressBar).progress = this.progress;
        //         }
        //     }
        // };
        UtilsPrefabs.init(self.node).addPrefabs(UtilsPrefabs.PrefabsName[2], null, (node) => {
            // if (cc.sys.platform != cc.sys.WECHAT_GAME) {
            // }
            //获取登录按钮ui，用wx 接口获取临时链接
            WeChat.onGetPlayButtonPicture((data) => {
                // console.log('按钮图片：', data);
                self.loginbuttonImageUrl = data.tempFileURL;
                self.wxLogin();
            }, (err) => {
                console.error('获取按钮图片失败，检查网络！');
            })
        });
    },

    wxLogin() {
        let self = this;
        let isOnTap = false;

        wx.login({
            success: function (res) {
                if (res.code) {
                    console.log("登陆成功,获取到code", res.code);
                }
                //self.loginbuttonImageUrl
                // type: 'text',
                // text: '开始游戏',
                //image: 'https://7465-test-533989-1259102327.tcb.qcloud.la/pictures/PlayButtonnew.png?sign=545e70218ce3106a7e518fdfb8240c5e&t=1556089089',
                let button = wx.createUserInfoButton({
                    type: 'image',
                    image: self.loginbuttonImageUrl,
                    style: {
                        left: wx.getSystemInfoSync().screenWidth / 2 - 80,
                        top: wx.getSystemInfoSync().screenHeight - 230,
                        width: 160,
                        height: 60,
                        lineHeight: 40,
                        // backgroundColor: '#ff0000',
                        color: '#ffffff',
                        textAlign: 'center',
                        fontSize: 16,
                        borderRadius: 4
                    }
                })
                button.show();
                button.onTap((res) => {
                    // console.log(res)
                    if (res.errMsg == "getUserInfo:ok") {

                        if (isOnTap) return;
                        isOnTap = true;
                        //点击允许，授权
                        // console.log('已经授权。');
                        //全局函数
                        //注册或者登录用户信息
                        WeChat.onRegisterUser(res.userInfo,
                            (res) => {
                                //记录用户信息在全局变量
                                GlobalD.UserInfo = res.result.data.userinfo;
                                userData.openId = res.result.data.openid;
                                // console.log('用户信息：',);
                                //清除微信授权按钮
                                button.destroy();
                                self._showLoading();//显示载入loading
                                //全局函数
                                //获取游戏数据
                                WeChat.onGetGameData((res) => {
                                    console.log('获取的游戏数据：', res);
                                    //记录读取的数据到内存里面
                                    userData.readData = res.data;
                                    self._gotoScene();//跳转场景
                                })

                            }, (fail) => {//登录失败
                                isOnTap = false;
                            });
                    } else {
                        //点击拒绝，没有授权
                        console.log('不允许登录。');
                    }


                })
            }

        });
    },

    update(dt) {
        if (this.progressTag) {
            this.addCount += dt * Math.random();
            let progress = (this.addCount / 0.8);

            if (progress >= 1) {
                //跳转场景
                this._gotoScene();
                this.progressTag = false;
            }
            if (this.progressNode) {
                this.progressNode.getComponent(cc.ProgressBar).progress = progress;
            }
        }
    },

    _showLoading() {
        console.log('显示载入预制');
        //显示载入预制
        UtilsPrefabs.init(this.node)
            .addPrefabs(UtilsPrefabs.PrefabsName[3], null, function (node) {
                node.y = -500;
                var bgbar = UtilsPrefabs.getNode("bgbar", node);
                this.progressNode = UtilsPrefabs.getNode("progress", bgbar);
                this.progressTag = true;
                this.addCount = 0;
            }.bind(this));


    },
    _gotoScene() {
        cc.director.loadScene('MyCityScene - 004', function () {
            // this.progressTag = false;
        }.bind(this));
        // //预加载
        // cc.director.preloadScene('MyCityScene - 004', (completedCount, totalCount, item) => {

        //     let progress = (1 * completedCount / totalCount).toFixed(1);
        //     console.log("进度条", progress + '%');
        //     if (this.progressNode != null) {
        //         this.progressNode.getComponent(cc.ProgressBar).progress = progress;
        //     }
        // }, () => {
        //     //onLoaded
        //     cc.log('Next scene preloaded');
        //     cc.director.loadScene('MyCityScene - 004', function () {
        //         // this.progressTag = false;
        //     }.bind(this));
        // });
    }

});
