"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 Scene_1 = require("../views/Scene");
var MyImage_1 = require("./MyImage");
var panelCtrl_1 = require("../ctrls/panelCtrl");
var sceneTypes_1 = require("../types/sceneTypes");
var NetManager_1 = require("../../libs/tw/manager/NetManager");
var DataManager_1 = require("../../libs/tw/manager/DataManager");
var GTime_1 = require("../../libs/tc/util/GTime");
var TimeFormat_1 = require("../../libs/tc/enum/TimeFormat");
var GDispatcher_1 = require("../../libs/tc/util/GDispatcher");
var FoodItem_1 = require("./FoodItem");
var Buried_1 = require("../../libs/tw/util/Buried");
var GuidePanel_1 = require("../guidePanel/GuidePanel");
var GCache_1 = require("../../libs/tc/util/GCache");
var ADD_SPEED = 0.05;
var DISAPPEAR_SP = -703; //856
//喂食按钮动画运动时间间隔
var F_TIME_SPACE = 600;
//喂食按钮初始角度
var F_ANGLE = 7;
//清晨
var MORNING_SECOND = 6 * 3600;
//白天开始
var DAY_SECOND_START = 9 * 3600;
//白天结束
var DAY_SECOND_END = 18 * 3600;
var MainScene = (function (_super) {
    __extends(MainScene, _super);
    function MainScene() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        //7个位置可以放置粮食，创建粮食时会随机抽一个
        _this.fPosArr = [0, 1, 2, 3, 4, 5, 6];
        _this.itmePos = -1;
        _this.tick = 0;
        _this.timeTick = 0;
        return _this;
    }
    Object.defineProperty(MainScene.prototype, "skinKey", {
        get: function () { return 'MainScene'; },
        enumerable: true,
        configurable: true
    });
    MainScene.prototype.initEvents = function () {
        this.signInBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_signInBtn, this);
        this.propBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_propBtn, this);
        this.mijiBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_mijiBtn, this);
        this.travelBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_travelBtn, this);
        this.getCoinBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_getCoinBtn, this);
        this.feedBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_feedBtn, this);
        this.skipBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.myCoinGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_myCoinGroup, this);
        GDispatcher_1.GDispatcher.addEvent('buyComplete', this.buyComplete, this);
        GDispatcher_1.GDispatcher.addEvent('useComplete', this.useComplete, this);
    };
    MainScene.prototype.removeEvents = function () {
        this.signInBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_signInBtn, this);
        this.propBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_propBtn, this);
        this.mijiBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_mijiBtn, this);
        this.travelBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_travelBtn, this);
        this.getCoinBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_getCoinBtn, this);
        this.feedBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_feedBtn, this);
        this.skipBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.myCoinGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_myCoinGroup, this);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        GDispatcher_1.GDispatcher.removeEvent('buyComplete', this.buyComplete, this);
        GDispatcher_1.GDispatcher.removeEvent('useComplete', this.useComplete, this);
        if (this.guideLayer) {
            this.removeChild(this.guideLayer);
        }
    };
    MainScene.prototype.start = function () {
        this.percentHeight = 100;
        this.isActPlay = false;
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
    };
    MainScene.prototype.onLoad = function () {
        this.act2.play();
        // this.fengche.visible = false;
        this.fengche.y = this.stage.stageHeight - 1014;
        this.spDisappear = DISAPPEAR_SP; //this.stage.stageHeight - DISAPPEAR_SP;
        DataManager_1.DataManager.ins.petHomeInfoData.statusRemainingTime += 5; //增加5秒确保服务端时间到期
        this.initUI();
        // this.loadImgShuipao();
        this.playAnimation(this.act1, true);
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        //初始化喂食按钮进度条遮罩
        this.initFeedMask();
        this.isGuide = GCache_1.GCache.readCache('isGuide');
        if (!this.isGuide) {
            this.showGuide(1);
        }
    };
    MainScene.prototype.initUI = function () {
        //初始化需要加载资源的ui
        this.initUIRes();
        //初始化不需要家在资源的ui
        this.initUIInfo();
        //初始化海豚状态
        this.initPetState();
        //初始化粮食
        this.createFood();
    };
    //等待主体资源加载完成在显示
    MainScene.prototype.showAllUI = function (isShow) {
        // this.timeBarContainer.visible 	= isShow;
        this['headInfoMc'].visible = isShow;
        this.foodGroup.visible = isShow;
        this.signInBtn.visible = isShow;
        this.propBtn.visible = isShow;
        this.propBtn.visible = isShow;
        this['boat'].visible = isShow;
        this.fengche.visible = isShow;
        this.feedBtn.visible = isShow;
        this.travelBtn.visible = isShow;
        this.getCoinBtn.visible = isShow;
        this.scContaner0.visible = isShow;
        this.scContaner1.visible = isShow;
    };
    MainScene.prototype.initUIRes = function () {
        return __awaiter(this, void 0, void 0, function () {
            var sc1Json, sc1Img, mcFactory, _a, bgtexture;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!this.shuicao1) return [3 /*break*/, 7];
                        this.showAllUI(false);
                        return [4 /*yield*/, RES.getResAsync("haicao_json")];
                    case 1:
                        sc1Json = _b.sent();
                        return [4 /*yield*/, RES.getResAsync("haicao_png")];
                    case 2:
                        sc1Img = _b.sent();
                        mcFactory = new egret.MovieClipDataFactory(sc1Json, sc1Img);
                        this.shuicao1 = new egret.MovieClip(mcFactory.generateMovieClipData());
                        this.scContaner1.addChild(this.shuicao1);
                        this.shuicao1.play(-1);
                        this.shuicao1.scaleX = 0.8;
                        this.shuicao1.scaleY = 0.8;
                        this.shuicao1.y = 10;
                        this.shuicao1.x = 10;
                        return [4 /*yield*/, RES.getResAsync("haicao_json")];
                    case 3:
                        sc1Json = _b.sent();
                        return [4 /*yield*/, RES.getResAsync("haicao_png")];
                    case 4:
                        sc1Img = _b.sent();
                        mcFactory = new egret.MovieClipDataFactory(sc1Json, sc1Img);
                        this.shuicao2 = new egret.MovieClip(mcFactory.generateMovieClipData());
                        this.scContaner0.addChild(this.shuicao2);
                        this.shuicao2.play(-1);
                        //加载水草资源
                        _a = this;
                        return [4 /*yield*/, RES.getResAsync("shuipao_png")];
                    case 5:
                        //加载水草资源
                        _a.imgLoaderData = _b.sent();
                        //加载背景并设置背景图片
                        this.currBgName = this.getBgNameStr();
                        return [4 /*yield*/, RES.getResAsync(this.currBgName)];
                    case 6:
                        bgtexture = _b.sent();
                        this.mainbg.texture = bgtexture;
                        this.showAllUI(true);
                        // setTimeout(function() {	
                        this.getPetGooutReward();
                        _b.label = 7;
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    MainScene.prototype.initUIInfo = function () {
        this.nickName.text = DataManager_1.DataManager.ins.petHomeInfoData.petName;
        var currExp = DataManager_1.DataManager.ins.petHomeInfoData.petExp - DataManager_1.DataManager.ins.petHomeInfoData.currentLevelExp;
        var maxExp = DataManager_1.DataManager.ins.petHomeInfoData.nextLevelExp;
        this.exp.text = currExp + '/' + maxExp;
        this.expBar.value = Math.floor(currExp / maxExp * 100);
        this.LvLb.text = 'Lv.' + DataManager_1.DataManager.ins.petHomeInfoData.petLevel;
        this.myCoin.text = '' + DataManager_1.DataManager.ins.petIndexData.credits;
        this.foodGroup.touchEnabled = false;
        //食物容器初始位置取值
        if (!this.fctnPosArr) {
            this.fctnPosArr = [];
        }
        for (var i = 0; i < 7; i++) {
            this.fctnPosArr[i] = [this['foodCtner' + i].x, this['foodCtner' + i].y];
        }
        if (!this.fidArr) {
            this.fidArr = [];
        }
        var rate = DataManager_1.DataManager.ins.petHomeInfoData.foodNum / DataManager_1.DataManager.ins.petHomeInfoData.feedLimit;
        var angle = Math.floor(rate * 360);
        this.setFeedBar(-F_ANGLE, angle - F_ANGLE, true);
    };
    //
    MainScene.prototype.initPetState = function (sval) {
        if (sval === void 0) { sval = -1; }
        return __awaiter(this, void 0, void 0, function () {
            var state, mcName, _a, pImg;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (this.dolphinMc) {
                            this.petContainer.removeChild(this.dolphinMc);
                            this.dolphinMc = null;
                        }
                        if (this.petStateImg) {
                            this.petStateImg.visible = false;
                        }
                        this.timeBarContainer.visible = false;
                        if (sval == -1) {
                            state = DataManager_1.DataManager.ins.petHomeInfoData.status;
                        }
                        else {
                            state = sval;
                        }
                        mcName = this.getDolphinMcName();
                        _a = state;
                        switch (_a) {
                            case 1: return [3 /*break*/, 1];
                            case 2: return [3 /*break*/, 2];
                            case 3: return [3 /*break*/, 5];
                            case 4: return [3 /*break*/, 6];
                        }
                        return [3 /*break*/, 7];
                    case 1:
                        this.createDolphinMc(mcName + '0');
                        return [3 /*break*/, 7];
                    case 2:
                        if (!!this.petStateImg) return [3 /*break*/, 4];
                        return [4 /*yield*/, RES.getResAsync('petState_png')];
                    case 3:
                        pImg = _b.sent();
                        this.petStateImg = new egret.Bitmap(pImg);
                        this.petContainer.addChild(this.petStateImg);
                        _b.label = 4;
                    case 4:
                        this.petStateImg.visible = true;
                        this.timeBarContainer.visible = true;
                        return [3 /*break*/, 7];
                    case 5:
                        this.createDolphinMc(mcName + '2');
                        return [3 /*break*/, 7];
                    case 6:
                        this.createDolphinMc(mcName + '1');
                        return [3 /*break*/, 7];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    //创建海豚动画
    MainScene.prototype.createDolphinMc = function (mcName) {
        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(mcName + "_json")];
                    case 1:
                        mcJson = _a.sent();
                        return [4 /*yield*/, RES.getResAsync(mcName + "_png")];
                    case 2:
                        mcImg = _a.sent();
                        mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);
                        this.dolphinMc = new egret.MovieClip(mcFactory.generateMovieClipData());
                        this.petContainer.addChild(this.dolphinMc);
                        this.dolphinMc.x = (this.petContainer.width - this.dolphinMc.width) * 0.5;
                        this.dolphinMc.y = (this.petContainer.height - this.dolphinMc.height) * 0.5;
                        this.dolphinMc.play(-1);
                        return [2 /*return*/];
                }
            });
        });
    };
    //签到
    MainScene.prototype.onClick_signInBtn = function () {
        console.log('签到');
        if (!this.isGuide) {
            this.hideGuide();
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.SIGN_IN_PANEL, this.showGuide.bind(this));
        }
        else {
            // NetManager.ins.getSignInfo(function(){
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.SIGN_IN_PANEL);
            // }, 455555);
        }
        //点击埋点，签到
        var dpm = Buried_1.Buried.connectDpm(110, 1, 4);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
    };
    //道具
    MainScene.prototype.onClick_propBtn = function () {
        var _this = this;
        console.log('道具');
        NetManager_1.NetManager.ins.getActToys(function () {
            console.log('道具数据', DataManager_1.DataManager.ins.getActToysListData);
            if (!_this.isGuide) {
                _this.hideGuide();
                panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.PROP_PANEL, _this.showGuide.bind(_this));
            }
            else {
                panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.PROP_PANEL);
            }
        }, DataManager_1.DataManager.ins.petIndexData.activityId, 4, 3);
        //点击埋点，道具
        var dpm = Buried_1.Buried.connectDpm(110, 1, 5);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
    };
    //秘籍
    MainScene.prototype.onClick_mijiBtn = function () {
        console.log('秘籍');
        // this.visible = false;
        panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.RULE_PANEL);
        //点击埋点，秘籍攻略
        var dpm = Buried_1.Buried.connectDpm(110, 1, 6);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
    };
    //出游
    MainScene.prototype.onClick_travelBtn = function () {
        console.log('出游');
        //集卡查询（查询去过哪些地方）,默认查中国
        NetManager_1.NetManager.ins.getCollectRule(this.getCollectRule_Back.bind(this), window['collectRuleIdList'] ? window['collectRuleIdList'][0] : 1);
        //点击埋点，出游
        var dpm = Buried_1.Buried.connectDpm(110, 1, 2);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
    };
    MainScene.prototype.getCollectRule_Back = function (success) {
        if (!success) {
            return;
        }
        if (!this.isGuide) {
            this.hideGuide();
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.TOUR_PANEL, this.showGuide.bind(this));
        }
        else {
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.TOUR_PANEL);
        }
    };
    //赚金币
    MainScene.prototype.onClick_getCoinBtn = function () {
        console.log('赚金币');
        panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.EARN_GOLD_COIN_PANEL);
        //点击埋点，赚金币
        var dpm = Buried_1.Buried.connectDpm(110, 1, 3);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
        if (!this.isGuide) {
            this.hideGuide();
            GCache_1.GCache.writeCache('isGuide', true);
            this.isGuide = GCache_1.GCache.readCache('isGuide');
        }
    };
    //喂食按钮处理
    MainScene.prototype.onClick_feedBtn = function () {
        console.log('喂食');
        if (this.isActPlay) {
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MSG_PANEL, ["啊哦...你操作太快，休息一下~"]);
            return;
        }
        if (DataManager_1.DataManager.ins.petHomeInfoData.foodNum < 25) {
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MSG_PANEL, ["食物不够了~"]);
            return;
        }
        //点击埋点，喂食
        var dpm = Buried_1.Buried.connectDpm(110, 1, 1);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
        // this.feedBtn.scaleX = 1;
        // this.feedBtn.scaleY = 1;
        // this.isfBtnDown = false;
        NetManager_1.NetManager.ins.petFeed(function () {
            //喂食动画处理
            this.initPetState(3);
            setTimeout(function () {
                this.initPetState();
            }.bind(this), 2000);
            //食物进度条减少动画处理
            this.isActPlay = true;
            var rate = DataManager_1.DataManager.ins.petHomeInfoData.foodNum / DataManager_1.DataManager.ins.petHomeInfoData.feedLimit;
            var angle = Math.floor(rate * 360);
            DataManager_1.DataManager.ins.petHomeInfoData.foodNum -= 25;
            var rate2 = (DataManager_1.DataManager.ins.petHomeInfoData.foodNum) / DataManager_1.DataManager.ins.petHomeInfoData.feedLimit;
            var angle2 = Math.floor(rate2 * 360);
            this.setFeedBar(angle - F_ANGLE, angle2 - F_ANGLE);
            //刷新宠物信息
            NetManager_1.NetManager.ins.getPetInfo(function () {
                this.initUIInfo();
            }.bind(this), DataManager_1.DataManager.ins.petIndexData.activityId);
        }.bind(this), DataManager_1.DataManager.ins.petHomeInfoData.petId, 25);
        if (!this.isGuide) {
            this.showGuide(5);
        }
        // GCache.writeCache('isGuide', true);//喂了食，就是老用户了，下次进来就不引导了
    };
    //我的金币
    MainScene.prototype.onClick_myCoinGroup = function () {
        console.log('我的金币');
        NetManager_1.NetManager.ins.weOrder(function (success) {
            if (!success) {
                return;
            }
            console.log('接口返回');
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MY_GOLD_COIN_PANEL);
        }, DataManager_1.DataManager.ins.petIndexData.appId, DataManager_1.DataManager.ins.petIndexData.partnerUserId, 1, 10, 'success');
        //点击埋点，我的金币
        var dpm = Buried_1.Buried.connectDpm(110, 1, 7);
        var dcm = Buried_1.Buried.connectDcm(230, window['skinID'], 0);
        var embedDomain = DataManager_1.DataManager.ins.petIndexData.embedDomain;
        var exposure = Buried_1.Buried.createExposure(dpm, dcm, embedDomain);
        NetManager_1.NetManager.ins.clickLog(exposure);
    };
    //开始也动画跳过
    MainScene.prototype.onClick_skipBtn = function () {
        console.log('跳过');
        this.act2.stop();
        this.startGroup.visible = false;
    };
    /**
     * 购买成功事件监听
     */
    MainScene.prototype.buyComplete = function () {
        this.myCoin.text = '' + DataManager_1.DataManager.ins.petIndexData.credits;
    };
    /**
     * 使用成功事件监听
     */
    MainScene.prototype.useComplete = function () {
        this.refreshState();
    };
    MainScene.prototype.createFood = function () {
        // var fArr:any[] = DataManager.ins.petHomeInfoData.foodList;
        NetManager_1.NetManager.ins.getFoodPiles(function () {
            var fArr = DataManager_1.DataManager.ins.getFoodPilesData.list;
            for (var i = 0; i < fArr.length; i++) {
                var fobj = fArr[i];
                if (this.fidArr.indexOf(fobj.id) == -1) {
                    var posIdx = Math.floor(this.fPosArr.length * Math.random());
                    var fPos = this.fPosArr[posIdx];
                    this.itmePos = fPos;
                    this.fPosArr.splice(posIdx, 1);
                    this.fidArr.push(fobj.id);
                    var fitem = new FoodItem_1.FoodItem(fobj.id, fobj.foodNum, fPos, this.onClick_food.bind(this));
                    this['foodCtner' + fPos].addChild(fitem);
                    fitem.playAct();
                }
            }
        }.bind(this));
    };
    //食物收取点击
    MainScene.prototype.onClick_food = function (item) {
        if (DataManager_1.DataManager.ins.petHomeInfoData.foodNum >= DataManager_1.DataManager.ins.petHomeInfoData.feedLimit) {
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MSG_PANEL, ["啊哦...食物储存达到上限啦", "快去喂食吧~"]);
            return;
        }
        if (this.isActPlay) {
            panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.MSG_PANEL, ["啊哦...您操作太频繁了", "请休息一下~"]);
            return;
        }
        this.isActPlay = true;
        NetManager_1.NetManager.ins.collectFood(function () {
            DataManager_1.DataManager.ins.petHomeInfoData.foodNum += item.fcount;
            var rate = DataManager_1.DataManager.ins.petHomeInfoData.foodNum / DataManager_1.DataManager.ins.petHomeInfoData.feedLimit;
            var angle = Math.floor(rate * 360);
            var rate2 = (DataManager_1.DataManager.ins.petHomeInfoData.foodNum - item.fcount) / DataManager_1.DataManager.ins.petHomeInfoData.feedLimit;
            var angle2 = Math.floor(rate2 * 360);
            this.setFeedBar(angle2 - F_ANGLE, angle - F_ANGLE);
            var ctn = this['foodCtner' + item.pos];
            this.fPosArr.push(item.pos);
            item.removeEvent();
            item.stopAct();
            var endY = this.feedBtn.y - this.foodGroup.y; // this.foodGroup.height - 200;// - this.foodGroup.y;// - item.y;
            var endX = this.feedBtn.x; // - ctn.x;
            var a = this.foodGroup.height - ctn.y;
            var b = ctn.x - this.feedBtn.x;
            var time = Math.sqrt((a * a) + (b * b)) /
                Math.sqrt(this.foodGroup.height * this.foodGroup.height + this.foodGroup.width * this.foodGroup.width) * 600;
            egret.Tween.get(ctn).to({ x: endX, y: endY, scaleX: 0.3, scaleY: 0.3, ease: egret.Ease.circIn }, Math.floor(time)).call(function (item) {
                var pos = item.pos;
                var ctn = this['foodCtner' + pos];
                ctn.x = this.fctnPosArr[pos][0];
                ctn.x = this.fctnPosArr[pos][1];
                ctn.scaleX = 1;
                ctn.scaleY = 1;
                //移除食物id记录
                this.fidArr.splice(this.fidArr.indexOf(item.fid), 1);
                ctn.removeChild(item);
            }, this, [item]);
        }.bind(this), item.fid, DataManager_1.DataManager.ins.petIndexData.activityId);
        if (!this.isGuide) {
            this.showGuide(4);
        }
    };
    MainScene.prototype.onEnterFrame = function () {
        if (this.imgLoaderData) {
            if (this.tick > 15) {
                this.tick = 0;
                this.createShuipao();
                this.showShuipao();
            }
            this.tick++;
            this.moveShuipao();
        }
        var useTime;
        var date = new Date();
        if (this.lastSystemTime) {
            useTime = date.getTime() - this.lastSystemTime;
        }
        else {
            useTime = 1000 / 60;
        }
        this.lastSystemTime = date.getTime();
        var times = useTime / (1000 / 60);
        if (this.timeTick >= 60) {
            var tNum = DataManager_1.DataManager.ins.petHomeInfoData.statusRemainingTime;
            if (tNum > 0) {
                this.timeBar.value = Math.floor(tNum / DataManager_1.DataManager.ins.petHomeInfoData.statusTotalTime * 100);
                tNum -= Math.floor(this.timeTick / 60);
                if (tNum < 0) {
                    tNum = 0;
                }
                DataManager_1.DataManager.ins.petHomeInfoData.statusRemainingTime = tNum;
                var tStr = GTime_1.GTime.formatTime(tNum, TimeFormat_1.TimeFormat.HMS, false, [':', ':', '', '']);
                this.timeLabel.text = '出游时间剩余' + tStr;
                this.timeTick = 0;
                if (tNum == 0) {
                    //刷新状态
                    this.refreshState();
                }
            }
            //刷新背景状态
            var bname = this.getBgNameStr();
            if (this.currBgName != bname) {
                this.currBgName = bname;
                this.loadMainBg();
            }
        }
        this.timeTick += times;
        // console.log('this.timeTick=' + this.timeTick);
        // console.log('times=' + times);
    };
    //切换要加载的图片
    MainScene.prototype.loadMainBg = function () {
        return __awaiter(this, void 0, void 0, function () {
            var bgtexture;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, RES.getResAsync(this.currBgName)];
                    case 1:
                        bgtexture = _a.sent();
                        this.mainbg.texture = bgtexture;
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 刷新鱼的当前状态
     */
    MainScene.prototype.refreshState = function () {
        var currStatus = DataManager_1.DataManager.ins.petHomeInfoData.status;
        NetManager_1.NetManager.ins.getPetStatus(function () {
            var _this = this;
            //切换状态
            if (currStatus == 2) {
                //获取出游奖励
                NetManager_1.NetManager.ins.getPetGooutReward(function () {
                    if (DataManager_1.DataManager.ins.gooutRewardData.hasReward) {
                        //插件抽奖
                        NetManager_1.NetManager.ins.doJoinPlugDraw(_this.doJoinPlugDraw_Back.bind(_this), DataManager_1.DataManager.ins.gooutRewardData.pluginId);
                    }
                }, DataManager_1.DataManager.ins.petIndexData.activityId, DataManager_1.DataManager.ins.petHomeInfoData.petId);
            }
            DataManager_1.DataManager.ins.petHomeInfoData.status = 1; ///测试用
            this.initPetState();
        }.bind(this), DataManager_1.DataManager.ins.petHomeInfoData.petId);
    };
    //初始化喂食遮罩
    MainScene.prototype.initFeedMask = function () {
        this.setMask(this.feedBtn['circleImg0'], this.feedBtn['fContainer'], 70.5, 0, 100, 200);
        this.setMask(this.feedBtn['circleImg1'], this.feedBtn['fContainer'], 70.5, 0, 100, 200);
        this.setMask(this.feedBtn['circleImg2'], this.feedBtn['fContainer'], 0, 0, 72, 200);
        this.setMask(this.feedBtn['circleImg3'], this.feedBtn['fContainer'], 0, 0, 72, 200);
        this.feedBtn['circleImg0'].rotation = -F_ANGLE;
        this.feedBtn['circleImg1'].rotation = -F_ANGLE;
        this.feedBtn['circleImg2'].rotation = 180 - F_ANGLE;
        this.feedBtn['circleImg3'].rotation = 180 - F_ANGLE;
    };
    //获取海豚模型type
    // return type  1.sDolphin 少年  2.mDolphin 中年  3.bDolphin 壮年
    MainScene.prototype.getDolphinMcName = function () {
        var lvNum = DataManager_1.DataManager.ins.petHomeInfoData.petLevel;
        var mcName = '';
        if (lvNum < 4) {
            mcName = 'sDolphin';
        }
        else if (lvNum < 7) {
            mcName = 'mDolphin';
        }
        else if (lvNum < 11) {
            mcName = 'bDolphin';
        }
        return mcName;
    };
    //设置喂食按钮进度条
    MainScene.prototype.setFeedBar = function (currVal, targetVal, isSetAngle) {
        if (isSetAngle === void 0) { isSetAngle = false; }
        if (currVal == targetVal) {
            return;
        }
        if (targetVal > currVal) {
            if (currVal <= 90 - F_ANGLE) {
                this.moveCircleUp(currVal, targetVal, 1, isSetAngle, true);
            }
            else if (currVal <= 90 * 2 - F_ANGLE) {
                this.moveCircleUp(currVal, targetVal, 2, isSetAngle, true);
            }
            else if (currVal <= 90 * 3 - F_ANGLE) {
                this.moveCircleUp(currVal, targetVal, 3, isSetAngle, true);
            }
            else if (currVal <= 90 * 4 - F_ANGLE) {
                this.moveCircleUp(currVal, targetVal, 4, isSetAngle, true);
            }
        }
        else {
            if (currVal > 90 * 3 - F_ANGLE) {
                this.moveCircleDown(currVal, targetVal, 4);
            }
            else if (currVal > 90 * 2 - F_ANGLE) {
                this.moveCircleDown(currVal, targetVal, 3);
            }
            else if (currVal > 90 * 1 - F_ANGLE) {
                this.moveCircleDown(currVal, targetVal, 2);
            }
            else if (currVal > -F_ANGLE) {
                this.moveCircleDown(currVal, targetVal, 1);
            }
        }
    };
    //1/4圆运动
    //圆的减少动画
    MainScene.prototype.moveCircleDown = function (currVal, targetVal, idx) {
        if (currVal == targetVal) {
            console.log('555555555');
            return;
        }
        var tval = 0;
        var time = 0;
        var img = this.feedBtn['circleImg' + (idx - 1)];
        if (targetVal <= 90 * (idx - 1) - F_ANGLE) {
            console.log('rot' + (idx - 1) + '=' + this.feedBtn['circleImg' + (idx - 1)].rotation);
            if (idx < 3) {
                tval = 90 * (idx - 1) - F_ANGLE;
            }
            else {
                tval = 90 * (idx - 1) - F_ANGLE - 360;
            }
            time = Math.floor((currVal - 90 * (idx - 1) + F_ANGLE) / 90 * F_TIME_SPACE);
            console.log('tvaltt===' + tval);
            currVal = 90 * (idx - 1) - F_ANGLE;
            egret.Tween.get(img).to({ rotation: tval }, time).call(function (currVal, targetVal, idx) {
                this.moveCircleDown(currVal, targetVal, idx - 1);
                if (img.rotation == (img.rotation < -F_ANGLE ? targetVal - 360 : targetVal)) {
                    this.isActPlay = false;
                }
                console.log('img.rotation1=' + img.rotation);
                console.log('targetVal1=' + (img.rotation < 0 ? targetVal - 360 : targetVal));
                console.log('this.isActPlay1=' + this.isActPlay);
            }, this, [currVal, targetVal, idx]);
        }
        else {
            if (idx < 3) {
                tval = targetVal;
            }
            else {
                // if(tval > 0){
                tval = targetVal - 360;
                // }
            }
            // time = Math.floor(Math.abs((currVal - targetVal - F_ANGLE) % 90) / 90 * F_TIME_SPACE);
            var mAngle = Math.abs((currVal - targetVal) % 90);
            time = Math.floor(mAngle / 90 * F_TIME_SPACE);
            egret.Tween.get(this.feedBtn['circleImg' + (idx - 1)]).to({ rotation: tval }, time).call(function (targetVal) {
                this.isActPlay = false;
            }, this, [targetVal]);
        }
        console.log('time=' + time);
        //减少时同步下层半圆位置
        if (idx == 3 || idx == 1) {
            this.feedBtn['circleImg' + idx].rotation = tval;
        }
    };
    //当前运动的是哪个方位的1/4（圆增加动画）
    MainScene.prototype.moveCircleUp = function (currVal, targetVal, idx, isSetAngle, isfirst) {
        if (isSetAngle === void 0) { isSetAngle = false; }
        if (isfirst === void 0) { isfirst = false; }
        if (currVal == targetVal) {
            return;
        }
        console.log('idx=' + idx);
        var img = this.feedBtn['circleImg' + (idx - 1)];
        if (isfirst) {
            img.rotation = currVal;
        }
        else {
            img.rotation = 90 * (idx - 1) - 3;
        }
        var tval = 0;
        var time = 0;
        //动画是否还有下一个阶段
        var hasNext = false;
        if (targetVal >= 90 * idx - F_ANGLE) {
            tval = 90 * idx - 3;
            if (idx < 4) {
                hasNext = true;
            }
            else {
                hasNext = false;
            }
            if (isfirst) {
                time = (tval - currVal) / 90 * F_TIME_SPACE;
            }
            else {
                time = F_TIME_SPACE;
                if (Math.floor((currVal + F_ANGLE) / 90) == idx - 1) {
                    time = (90 - (currVal + F_ANGLE) % 90) / 90 * F_TIME_SPACE;
                    console.log('time=' + time);
                }
            }
        }
        else {
            time = (targetVal - 90 * (idx - 1)) / 90 * F_TIME_SPACE;
            tval = targetVal;
            hasNext = false;
        }
        if (isSetAngle) {
            time = 0;
        }
        // console.log('tval=',tval);
        // console.log('currVal=', currVal);
        // console.log('chur=', img.rotation);
        if (img.rotation < 0 && img.rotation < -F_ANGLE) {
            tval -= 360;
        }
        // if(idx == 4){
        // 	tval -= 360;
        // }
        if (hasNext) {
            egret.Tween.get(img).to({ rotation: tval }, Math.floor(time)).call(function (idx, currVal, targetVal) {
                this.moveCircleUp(currVal, targetVal, idx + 1, isSetAngle);
                if (img.rotation == (img.rotation < 0 ? targetVal - 360 : targetVal)) {
                    this.isActPlay = false;
                }
                console.log('img.rotation1=' + img.rotation);
                console.log('targetVal1=' + (img.rotation < 0 ? targetVal - 360 : targetVal));
                console.log('this.isActPlay1=' + this.isActPlay);
            }, this, [idx, currVal, targetVal, isSetAngle]);
        }
        else {
            egret.Tween.get(img).to({ rotation: tval }, Math.floor(time)).call(function (targetVal) {
                this.isActPlay = false;
                console.log('img.rotation=' + img.rotation);
                console.log('targetVal=' + (img.rotation < 0 ? targetVal - 360 : targetVal));
                console.log('this.isActPlay1=' + this.isActPlay);
            }, this, [targetVal]);
        }
        // console.log(time);
    };
    //创建水泡
    MainScene.prototype.createShuipao = function () {
        if (!this.shuipaoArr) {
            this.shuipaoArr = [];
        }
        if (this.shuipaoArr.length < 10) {
            for (var i = 0; i < 50; i++) {
                // let texture = new egret.Texture();
                // texture._setBitmapData(this.imgLoaderData);
                var bitmap = new MyImage_1.default(this.imgLoaderData);
                this.shuipaoArr.push(bitmap);
            }
        }
    };
    //显示水泡
    MainScene.prototype.showShuipao = function () {
        var spaceX = 10;
        var spaceY = 35;
        var sX = 40; //this.travelBtn.x + 40;
        var sY = 0; //this.travelBtn.y - 100;
        if (!this.spMoveArr) {
            this.spMoveArr = [];
        }
        for (var i = 0; i < Math.floor(1 + 8 * Math.random()); i++) {
            var img = this.shuipaoArr.shift();
            this.spMoveArr.push(img);
            var iX = sX + spaceX * Math.random();
            var rdm = Math.random();
            img.x = iX;
            img.y = sY + spaceY * Math.random();
            img.speed = (Math.random() > 0.5 ? 2 : -1);
            img.scaleX = 0.4 + 1.1 * rdm;
            img.scaleY = 0.4 + 1.1 * rdm;
            img.alpha = 0.5 + 0.5 * Math.random();
            //水泡是左移还是右移，还是水平方向没有速度
            var dir;
            if (rdm >= 0 && rdm < 0.3) {
                dir = 1;
            }
            else if (rdm >= 0.3 && rdm < 0.6) {
                dir = -1;
            }
            else {
                dir = 0;
            }
            img.directX = dir;
            sX = sX + spaceX;
            this.spContainer.addChild(img);
        }
    };
    //让水泡动起来
    MainScene.prototype.moveShuipao = function () {
        if (!this.spMoveArr) {
            return;
        }
        var len = this.spMoveArr.length;
        for (var i = 0; i < len; i++) {
            var img = this.spMoveArr[i];
            img.y -= img.speed;
            img.x += 0.5 * img.directX;
            img.speed = img.speed + ADD_SPEED;
            if (img.y <= this.spDisappear + 200 * Math.random()) {
                this.spMoveArr.splice(i, 1);
                this.spContainer.removeChild(img);
                this.shuipaoArr.push(img);
                len--;
            }
        }
    };
    //加载水泡图片
    MainScene.prototype.loadImgShuipao = function () {
        var imgLoader = new egret.ImageLoader();
        imgLoader.addEventListener(egret.Event.COMPLETE, function (e) {
            var imageLoader = e.currentTarget;
            this.imgLoaderData = imageLoader.data;
        }, this);
        imgLoader.load('resource/assets/main_scene/shuipao.png');
    };
    //添加矩形遮罩
    MainScene.prototype.setMask = function (target, tcontainer, tx, ty, tw, th) {
        var square = new egret.Shape();
        square.graphics.beginFill(0xff0000);
        square.graphics.drawRect(0, 0, tw, th);
        square.graphics.endFill();
        square.x = tx;
        square.y = ty;
        tcontainer.addChild(square);
        target.mask = square;
    };
    //获取出游获取的礼物
    MainScene.prototype.getPetGooutReward = function () {
        var _this = this;
        if (DataManager_1.DataManager.ins.petHomeInfoData.status != 2) {
            NetManager_1.NetManager.ins.getPetGooutReward(function () {
                if (DataManager_1.DataManager.ins.gooutRewardData.hasReward) {
                    //插件抽奖
                    NetManager_1.NetManager.ins.doJoinPlugDraw(_this.doJoinPlugDraw_Back.bind(_this), DataManager_1.DataManager.ins.gooutRewardData.pluginId);
                    // PanelCtrl.instance.show(ModuleTypes.REWARD_PANEL);
                }
            }, DataManager_1.DataManager.ins.petIndexData.activityId, DataManager_1.DataManager.ins.petHomeInfoData.petId);
        }
    };
    //根据时间判断，获取当前背景图名字
    MainScene.prototype.getBgNameStr = function () {
        var bName;
        var date = new Date();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        var timeVal = hour * 3600 + minute * 60 + second;
        if (timeVal > MORNING_SECOND && timeVal <= DAY_SECOND_START) {
            this.scContaner0.visible = true;
            this.scContaner1.visible = true;
            bName = 'bgmorning_jpg';
        }
        else if (timeVal > DAY_SECOND_START && timeVal <= DAY_SECOND_END) {
            this.scContaner0.visible = true;
            this.scContaner1.visible = true;
            bName = 'bgday_jpg';
        }
        else {
            this.scContaner0.visible = false;
            this.scContaner1.visible = false;
            bName = 'bgnight_jpg';
        }
        return bName;
    };
    //循环播放动画
    MainScene.prototype.playAnimation = function (target, isLoop) {
        if (isLoop) {
            for (var key in target.items) {
                target.items[key].props = { loop: true };
            }
        }
        target.play();
    };
    /**
     * 插件抽奖接口回调
     * @param success
     */
    MainScene.prototype.doJoinPlugDraw_Back = function (success) {
        if (!success) {
            return;
        }
        //查询插件抽奖结果
        NetManager_1.NetManager.ins.getPlugOrderStatus(this.getPlugOrderStatus_Back.bind(this), DataManager_1.DataManager.ins.doJoinPlugDrawData.orderId, this.pollingCheck.bind(this), 10);
    };
    /**
     * 查询插件抽奖结果回调
     * @param success
     */
    MainScene.prototype.getPlugOrderStatus_Back = function (success) {
        if (!success) {
            return;
        }
        if (DataManager_1.DataManager.ins.getPlugOrderStatusData.result == 2) {
            //中奖了，打开奖励面板
            if (!this.isGuide) {
                panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.REWARD_PANEL, this.showGuide.bind(this));
            }
            else {
                panelCtrl_1.default.instance.show(sceneTypes_1.ModuleTypes.REWARD_PANEL);
            }
        }
    };
    //轮询
    MainScene.prototype.pollingCheck = function (data) {
        return data.result == 0;
    };
    /**
     * 播放引导
     * @param index : 引导步骤 1签到，2确认签到。。。。
     */
    MainScene.prototype.showGuide = function (index) {
        this.hideGuide();
        if (!this.guideLayer) {
            this.guideLayer = new GuidePanel_1.default();
            this.addChild(this.guideLayer);
        }
        this.guideLayer.visible = true;
        var x;
        var y;
        var w;
        var h;
        var tips;
        if (index == 1) {
            x = 750 - this.signInBtn.right - 90;
            y = this.signInBtn.top;
            w = 90;
            h = 100;
            tips = '每天签到可领取金币~';
        }
        else if (index == 3) {
            x = this['foodCtner' + this.itmePos].x - 60;
            y = this['foodCtner' + this.itmePos].y + this.foodGroup.y - 60;
            w = 120;
            h = 120;
            tips = '鱼食每天自动产生，点击收取后给小海豚喂食吧~';
        }
        else if (index == 4) {
            x = this.feedBtn.x - this.feedBtn.width / 2;
            y = this.feedBtn.y - this.feedBtn.height / 2;
            w = this.feedBtn.width;
            h = this.feedBtn.height;
        }
        else if (index == 5) {
            x = this.travelBtn.x + 5;
            y = this.travelBtn.y;
            w = this.travelBtn.width;
            h = this.travelBtn.height;
            tips = '小海豚吃饱啦，马上出游吧~';
        }
        else if (index == 8) {
            x = this.propBtn.x;
            y = this.propBtn.y;
            w = 90;
            h = 100;
            tips = '使用道具可以让小海豚加速回来！';
        }
        else if (index == 10) {
            x = this.getCoinBtn.x;
            y = this.getCoinBtn.y;
            w = this.getCoinBtn.width;
            h = this.getCoinBtn.height;
            tips = '想赚得更多金币？去看看吧~';
        }
        this.guideLayer.updateData(index, x, y, w, h, tips);
    };
    MainScene.prototype.hideGuide = function () {
        if (this.guideLayer) {
            this.guideLayer.dispose();
            this.removeChild(this.guideLayer);
            this.guideLayer = null;
        }
    };
    return MainScene;
}(Scene_1.default));
exports.default = MainScene;
__reflect(MainScene.prototype, "\"/Users/chiwang/Desktop/\u5151\u5427\u5DE5\u4F5C/gameegret20181011/db-game-template/egret/src/mainScene/MainScene\".MainScene");
//# sourceMappingURL=MainScene.js.map