import { GamePlayModel } from "../../libs/tw/model/game/GamePlayModel";
import Scene from "../views/Scene";
import Box from "./Box";
import BoxListCtrl from "./BoxListCtrl";
import LayerTypes from "./data/LayerTypes";
import debug from "./debug";
import Guide from "./Guide";
import GuideCtrl from "./GuideCtrl";
import Monkey from "./Monkey";
import Net from "./Net";
import BoxOpenState from "./view/BoxOpenState";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { DataManager } from "../../libs/tw/manager/DataManager";
import submitAfterDostart from "../../libs/new_tw/ctrls/submitAfterDostart";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import showAlertPanel from "../ctrls/showAlertPanel";
import Panel from "../views/Panel";
import Tips from "./view/Tips";
import DeclareTextTips from "./view/DeclareText";
import Kids from "./view/Kids";
import River from "./view/River";

const { TouchEvent } = egret;
export default class StartScene extends Scene {
    private _net: Net;
    private _kids: Kids;
    private _monkey: Monkey;
    private _boxListCtrl: BoxListCtrl;
    private _guideView: Guide;
    private _guideCtrl: GuideCtrl;
    static NET_RANGE = 200;
    private _debug: debug;
    private _keyResCounter = 0;
    async start(data?) {
        this.initUI();
        const t1 = Date.now() - __t0__; console.log(`startScene添加到stage:${t1 / 1000}s`)

        const picData: any = await this.getBg();
        const pic = new egret.Bitmap(picData);
        egret.Tween.get(pic).set({ alpha: 0 }).to({ alpha: 1 }, 200);
        this.getLayer(LayerTypes.bg).addChild(pic);
        const t2 = Date.now() - __t0__; console.log(`首屏(背景显示)时间:${t2 / 1000}s`);

        this.getLayer(LayerTypes.ui).visible = true;

        this._boxListCtrl = new BoxListCtrl(this.getLayer(LayerTypes.box));
        await this._boxListCtrl.createFirstBox();
        this._boxListCtrl.resume();
        this.canInteract();

        const monkey = new Monkey();
        this.getLayer(LayerTypes.monkey).addChild(monkey);
        monkey.addEventListener('pointUpdate', this.onPointUpdate, this)
        this._monkey = monkey;
        this._keyResCounter++;
        monkey.addEventListener(egret.Event.COMPLETE, this.checkKeyResource, this);

        this._guideView = new Guide(this.getLayer(LayerTypes.guide));
        this._guideCtrl = new GuideCtrl(this);
        this._keyResCounter++;
        this._guideCtrl.addEventListener(egret.Event.COMPLETE, this.checkKeyResource, this);
        this._guideCtrl.start();
        

        if (__debug__) {
            this._debug = new debug(this.getLayer(LayerTypes.top));
        }
    }

    canInteract() {
        this.getLayer(LayerTypes.bg).touchEnabled = true;
        const t = Date.now() - __t0__; console.log(`可交互时间:${t / 1000}s`);
    }

    checkKeyResource() {
        this._keyResCounter--;
        if (this._keyResCounter != 0) return;
        const t = Date.now() - __t0__; console.log(`关键元素完全时间:${t / 1000}s`);
        
        this._guideCtrl.enableInteract();

        this._kids = new Kids();
        this.getLayer(LayerTypes.kids).addChild(this._kids);
        this.getLayer(LayerTypes.river).addChild(new River());

        const net = new Net();
        this.getLayer(LayerTypes.net).addChild(net);
        this._net = net;
    }

    addTouchEvent() {
        this.getLayer(LayerTypes.bg).addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouch, this);
    }

    removeTouchEvent() {
        this.getLayer(LayerTypes.bg).removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouch, this);
    }

    private _catchedBox: Box;
    private _cathchedBoxOpenState: BoxOpenState;
    onTouch() {
        if (!this.checkCanDoAtion()) return;
        this.doAction();
    }

    _isBoxFlying: boolean;
    doAction() {
        this._net && this._net.doAction();
        if (this._kids) this._kids.doAction();
        const catchedBoxs = this._boxListCtrl.boxs.filter(
            box => Math.abs(box.y - Box.MIDDLE_Y) < StartScene.NET_RANGE);
        const catchedBox = catchedBoxs[0];
        if (catchedBox) { //抓住了，box没有办法再过线消失
            this._boxListCtrl.pause();
            //先从boxlist中移除，使之不再受到boxlistCtrl的控制
            this._boxListCtrl.removeBoxFromList(catchedBox);
            this._catchedBox = catchedBox;
            catchedBox.doThrow();
            this._isBoxFlying = true;
            this.addThrowTick();
        } else {//没有抓住，不需要处理，如果过网了就会自动消失。如果没有过网，下次还能抓。
            this.checkmode1();
        }
    }

    private _mode1DostartTag = true;
    private checkmode1() {
        if (__mode__ == 1) { //发一个空的
            this._mode1DostartTag = false;
            submitAfterDostart(() => {
                NetManager.ins.getInfo(() => { this._mode1DostartTag = true; console.log('小孩儿休息完毕.') });
            }, __award_thanks_score__);
        }
    }

    openBox() {
        submitAfterDostart(() => {
            this._cathchedBoxOpenState.destroy();
            this._cathchedBoxOpenState = null;
            this._isBoxFlying = false;
            let panel: Panel;
            if (DataManager.ins.gameGetSubmitResultData.lottery) {
                panel = PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL)
            } else {
                panel = showAlertPanel('手气不佳 \n 再试一次吧~');
            }
            panel.once('onDestroy', this.onPanelDestroy, this);

            NetManager.ins.getInfo(() => { this._mode1DostartTag = true; console.log('小孩儿休息完毕.') });
        }, this._cathchedBoxOpenState.boxData.award);
    }

    onPanelDestroy() {
        this.boxListCtrl.resume();
        this._monkey.startShaking();
    }

    checkCanDoAtion() {
        if (!DataManager.ins.getInfoData) {
            console.log('getinfo接口没有返回');
            return false;
        }
        if (this._isBoxFlying) {
            console.log('box还在飞呢');
            return false;
        }
        if (!this._mode1DostartTag && __mode__ == 1) {
            console.log('mode1,submitAfterDostart没有执行完成');
            return false;
        }
        if (DataManager.ins.getInfoData.status.code == 2) {//积分不足
            showAlertPanel('积分不足 \n 多赚点积分再来吧');
            return false;
        }
        if (DataManager.ins.getInfoData.status.code == 3) {//参与次数用完
            showAlertPanel('参与次数用完 \n 请明天再来吧');
            return false;
        }
        return true;
    }

    addThrowTick() {
        this.addEventListener(egret.Event.ENTER_FRAME, this.onThrowTick, this);
    }

    removeThrowTick() {
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onThrowTick, this);
    }

    onThrowTick() {
        this._catchedBox.onThrowTick();
        const disX = Math.abs(this._catchedBox.x - this._handX);
        const disY = Math.abs(this._catchedBox.y - this._handY);
        const dis = 100 + __monkeyHandSize__;
        if (disX < dis && disY < dis) {
            this.onCatchedByMonkey();
        } else if (this._catchedBox.vy > 0) {
            this.onNotCatchedByMonkey();
        }
    }

    private _catchedBoxByMoneky: Box;
    onCatchedByMonkey() {
        this.removeThrowTick();
        this._catchedBoxByMoneky = this._catchedBox;
        this._catchedBox = null;
        this.checkmode1();
        this._isBoxFlying = false;

        egret.Tween.get(this._catchedBoxByMoneky)
            .to({ scaleX: 1, scaleY: 1 }, 500)
            .wait(500)
            .to({ alpha: 0 }, 500).call(() => {
                this._catchedBoxByMoneky.destroy();
                this._catchedBoxByMoneky = null;
                this.boxListCtrl.resume();

            }, this);
    }

    onNotCatchedByMonkey() {
        this.removeThrowTick();
        this._cathchedBoxOpenState = new BoxOpenState(this._catchedBox.type);
        this._cathchedBoxOpenState.x = this._catchedBox.x;
        this._cathchedBoxOpenState.y = this._catchedBox.y;
        this.topLay.addChild(this._cathchedBoxOpenState);
        egret.Tween.get(this._catchedBox).to({ alpha: 0 }, 500);
        this._catchedBox = null;
        this._cathchedBoxOpenState.start();
        this.openBox();
    }

    private _handX: number;
    private _handY: number;
    onPointUpdate(e: egret.Event) {
        const p = e.data as egret.Point;
        this._handX = p.x + this._monkey.x;
        this._handY = p.y + this._monkey.y;
        if (this._catchedBoxByMoneky) {
            this._catchedBoxByMoneky.x = this._handX;
            this._catchedBoxByMoneky.y = this._handY;
        }
        if (this._debug) {
            this._debug.shape.x = this._handX;
            this._debug.shape.y = this._handY;
        }
    }
    async getBg() {
        const url = __bgUrl__
        return new Promise((resolve) => {
            RES.getResByUrl(url, (picData) => {
                resolve(picData)
            }, this, RES.ResourceItem.TYPE_IMAGE);
        });
    }

    initUI() {
        const uiLayer = this.getLayer(LayerTypes.ui);
        uiLayer.addChild(this['ruleBtn']);
        uiLayer.addChild(this['optionBtn']);
        this['ruleBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this['optionBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_optionBtn, this);
        uiLayer.addChild(new Tips());
        uiLayer.addChild(new DeclareTextTips());
        uiLayer.visible = false;
    }

    onTap_ruleBtn(e: egret.Event) {
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    onTap_optionBtn(e: egret.Event) {
        PanelCtrl.instance.show(ModuleTypes.OPTIONS_PANEL);
    }

    protected get layerKeys() {
        return [
            LayerTypes.bg,
            LayerTypes.river,
            LayerTypes.guide,
            LayerTypes.kids,
            LayerTypes.net,
            LayerTypes.ui,
            LayerTypes.box,
            LayerTypes.monkey,
            LayerTypes.top,
        ]
    }

    ruleBtn: eui.Button;
    optionBtn: eui.Button;
    protected get skinKey() { return 'Start' }
    get guideView() { return this._guideView }
    get monkey() { return this._monkey }
    get boxListCtrl() { return this._boxListCtrl }
    get net() { return this._net }
    get topLay() { return this.getLayer(LayerTypes.top) }
}