import SkinScene from "../views/SkinScene";
import SceneCtrl from "../ctrls/SceneCtrl";
import PanelCtrl from "../ctrls/PanelCtrl";
import RulePanel from "../Panel/RulePanel";
import Net from "../Net";
import { setShareImg, clearShareImg } from "../utils";
import { MUtils } from "../MUtils";
import Ant from "../Game/Ant/Ant";
import DebugMgr from "../Mgr/DebugMgr";
import { MConst } from "../MConst";
import GameMgr from "../Mgr/GameMgr";
import GameObject from "../Game/GameObject";
import PlayerController, { ControllerDirection } from "../Game/PlayerController";
import { Decorator } from "../Decorator/Decorator";
import Legs from "../Game/Legs";
import { ThroughSubmitData } from "../../libs/tw/data/custom/throughSubmit/ThroughSubmitData";
import DisplayCollider, { Tag } from "../Game/DisplayCollider";
// import { MConfigs } from "../MConfigs";
import PhysicalSystem from "../Game/PhysicalSystem";
import GoldCoin from "../Game/GoldCoin";
import Scene from "../components/Scene";
import Leg, { LegToward } from "../Game/Leg";
import GameStage from "../Game/GameStage";
import WinningPanel from "../Panel/WinningPanel";
import NotWinningPanel from "../Panel/NotWinningPanel";
import RankListPanel from "../Panel/RankListPanel";
import Panel from "../views/Panel";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetName } from "../../libs/tw/enum/NetName";
import StartScene from "./StartScene";
import SceneUILayer from "./SceneUILayer";
import SoundMgr from "../Mgr/SoundMgr";
import SoundPanel from "../Panel/SoundPanel";
import ParticleMgr from "../Mgr/ParticleMgr";
const MConfigs: any = window;

@Decorator.OnLoad
@Decorator.OnUpdate
export default class MainScene extends Scene {
    private playerController: PlayerController = null;
    private ant: Ant = null;
    private gameStage: GameStage = null;
    private curLegs: Legs = null;
    private ui: MainSceneUI = null;

    /**玩家当前得分 */
    public get score() {
        return this._score;
    }
    public set score(v: number) {
        this.ui.labelScore.text = v.toString();
        this._score = v;
    }
    private _score: number = 0;

    private isOver = false;
    private guideLayer: egret.DisplayObjectContainer = null;

    constructor() {
        super();
        //创建游戏舞台
        let gameStage = new GameStage(true);
        gameStage.onGoldCoinEated = (score) => {
            this.score += score;
        }
        this.addChild(gameStage);
        this.gameStage = gameStage;
        GameMgr.instance.particleMgr = new ParticleMgr(this.gameStage);
    }

    private startGame() {
        //创建脚
        let legs = this.createLegs();
        this.curLegs = legs;

        this.startCreateGoldCoin();
    }

    async onLoad() {
        //创建蚂蚁
        let ant = new class extends Ant {
            protected updateLookAt() {
                let nearest: number = Number.POSITIVE_INFINITY;
                let center: egret.Point = undefined;
                this.gameStage.getLegList().forEach(e => {
                    let distance = e.center.subtract(this.center);
                    if (Math.abs(distance.x) > MConfigs.distanceAntToLegWhenAntLook) return;
                    if (distance.length < nearest) {
                        nearest = distance.length;
                        center = e.center;
                    }
                });
                this.doLookAt(center);
            }
        }(this.gameStage);
        ant.land(GameMgr.instance.stage.stageWidth / 2);
        this.gameStage.antLayer.addChild(ant);
        this.ant = ant;
        ant.onDie = () => {
            this.gameOver();
        }

        //创建控制器
        this.playerController = new PlayerController();
        this.addChild(this.playerController);
        GameMgr.instance.playerController = this.playerController;

        this.ui = this.createUILayer(MainSceneUI) as MainSceneUI;

        // localStorage.setItem("guide", "false");
        if (!localStorage.getItem("guide") || localStorage.getItem("guide") == "false") {
            this.isOver = true;
            this.guide();
            this.playerController.once(egret.TouchEvent.TOUCH_BEGIN, () => {
                this.guideLayer.destroy();
                this.isOver = false;
                this.startGame();
            }, this);
        } else {
            this.startGame();
        }
    }

    private guide() {
        let layer = new egret.DisplayObjectContainer();
        layer.touchEnabled = false;
        this.addChild(layer);
        this.guideLayer = layer;
        let tex = RES.getRes("guide_arrows_png") as egret.Texture;
        let guideImg1 = new egret.Bitmap(tex);
        guideImg1.x = this.stage.stageWidth / 2 - guideImg1.width / 2 - 240;
        guideImg1.y = MConst.GroundLine - tex.textureHeight / 2;
        guideImg1.anchorOffsetX = tex.textureWidth / 2;
        guideImg1.anchorOffsetY = tex.textureHeight / 2;
        let label = new eui.Label();
        label.text = "点击屏幕左右控制蚂蚁移动，不要被踩到";
        label.textColor = 0x333333;
        label.size = 30;
        label.x = this.stage.stageWidth / 2 - label.width / 2;
        label.y = MConst.GroundLine + 70;
        layer.addChild(label);

        let onceTween1 = () => {
            egret.Tween.get(guideImg1)
                .to({ scaleX: 1.2, scaleY: 1.2 }, 500)
                .to({ scaleX: 1, scaleY: 1 }, 500)
                .call(onceTween1);
        }
        onceTween1();

        let guideImg2 = new egret.Bitmap(tex);
        guideImg2.x = this.stage.stageWidth / 2 + guideImg2.width / 2 + 240;
        // guideImg2.y = this.stage.stageHeight / 2 - guideImg2.height / 2 + 200;
        guideImg2.y = MConst.GroundLine - tex.textureHeight / 2;
        guideImg2.anchorOffsetX = tex.textureWidth / 2;
        guideImg2.anchorOffsetY = tex.textureHeight / 2;
        guideImg2.scaleX = -1;

        let onceTween2 = () => {
            egret.Tween.get(guideImg2)
                .to({ scaleX: -1.2, scaleY: 1.2 }, 500)
                .to({ scaleX: -1, scaleY: 1 }, 500)
                .call(onceTween2)
        }

        this.ant.setTimer(500, () => { onceTween2() });

        layer.addChild(guideImg1);
        layer.addChild(guideImg2);

        localStorage.setItem("guide", "true");
    }

    private gameOver() {
        this.isOver = true;

        setTimeout(() => {
            NetManager.ins.GameSubmit((success: any) => {
                if (!success) {
                    SceneCtrl.instance.change(StartScene);
                    return;
                }

                NetManager.ins.getOrderStatus((success: any) => {	// 轮询查询订单状态
                    if (!success || DataManager.ins.getData(NetName.GET_ORDER_STATUS).code != "0000000000") {
                        SceneCtrl.instance.change(StartScene);
                        return;
                    }

                    let lotteryData = DataManager.ins.getData(NetName.GET_ORDER_STATUS).data.lottery;
                    let scoreData = DataManager.ins.getData(NetName.GAME_SUBMIT_NEW).data;
                    if (!lotteryData || lotteryData.type === 'thanks') {	// 如果未中奖
                        //未中奖
                        PanelCtrl.instance.show(NotWinningPanel, {
                            score: scoreData.score,
                            highestScore: scoreData.maxScore
                        });
                    } else {
                        //中奖
                        PanelCtrl.instance.show(WinningPanel, {
                            score: scoreData.score,
                            imgUrl: lotteryData.imgUrl,
                            highestScore: scoreData.maxScore,
                            rewardUrl: lotteryData.link
                        });
                    }
                }, window["netData"][window['CFG'].doJoin]["orderId"], () => {
                    return DataManager.ins.getData(NetName.GET_ORDER_STATUS).code != "0000000000"
                }, 10)
            }, window["netData"][window['CFG'].doJoin]["orderId"], this.score);
        }, 1000);
    }

    onUpdate() {
        this.ant.move(this.playerController.direction);
        if (!this.isOver) {
            this.gameLoop();
        }
    }

    private gameLoop() {
        if (this.score >= 8) {
            if (this.curLegs.toward == LegToward.Right) {
                if (this.curLegs.posX > GameMgr.instance.stage.stageWidth / 2) {
                    this.curLegs = this.createLegs();
                }
            } else {
                if (this.curLegs.posX < GameMgr.instance.stage.stageWidth / 2) {
                    this.curLegs = this.createLegs();
                }
            }
        } else {
            if (this.curLegs.toward == LegToward.Right) {
                if (this.curLegs.posX > GameMgr.instance.stage.stageWidth) {
                    this.curLegs = this.createLegs();
                }
            } else {
                if (this.curLegs.posX < 0) {
                    this.curLegs = this.createLegs();
                }
            }
        }
    }

    createLegs() {
        let id = MUtils.randomInt(1, 7);
        let toward = MUtils.randomInt(1, 3) == 1 ? LegToward.Right : LegToward.Left;
        let legs = new Legs(this.gameStage, MConst.LocalRect.Leg[id], RES.getRes(`leg${id}_png`), toward, MConst.legColliderOffset[id]);
        let bornPosX = toward == LegToward.Right ? -800 : GameMgr.instance.stage.stageWidth + 800;
        legs.setInitPosX(bornPosX);
        return legs;
    }

    private startCreateGoldCoin() {
        let onceCreate = () => {
            if (this.isOver) return;

            this.gameStage.createGoldCoin(MUtils.random(0, this.stage.stageWidth));
            this.setTimer(5000, onceCreate);
        }
        onceCreate();
    }
}

@Decorator.Skin("MainSceneUI")
class MainSceneUI extends SceneUILayer {
    get skinKey() { return "MainSceneUI" }
    public btnSound: eui.Button;
    public labelScore: eui.Label;

    onSkinComplete() {
        this.btnSound.onTap(this, () => {
            PanelCtrl.instance.show(SoundPanel);
        });
    }
}