const weChat = require('./net/WeChat');
const LoginApi = require('./net/LoginApi');
const DWTool = require('./utils/DWTool');
// var tutorial = require('./utils/Bundle').tutorial;
// console.log(tutorial);

cc.Class({
    extends: cc.Component,

    properties: {

        preloadProgress: cc.ProgressBar,
        preloadLabel: cc.Label,
        updateUI: cc.Node,

        _updating: false,           //是否正在更新
        _canRetry: false,           //能否重新获取更新
        _preloaded: false,          //是否已经预加载完资源
    },

    onLoad() {
        // this._testProto();
        // this.hotUpdate = this.node.getComponent('HotUpdate');
        // this.hotUpdate.init();
        // cc.director.preloadScene("game", () => {
        //     this.hotUpdate.endPreload();
        //     this._startGame();
        //     cc.log("Next scene preloaded");
        // });
        this.loadAllGameRes();
    },

    loadAllGameRes() {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            this.updateUI.active = true;

            // 加载需要的图片资源
            cc.loader.loadResDir("./building", cc.Texture2D, (completeCount, totalCount, res) => {

                console.log("资源总数量: " + totalCount);
                console.log("当前下载中: " + completeCount);
                // 正在加载图片资源中...
                this.preloadProgress.progress = completeCount / totalCount;
                this.preloadLabel.string = '加载游戏资源中，请稍候...' + (this.preloadProgress.progress * 100).toFixed(0) + '%';

            }, (err, res) => {

                Global.buildRes = res;

                this.preloadProgress.progress = 0;
                this.loadSense();

                // 加载图片资源完成, 开始加载首页场景    
                cc.director.preloadScene("game", () => {
                    // 加载完成, 开始进入游戏
                    this.endPreload();
                    this._startGame();
                    cc.log("Next scene preloaded");
                });
            });

        } else {
            this.updateUI.active = false;

            Global.showLoginPage = false;
            Global.channel = 'LuciferChannel';
            Global.os = 1;
            Global.ver = 1;

            let uid = DWTool.getUrlParam('uid');
            let token = DWTool.getUrlParam('token');
            if (!uid && !token) {
                Global.user = {
                    uid: 1,
                    token: 'lucifer_test_token',
                    nick: 'lucifer',
                    avatar: "",
                    gender: 1
                }
            } else {
                Global.user = {
                    uid: uid,
                    token: token,
                    nick: "游客",
                    avatar: "",
                    gender: 1
                }
            }

            this._getUserInfoAndStartGame();
        }
    },

    loadSense() {
        let dis = 0.012
        this.timeCtrl = () => {
            if (parseInt(this.preloadProgress.progress) == 1) {
                this._preloaded = true;
                this.unschedule(this.timeCtrl);
            } else {
                dis = dis < 0.002 ? 0.002 : dis - 0.0001;
                this.preloadProgress.progress += dis;
            }
            this.preloadLabel.string = '正在进入游戏，请稍候...' + (this.preloadProgress.progress * 100).toFixed(0) + '%'
        }

        this.schedule(this.timeCtrl, 0.03);
    },

    /**
     * 预加载结束
     */
    endPreload() {
        this.preloadProgress.progress = 1;
        this.scheduleOnce(() => {
            this.updateUI.active = false;
        }, 0.5)
    },



    _startGame() {

        if (Global.needLogin) {
            //服务端通知登录态失效，重新调起微信登录获取新的token
            weChat.login(() => {
                this._getUserInfoAndStartGame();
            });
        } else {
            //检查登录态
            weChat.checkLogin(flag => {
                if (flag) {
                    //登录态未失效，静默登录
                    weChat.loginStatic(() => {
                        this._getUserInfoAndStartGame();
                    })
                } else {
                    //登录态失效，重新调起微信登录获取新的token
                    weChat.login(() => {
                        this._getUserInfoAndStartGame();
                    });
                }
            })
        }
    },

    _getUserInfoAndStartGame() {
        LoginApi.getUserInfoPromise().then(({ data, msg }) => {
            Global.needLogin = false;
            Global.cityId = data.cityId;
            cc.director.loadScene("game");
        }).catch(({ code, msg }) => {
            console.error(msg);
        });
    },

    _testProto() {
        var Message = tutorial.Message;

        var payload = {
            commonMessage: {
                msg: "我现在来测试一下啦"
            }
        }

        // var errMsg = Message.verify(payload)
        // console.log(errMsg);

        var msg = Message.create(payload);
        console.log('[msg]: ', msg);

        var buffer = Message.encode(msg).finish()
        console.log('[buffer]: ', buffer);

        // var decoded2 = Message.decode(buffer);
        // console.log('[decoded]: ', decoded2);

        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            var socketTask = wx.connectSocket({
                url: "ws://172.16.15.133:8108/connect?uid=1&token=lucifer_test_token&channel=LuciferChannel&ver=1&os=1",
                header: {},
                success: function (ret) {

                }
            })

            socketTask.onOpen(function (res) {
                socketTask.send({
                    data: buffer
                })
            })

            socketTask.onMessage(function (res) {
                var tt = new Uint8Array(res.data)
                var decoded = Message.decode(tt);
                console.log("[Response text msg]: ", decoded);
            })
        } else {
            var ws = new WebSocket("ws://172.16.15.133:8108/connect?uid=1&token=lucifer_test_token&channel=LuciferChannel&ver=1&os=1");
            ws.binaryType = "arraybuffer";

            ws.onopen = function (event) {
                console.log("[Send Text WS was opened]");
            };

            ws.onmessage = function (event) {
                // var buf = new ArrayBuffer(event.data);
                var tt = new Uint8Array(event.data)
                var decoded = Message.decode(tt);
                console.log("[Response text msg]: ", decoded);
                // console.log("response text msg: " + event.data);
                // console.log("response text type: " + typeof(event.data));
            };

            setTimeout(function () {
                ws.send(buffer);
            }, 3000)
        }
    }
});