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";

const { TouchEvent } = egret;
export default class StartScene extends Scene {
    private _net: Net;
    private _monkey: Monkey;
    private _boxListCtrl: BoxListCtrl;
    private _guideView: Guide;
    private _guideCtrl: GuideCtrl;
    static NET_RANGE = 200;
    private _debug: debug;
    async start(data?) {
        this.addUI();
        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 }, 500);
        this.getLayer(LayerTypes.bg).addChild(pic);
        const t2 = Date.now() - __t0__;
        console.log(`首屏(背景显示)时间:${t2 / 1000}s`);

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

        this._boxListCtrl.resume();
        const t3 = Date.now() - __t0__;
        console.log(`关键利益点时间:${t3 / 1000}s`);

        const monkey = new Monkey();
        this.getLayer(LayerTypes.monkey).addChild(monkey);
        monkey.addEventListener('pointUpdate', this.onPointUpdate, this)
        this._monkey = monkey;

        this._guideView = new Guide(this.getLayer(LayerTypes.guide));
        this._guideCtrl = new GuideCtrl(this);

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

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

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

    removeTouchEvent() {
        this.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.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__);
        }
    }

    openBoxMode() {
        submitAfterDostart(() => {
            this._cathchedBoxOpenState.destroy();
            this._cathchedBoxOpenState = null;
            this._isBoxFlying = false;
            setTimeout(() => {
                this.boxListCtrl.resume();
                this._monkey.startShaking();
            }, 2000);
            NetManager.ins.getInfo(() => { this._mode1DostartTag = true; console.log('小孩儿休息完毕.') });
        }, this._cathchedBoxOpenState.boxData.award);
    }

    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;
        }
        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.openBoxMode();
    }

    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() {
        let url = __bgUrl__
        return new Promise((resolve) => {
            RES.getResByUrl(url, (picData) => {
                resolve(picData)
            }, this, RES.ResourceItem.TYPE_IMAGE);
        });
    }

    addUI() {
        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);
    }

    onTap_ruleBtn() {
        // alert('onTap_ruleBtn');
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    onTap_optionBtn() {
        alert('onTap_optionBtn')
    }

    protected get layerKeys() {
        return [
            LayerTypes.bg,
            LayerTypes.kids,
            LayerTypes.guide,
            LayerTypes.net,
            LayerTypes.box,
            LayerTypes.monkey,
            LayerTypes.ui,
            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) }
}