"use strict";
var __reflect = (this && this.__reflect) || function (p, c, t) {
    p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t;
};
var __extends = this && this.__extends || function __extends(t, e) { 
 function r() { 
 this.constructor = t;
}
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]);
r.prototype = e.prototype, t.prototype = new r();
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var NetManager_1 = require("./../../libs/tw/manager/NetManager");
var Scene_1 = require("../views/Scene");
var panelCtrl_1 = require("../ctrls/panelCtrl");
var DataManager_1 = require("../../libs/tw/manager/DataManager");
var Loading_1 = require("../loading/Loading");
var MyImage_1 = require("./MyImage");
var GTime_1 = require("../../libs/tc/util/GTime");
var sceneTypes_1 = require("../types/sceneTypes");
var sceneCtrl_1 = require("../ctrls/sceneCtrl");
var GameScene = (function (_super) {
    __extends(GameScene, _super);
    function GameScene(data) {
        var _this = _super.call(this, data) || this;
        _this.mData = data;
        console.log(data);
        return _this;
    }
    Object.defineProperty(GameScene.prototype, "skinKey", {
        get: function () { return 'GameScene'; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(GameScene.prototype, "groupName", {
        get: function () { return 'game_scene'; },
        enumerable: true,
        configurable: true
    });
    GameScene.prototype.initEvents = function () {
        _super.prototype.initEvents.call(this);
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.gameRoleMc.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_gameRoleMc, this);
        // this.timer.addEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        // this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ontap_beforeStartBtn, this);
    };
    GameScene.prototype.removeEvents = function () {
        _super.prototype.removeEvents.call(this);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.gameRoleMc.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin_gameRoleMc, this);
        // this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.ontap_beforeStartBtn, this);
        // this.timer.removeEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        // this.timer.stop();//停止倒计时
    };
    GameScene.prototype.onSkinComplete = function () {
        _super.prototype.onSkinComplete.call(this);
        // this.mainbg.texture = this.bgtexture;
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    };
    GameScene.prototype.preLoadRes = function () {
        return __awaiter(this, void 0, void 0, function () {
            var mcJson, mcImg, mcFactory;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, RES.getResAsync('lightGameEff_json')];
                    case 1:
                        mcJson = _a.sent();
                        return [4 /*yield*/, RES.getResAsync('lightGameEff_png')];
                    case 2:
                        mcImg = _a.sent();
                        mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);
                        this.lightAct = new egret.MovieClip(mcFactory.generateMovieClipData());
                        return [2 /*return*/, new Promise(function (resolve, reject) {
                                resolve();
                            })];
                }
            });
        });
    };
    GameScene.prototype.start = function (data) {
        _super.prototype.start.call(this, data);
        // this.timer = new egret.Timer(1000);
        this.percentHeight = 100;
        // this.bgImg0.y = -2281;
        // this.bgImg1.y = 1676 - 2281;
        // this.bgImg1.y = this.bgHightArr[0] - 2281;
    };
    GameScene.prototype.onLoad = function () {
        this.initUI();
    };
    GameScene.prototype.initUI = function () {
        this.flowerCount = 0;
        this.scoreCount = 0;
        this.hasPrize = 0;
        this.isStop = 1;
        this.scoreArr = [1, 2, 3, -5];
        this.bgHightArr = [1676, 2229, 2103];
        this.flowerCountArr = [0, 0, 0, 0];
        this.gameRoleMc.y = this.parent.height - 400;
        this.playAnimation(this['roleGameAct0']);
        this.playAnimation(this['roleGameAct1']);
        this.bgImg0.source = 'startBg01_jpg';
        this.bgImg1.source = 'startBg02_jpg';
        this.tick = 0;
        this.addSpeed = 0.1;
        this.currBgIdx = 2;
        this.moveSpeed = 10;
        this.lastSystemTime = 0;
        this.gameRoleMc.addChild(this.lightAct);
        this.lightAct.x = -30;
        this.lightAct.y = -30;
        this.lightAct.visible = false;
    };
    GameScene.prototype.onBegin_gameRoleMc = function () {
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_this, this);
        this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);
    };
    GameScene.prototype.onMove_this = function (e) {
        if (!this.isStop) {
            return;
        }
        //跟随手指或鼠标移动
        this.gameRoleMc.x = e.stageX;
        //触碰边界修复位置
        var ox = 250 * 0.5;
        var px = this.x + this.width - 150 * 0.5;
        if (this.gameRoleMc.x < ox) {
            this.gameRoleMc.x = ox;
        }
        else if (this.gameRoleMc.x > px) {
            this.gameRoleMc.x = px;
        }
    };
    GameScene.prototype.onTap_this = function () {
        this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_this, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);
    };
    GameScene.prototype.onEnterFrame = function () {
        var useTime;
        if (this.lastSystemTime) {
            useTime = GTime_1.GTime.getTimestamp() - this.lastSystemTime;
        }
        else {
            useTime = 1000 / 60;
        }
        this.lastSystemTime = GTime_1.GTime.getTimestamp();
        //本次消耗的时间 / 正常每帧应该消耗的时间 算出倍率
        var times = useTime / (1000 / 60);
        //速度 * 倍率 = 本次应该移动的距离
        if (this.tick > 19) {
            this.moveSpeed = Math.min(this.moveSpeed + this.addSpeed * this.tick / 19, 30);
            this.tick = 0;
        }
        this.moveSpeed *= this.isStop;
        this.tick += times;
        if (!this.flowerArr || this.flowerArr.length < 10) {
            this.createFlower();
        }
        this.moveMap();
        this.falling();
    };
    GameScene.prototype.falling = function () {
        var len = this.flowerArr.length;
        var _loop_1 = function () {
            var img = this_1.flowerArr[i];
            //如果下一次移动y坐标为正数责添加到舞台
            if (img.y + this_1.moveSpeed > 0) {
                this_1.flowerGroup.addChild(img);
            }
            img.y += this_1.moveSpeed;
            isHit = img.hitTest(this_1.gameRoleMc.x - 106.5, this_1.gameRoleMc.y, this_1.hitRect);
            //超出舞台或者跟人物发生碰撞
            if (img.y >= this_1.parent.height + 100 || isHit) {
                this_1.flowerGroup.removeChild(img);
                this_1.flowerArr.splice(i, 1);
                img.y = 0;
                // img.clean();
                len -= 1;
                // i -= 1;
                if (!this_1.flowerCache) {
                    this_1.flowerCache = [];
                }
                this_1.flowerCache.push(img);
            }
            if (isHit) {
                this_1.scoreCount += img.score;
                this_1.showAddAct(img.score);
                if (this_1.scoreCount < 0) {
                    this_1.scoreCount = 0;
                }
                this_1.scoreNumLb.text = this_1.scoreCount + '';
                //结算界面所需道具数量计算
                var val = this_1.flowerCountArr[img.type];
                val++;
                this_1.flowerCountArr[img.type] = val;
                if (img.score > 0) {
                    if (!this_1.canplayEff) {
                        this_1.lightAct.visible = true;
                        this_1.canplayEff = true;
                        this_1.lightAct.gotoAndPlay(0);
                        setTimeout(function () {
                            this.canplayEff = false;
                            this.lightAct.visible = false;
                        }.bind(this_1), 200);
                    }
                    this_1.flowerCount++;
                }
                else {
                    var speed_1 = this_1.moveSpeed;
                    this_1.isStop = 0;
                    setTimeout(function () {
                        this.isStop = 1;
                        this.moveSpeed = speed_1;
                        console.log('this.isStop' + this.isStop);
                    }.bind(this_1), 500);
                    var oy = this_1.gameRoleMc.y;
                    var ox = this_1.gameRoleMc.x;
                    egret.Tween.get(this_1.gameRoleMc).to({ x: ox + 10, y: oy + 10 }, 60, egret.Ease.cubicOut)
                        .to({ x: ox - 10, y: oy + 20 }, 60, egret.Ease.cubicOut)
                        .to({ x: ox + 10, y: oy + 30 }, 60, egret.Ease.cubicOut)
                        .to({ x: ox, y: oy }, 500, egret.Ease.cubicOut);
                }
                this_1.flowerNumLb.text = this_1.flowerCount + '/30';
                //首页是否有礼包可领取处理
                if (this_1.mData) {
                    if (this_1.mData.hasPrize > 0) {
                        this_1.hasPrize = this_1.mData.hasPrize;
                    }
                    else {
                        if (this_1.mData.prizeData) {
                            if (this_1.mData.prizeData.length) {
                                for (var i_1 = 0; i_1 < this_1.mData.prizeData.length; i_1++) {
                                    var idx = this_1.mData.prizeData[i_1].level - 1;
                                    if (!this_1.mData.prizeData[i_1].opened && this_1.flowerCountArr[idx] + this_1.mData.prizeData[i_1].achieveNum >= this_1.mData.flowerCountArr[idx]) {
                                        this_1.hasPrize++;
                                    }
                                }
                            }
                        }
                    }
                }
                if (this_1.flowerCount >= 30 || this_1.scoreCount <= 0) {
                    //gameover
                    this_1.gameRoleMc.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this_1.onBegin_gameRoleMc, this_1);
                    this_1.onTap_this();
                    this_1.removeEventListener(egret.Event.ENTER_FRAME, this_1.onEnterFrame, this_1);
                    this_1.gameSubmit();
                }
            }
        };
        var this_1 = this, isHit;
        for (var i = len - 1; i >= 0; i--) {
            _loop_1();
        }
    };
    //播放加分动画
    GameScene.prototype.showAddAct = function (score) {
        var addLb = new eui.Label();
        addLb.alpha = 0;
        addLb.size = 39;
        addLb.stroke = 1.2;
        addLb.strokeColor = 0x8143be;
        this.addChild(addLb);
        if (score >= 0) {
            addLb.text = '+' + score;
        }
        else {
            addLb.text = score + '';
        }
        var ox = this.gameRoleMc.x;
        var oy = this.gameRoleMc.y;
        addLb.x = ox;
        addLb.y = oy;
        egret.Tween.get(addLb).to({ alpha: 1 }, 50).to({ x: ox + 100, y: oy - 100 }, 500).to({ alhpa: 0 }, 50).call(function () {
            this.removeChild(addLb);
        }, this);
    };
    GameScene.prototype.createFlower = function () {
        var orgY = this.parent.height;
        if (!this.flowerArr) {
            this.flowerArr = [];
        }
        var colCount = 2;
        var contW = Math.floor(750 / colCount);
        var contH = 390;
        var rowCount = 20;
        if (this.flowerArr && this.flowerArr.length > 1) {
            orgY = this.flowerArr[this.flowerArr.length - 1].y + contH;
        }
        for (var j = 0; j < rowCount; j++) {
            for (var i = 0; i < colCount; i++) {
                if (!this.flowerCache) {
                    this.flowerCache = [];
                }
                var img = void 0;
                if (this.flowerCache.length > 0) {
                    img = this.flowerCache.pop();
                }
                else {
                    img = new MyImage_1.default();
                }
                var idx = Math.floor(Math.random() * 4);
                img.source = 'flowerIcon' + idx + '_png';
                img.type = idx;
                // this.flowerGroup.addChild(img);
                this.flowerArr.push(img);
                var iW = 0;
                var iH = 0;
                img.anchorOffsetX = 0;
                img.anchorOffsetY = 0;
                if (idx == 2) {
                    img.anchorOffsetX = 50;
                    img.anchorOffsetY = 50;
                    iW = 70;
                    iH = 70;
                }
                else if (idx == 3) {
                    iW = 72;
                    iH = 70;
                }
                else {
                    iW = 65;
                    iH = 69;
                }
                img.score = this.scoreArr[idx];
                img.iHeight = iH;
                img.iWidth = iW;
                // img.alpha   = 0;
                img.x = i * contW + (contW - iW) * Math.random();
                // img.y       = -200 -j * contH + (contH - iH) * Math.random();
                img.y = orgY - 560 - (j * contH + (contH - iH) * Math.random());
            }
        }
        console.log(this.flowerArr);
    };
    GameScene.prototype.moveMap = function () {
        this.bgImg0.y += this.moveSpeed;
        this.bgImg1.y += this.moveSpeed;
        if (this.bgImg0.y > this.parent.height) {
            var idx = 0;
            if (this.currBgIdx == 3) {
                idx = 1;
                this.currBgIdx = 2;
            }
            else if (this.currBgIdx == 2) {
                idx = 3;
                this.currBgIdx = 1;
            }
            else {
                idx = 2;
                this.currBgIdx = 3;
            }
            this.bgImg0.source = 'startBg0' + idx + '_jpg';
            this.bgImg0.y = this.bgImg1.y - this.bgHightArr[idx - 1];
            console.log('idx=' + idx);
        }
        if (this.bgImg1.y > this.parent.height) {
            var idx = 0;
            if (this.currBgIdx == 3) {
                idx = 1;
                this.currBgIdx = 2;
            }
            else if (this.currBgIdx == 2) {
                idx = 3;
                this.currBgIdx = 1;
            }
            else {
                idx = 2;
                this.currBgIdx = 3;
            }
            this.bgImg1.source = 'startBg0' + idx + '_jpg';
            this.bgImg1.y = this.bgImg0.y - this.bgHightArr[idx - 1];
            console.log('idx1=' + idx);
        }
    };
    GameScene.prototype.ontap_startBtn = function () {
        // PanelCtrl.instance.btnDelay(this.startBtn);
        if (DataManager_1.DataManager.ins.getInfoData.status.code == 3) {
            // 参与次数已用完
            panelCtrl_1.default.instance.showMsg('okBtn', 5, null, null, '今日次数已用完！', '提示');
            return;
        }
        else if (DataManager_1.DataManager.ins.getInfoData.status.code == 2) {
            // 积分不足
            panelCtrl_1.default.instance.showMsg('okBtn', 5, null, null, '到门店购物赚取积分哦', '积分不足');
            return;
        }
        else if (DataManager_1.DataManager.ins.getInfoData.status.code == 1) {
            // 未登录
            panelCtrl_1.default.instance.showMsg('loginBtn', 2, function () {
            });
            return;
        }
        else {
            this.dostart();
        }
    };
    GameScene.prototype.dostart = function () {
        Loading_1.default.instace.show();
        NetManager_1.NetManager.ins.doStart(function (success) {
            var _this = this;
            if (success) {
                NetManager_1.NetManager.ins.getStartStatus(function (data) {
                    console.log('data轮询失败=' + data);
                    Loading_1.default.instace.hide();
                    if (data == 'pollingFaild' || !data) {
                        // PanelCtrl.instance.showMsg('okBtn', 4, null, null, '如积分丢失,联系客服核实！');
                        Loading_1.default.instace.show();
                        return;
                    }
                    else {
                        //开始游戏
                        // PanelCtrl.instance.removeImmediately();
                        panelCtrl_1.default.instance.isLoseCoin = true;
                        _this.hideLevelTitleAct();
                    }
                }, DataManager_1.DataManager.ins.doStartData.ticketId, function () { return DataManager_1.DataManager.ins.getStartStatusData.code == 0; }, 10);
            }
            else {
                Loading_1.default.instace.hide();
                console.log('dostart失败');
                //统一处理异常？？？？？？？
                panelCtrl_1.default.instance.showMsg('okBtn', 4, null, null, '请刷新重试！');
            }
        }.bind(this), false);
    };
    GameScene.prototype.gameSubmit = function () {
        var _this = this;
        Loading_1.default.instace.show();
        NetManager_1.NetManager.ins.gameSubmit(function (success) {
            if (!success) {
                // Loading.instace.hide();
                console.log('gameSubmit接口失败了');
                return;
            }
            //回调捞结果
            NetManager_1.NetManager.ins.getSubmitResult(function (data) {
                if (data == 'pollingFaild' || !data) {
                }
                else {
                    console.log('分数提交成功');
                    Loading_1.default.instace.hide();
                    var gameData = [];
                    for (var i = 0; i < _this.flowerCountArr.length; i++) {
                        var gdata = {};
                        gdata.level = i + 1;
                        if (i > 2) {
                            gdata.flowers = _this.flowerCount;
                        }
                        else {
                            gdata.flowers = _this.flowerCountArr[i];
                        }
                        gameData.push(gdata);
                    }
                    //提交花数
                    NetManager_1.NetManager.ins.submitGameData(function (success) {
                        if (success) {
                            console.log('提交花数成功');
                        }
                        else {
                            console.log('提交花数失败');
                        }
                    }.bind(_this), DataManager_1.DataManager.ins.doStartData.ticketId, gameData, DataManager_1.DataManager.ins.doStartData.submitToken);
                    panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.GAMEOVER_PANEL, {
                        fcountArr: _this.flowerCountArr,
                        scoreArr: _this.scoreArr,
                        score: _this.scoreCount,
                        hasPrize: _this.hasPrize,
                        callBack: function () {
                            sceneCtrl_1.default.instance.change(sceneTypes_1.ModuleTypes.START_SCENE);
                        }.bind(_this)
                    });
                }
            }, DataManager_1.DataManager.ins.gameSubmitData.orderId, 
            //轮询
            function () {
                return DataManager_1.DataManager.ins.gameGetSubmitResultData.flag;
            });
        }, DataManager_1.DataManager.ins.doStartData.ticketId, this.scoreCount, '[]', DataManager_1.DataManager.ins.doStartData.submitToken, "");
    };
    //循环播放动画
    GameScene.prototype.playAnimation = function (target, isLoop) {
        if (isLoop === void 0) { isLoop = true; }
        if (isLoop) {
            for (var key in target.items) {
                target.items[key].props = { loop: true };
            }
        }
        target.play();
    };
    return GameScene;
}(Scene_1.default));
exports.default = GameScene;
__reflect(GameScene.prototype, "\"/Users/chiwang/Desktop/\u5151\u5427\u5DE5\u4F5C/newGame/saolei19.03.06/db-game-template/egret/src/gameScene/GameScene\".GameScene");
//# sourceMappingURL=GameScene.js.map