import Panel from "../../libs/new_wx/components/Panel";
import StartSceneBase from "../../libs/new_wx/components/StartSceneBase";
import PanelCtrl from "../../libs/new_wx/ctrls/panelCtrl";
import { ModuleTypes } from "../../libs/new_wx/types/sceneTypes";
import EgretRender from "../physics/EgretRender";
import getAngle from "../physics/utils/getAngle";
import getRotation from "../physics/utils/getRotation";
import check from "./check";
import check2 from "./check2";
import createBox from "./createBox";
import createItems from "./createItems";
import { initLevel, resetLevel, updateLevelView, resetData } from "./level";
import { playToastSuccess } from "./playMovieClip";
import doStart from "../../libs/new_tw/ctrls/doStart";
import wait from "../../libs/new_tc/wait";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { globalData, showToast, doJoin, getNgameStartStatus, getRecordUrl } from "../hdTool";
import Loading from "../../libs/new_wx/components/Loading";

export default class StartScene extends StartSceneBase {
    _engine: Matter.Engine;
    _egretRender: EgretRender;
    private _lastTimestamp = 0;
    _startStandbyBubblesLeft: number;
    _startStandbyBubblesRight: number;
    egretRenderContainer: egret.Sprite;
    _currentDisplay: egret.DisplayObject;

    private removeGuideAndResume() {
        this['guide'].visible = this['tips'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = false;
        this._lastTimestamp = 0;
        egret.ticker.resume(); // 打开渲染与心跳
        this['group'].addChildAt(this.egretRenderContainer, 5);
    }

    onCollision(body: Matter.Body) {
        if (localStorage.getItem('guilde1') == '1') return;
        PanelCtrl.instance.closeCurrent();
        localStorage.setItem('guilde1', '1');
        egret.ticker.pause(); // 关闭渲染与心跳
        this['guide'].visible = this['tips'].visible = true;
        this['group'].addChild(this.egretRenderContainer);
    }

    onCollisionBoom(body: Matter.Body) {
        if (localStorage.getItem('guilde2') == '1') return;
        PanelCtrl.instance.closeCurrent();
        localStorage.setItem('guilde2', '1');
        egret.ticker.pause(); // 关闭渲染与心跳
        this['guide'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = true;
        // this['group'].addChild(this.egretRenderContainer);
    }

    async start(data?) {
        super.start();
        resetData();
        initLevel(this);
        //标题适配
        if (this.stage.stageHeight < 1170) {
            this["title"].y = 1170 - this.stage.stageHeight
        }
        //加个我的奖品按钮
        let recordBtn = this.addChild(new eui.Image("//yun.duiba.com.cn/db_games/activity/qiaoqiaoban1207/recordBtn.png"))
        recordBtn.x = 20, recordBtn.y = 15;
        recordBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            recordBtn.touchEnabled = false;
            setTimeout(() => { recordBtn.touchEnabled = true; }, 1000)
            window.location.href = getRecordUrl('00');
        }, this)
        // console.log(recordBtn)
        // wait(5000).then(()=>PanelCtrl.instance.addMask());
        egret.lifecycle.onPause = () => {
            console.log("app 进入后台");
            egret.ticker.pause(); // 关闭渲染与心跳
        }
        egret.lifecycle.onResume = () => {
            console.log("app 进入前台");
            if (this['guide'].visible == false) {
                this._lastTimestamp = 0;
                egret.ticker.resume(); // 打开渲染与心跳
            }
        }

        //创建引擎
        const engine = Matter.Engine.create();
        this._engine = engine;

        //创建egret渲染
        this.egretRenderContainer = new egret.Sprite();
        this._egretRender = new EgretRender(this.egretRenderContainer, this._engine);
        this['group'].y = this.stage.stageHeight - 1624;
        this['group'].addChildAt(this.egretRenderContainer, 5);
        this['group'].addChild(this['leftBtn']);
        this['group'].addChild(this['rightBtn']);
        this['group'].addChild(this['guild2pic']);
        this['group'].addChild(this['startBtnBg']);
        this['group'].addChild(this['startBtn']);
        this['group'].addChild(this['countTxt']);
        this['guide'].visible = this['tips'].visible = this['tips2'].visible = this['guild2pic'].visible = this['getitBtn'].visible = false;

        // run the engine
        this.runEngine();

        const options: any = {
            width: 750,
            height: 1624,
            wireframes: !1,
        };

        const render = Matter.Render.create({
            element: document.getElementById('debugCanvas'),
            engine: engine,
            options: options
        });
        Matter.Render.run(render);

        // this.initJoker(this['joker']);
        this.initLights(this['lights1'], this['lights2']);
        this['boomalert'].height = this.stage.stageHeight;
        this.runGame();
    }

    async initLights(img1: eui.Image, img2: eui.Image) {
        img1.alpha = 0;
        img2.alpha = 1;
        const freq = 500;
        egret.Tween.get(img1, { loop: true })
            .set({ alpha: 1 }).wait(freq)
            .set({ alpha: 0 }).wait(freq);
        egret.Tween.get(img2, { loop: true })
            .set({ alpha: 0 }).wait(freq)
            .set({ alpha: 1 }).wait(freq);
    }

    _seesaw: Matter.Body;
    async runGame() {
        const { seesaw } = createBox(this);
        this._seesaw = seesaw;

        const reslist = ['boom', 'gift2', 'candy2',
            'donut',
            'egg',
            'icecream']
        await Promise.all(
            reslist.map(res => RES.getResAsync(`${res}_json`))
        );

        // createItems(this);

        let touchLeft = false;
        let touchRight = false;
        let angle = 0;
        const rotationLimit = 30;
        const ontick = () => {
            if (touchLeft)
                angle += getAngle(-1);
            if (touchRight)
                angle += getAngle(1);
            let rotation = getRotation(angle);
            if (rotation > rotationLimit) {
                rotation = rotationLimit;
                angle = getAngle(rotationLimit);
            }
            if (rotation < -rotationLimit) {
                rotation = -rotationLimit;
                angle = getAngle(-rotationLimit);
            }

            this['joker'].rotation = -rotation;
            Matter.Body.setAngle(seesaw, getAngle(rotation));
            return false;
        }

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, (e: egret.TouchEvent) => {
                touchLeft = e.stageX < 375;
                touchRight = !touchLeft;
                ontick();
                egret.startTick(ontick, this);
                if (this['guide'].visible) {
                    this.removeGuideAndResume();
                }
            }, this);
        });

        this['getitBtn'].addEventListener(egret.TouchEvent.TOUCH_TAP, (e: egret.TouchEvent) => {
            this.removeGuideAndResume();
        }, this);

        [this['leftBtn'], this['rightBtn']].forEach(btn => {
            btn.addEventListener(egret.TouchEvent.TOUCH_END, (e: egret.TouchEvent) => {
                egret.stopTick(ontick, this);
            }, this);
        });

        PanelCtrl.instance.addEventListener('onPanelRemoved', this.onPanelRemoved, this);

        const createMask = () => {
            const s = new egret.Sprite();
            s.graphics.beginFill(0, 0.7);
            s.graphics.drawRect(0, 0, 750, 1624);
            s.graphics.endFill();
            return s
        }
        this['guide'].addChild(createMask())
        this['startBtnBg'].addChild(createMask())

        // this.updateGetInfoView();
        // this.updateExemptionTxt();
        if (!globalData.element) return;
        this.startBtn.visible = this['startBtnBg'].visible = this.countTxt.visible = true;
        this.updateCountTxt();
    }
    updateCountTxt() {
        const { freeLimit, status, needCredits, myCredits } = globalData.element;
        if (freeLimit >= 1) {
            this.countTxt.text = "免费游戏次数：" + freeLimit
        } else if (status == 4) {
            this.countTxt.text = "今日无剩余次数"
        } else if (status == 3) {
            this.countTxt.text = "无剩余次数"
        }
        else {
            if (status == 1) {
                this.countTxt.text = (window["CFG"].unitName || "积分") + "不足";
            } else {
                this.countTxt.text = "每局消耗" + needCredits + (window["CFG"].unitName || "积分");
            }
        }
    }

    async onPanelRemoved(e: egret.Event) {
        const panel = e.data.panel as Panel;
        if (panel.type == ModuleTypes.BoomNoPrizePanel || panel.type == ModuleTypes.BoomPrizePanel) {
            await updateLevelView(false);
            await playToastSuccess(this, 0);
            createItems(this);
        } else if (panel.type == ModuleTypes.CashBigPrize || panel.type == ModuleTypes.CashNoPrizePanel || panel.type == ModuleTypes.CashPrizePanel) {
            resetLevel();
            this['startBtnBg'].visible = this['startBtn'].visible = this['countTxt'].visible = true;
            // this.updateStartBtnStatus();
            this.updateCountTxt();
        }
        else if (panel.type == ModuleTypes.ALERT_PANEL) {
            this['startBtnBg'].visible = this['startBtn'].visible = this['countTxt'].visible = true;
            // this.updateStartBtnStatus();
            this.updateCountTxt();
        }
    }

    runEngine() {
        egret.startTick(this.onTick, this);
    }

    private onTick(timestamp: number) {
        if (this._lastTimestamp === 0) {
            this._lastTimestamp = timestamp;
            return;
        }
        let delta = timestamp - this._lastTimestamp;
        if (delta > 20)
            delta = 20;
        this._lastTimestamp = timestamp;
        Matter.Engine.update(this._engine, delta);
        this._egretRender.run();
        // this._debugRender.run();
        check(this);
        check2(this);
        return false;
    }

    onTap_startBtn(e?: egret.Event) {
        // doStart((success) => {
        //     if (!success) return;
        //     wait(1000).then(() => NetManager.ins.getInfo())
        //     this['startBtnBg'].visible = false;
        //     this['startBtn'].visible = false;
        //     this['countTxt'].visible = false;
        //     createItems(this);
        // });
        if (window["CFG"].isNotLoginUser) {
            showToast("您未登录，正在尝试登录中")
            // console.log('调用登录方法');
            if (window['requirelogin']) {
                window['requirelogin']();
            } else if (window['requireLogin']) {
                window['requireLogin']();
            } else {

            }
        }
        //没有次数
        else if (globalData.element) {
            //判断次数
            const { freeLimit, status } = globalData.element;
            if (freeLimit >= 1) {
                this.doJoin();
            } else if (status == 4 || status == 3) {
                showToast("参与次数已达上限")
            } else {
                if (status == 1) {
                    showToast((window["CFG"].unitName || "积分") + "不足")
                } else {
                    this.doJoin()
                }
            }
        } else {
            showToast("网络异常，请稍后再试")
        }
    }
    async doJoin() {
        console.log(123213)
        Loading.instace.show()
        const doJoinData = await doJoin()
        Loading.instace.hide();
        if (doJoinData.success) { //轮询
            Loading.instace.show();
            const startData = await getNgameStartStatus(doJoinData.data)
            Loading.instace.hide();
            if (startData.success) {//轮询成功
                this['startBtnBg'].visible = false;
                this['startBtn'].visible = false;
                this['countTxt'].visible = false;
                createItems(this);
            }
        }
    }

    destroy() {
        super.destroy();
    }
}