import SkinScene from "../views/SkinScene";
import { Decorator } from "../Decorator/Decorator";
import SceneCtrl from "../ctrls/SceneCtrl";
import MainScene from "./MainScene";
import Ant from "../Game/Ant/Ant";
import DisplayCollider, { Tag } from "../Game/DisplayCollider";
import { MConst } from "../MConst";
import PlayerController, { ControllerDirection } from "../Game/PlayerController";
import PhysicalSystem from "../Game/PhysicalSystem";
import GoldCoin from "../Game/GoldCoin";
import Scene from "../components/Scene";
import GameMgr from "../Mgr/GameMgr";
import Loading from "../loading/Loading";
import { NetManager } from "../../libs/tw/manager/NetManager";
import TopLayerCtrl from "../ctrls/TopLayerCtrl";
import { DataManager } from "../../libs/tw/manager/DataManager";
import { NetName } from "../../libs/tw/enum/NetName";
import SceneUILayer from "./SceneUILayer";
import { ThroughSubmitData } from "../../libs/tw/data/custom/throughSubmit/ThroughSubmitData";
import PanelCtrl from "../ctrls/PanelCtrl";
import RankListItem from "../Panel/RankListItem";
import RankListPanel from "../Panel/RankListPanel";
import Panel from "../views/Panel";
import ToastPanel from "../components/ToastPanel";
import SoundMgr from "../Mgr/SoundMgr";
import SoundPanel from "../Panel/SoundPanel";
import ParticleMgr from "../Mgr/ParticleMgr";
import GameStage from "../Game/GameStage";
import { MUtils } from "../MUtils";
import RulePanel from "../Panel/RulePanel";
import { startGameRequest } from "../utils";
import { MTweenObject, MTweenMgr } from "../Game/MTween";

@Decorator.OnUpdate
export default class StartScene extends Scene {
    private gameStage: GameStage = null;
    private ant: Ant = null;

    constructor() {
        super();

        /* let bg = new eui.Image(RES.getRes("start_bg_jpg"));
        this.addChild(bg); */
        this.gameStage = new GameStage(false);
        this.addChild(this.gameStage);
        GameMgr.instance.particleMgr = new ParticleMgr(this.gameStage);

        let uiLayer: SceneUILayer = new StartSceneUI();
        this.addChild(uiLayer);
        this.playGameDemo();
    }

    private playGameDemo() {
        //创建蚂蚁
        let ant = new Ant(this.gameStage);
        this.gameStage.antLayer.addChild(ant);
        ant.land(300);
        this.ant = ant;

        this.antAct();
    }

    private async antAct() {
        let stageCenter = GameMgr.instance.stage.stageWidth / 2;
        let max: number = 0;
        let min: number = 0;
        if (this.ant.x > stageCenter) {
            max = this.ant.x - stageCenter;
            min = 0 + 40;
        } else {
            min = this.ant.x + stageCenter;
            max = GameMgr.instance.stage.stageWidth - 40;
        }
        //创建金币
        let goldCoin = this.gameStage.createGoldCoin(MUtils.random(min, max));
        await this.ant.delay(1000);
        await this.goToEatGoldCoin(goldCoin);
        await this.ant.delay(150);
        this.ant.move(ControllerDirection.None);
        await this.ant.delay(1000);
        this.antAct();
    }

    private goToEatGoldCoin(goldCoin: GoldCoin) {
        if (goldCoin.x > this.ant.x) {
            this.ant.move(ControllerDirection.Right);
        } else {
            this.ant.move(ControllerDirection.Left);
        }

        this.ant.doLookAt(goldCoin.parent.localToGlobal(goldCoin.x, goldCoin.y));

        return new Promise<void>((resolve, reject) => {
            goldCoin.onEated = () => {
                this.ant.doLookAt();
                resolve()
            }
        });
    }

    onUpdate() {
        // this.ant.move(this.playerController.direction);
    }
}

@Decorator.Skin("StartSceneUI")
class StartSceneUI extends SceneUILayer {
    get skinKey() { return "StartSceneUI" }
    public btnLogin: eui.Button;
    public btnStart: eui.Button;
    public btnRank: eui.Button;
    public btnRule: eui.Button;
    public btnRecord: eui.Button;
    public btnSound: eui.Button;
    public labelFreeTime: eui.Label;
    public labelMyCredit: eui.Label;

    onSkinComplete() {
        this.btnLogin.visible = false;
        this.btnStart.visible = false;

        this.btnLogin.onTap(this, () => {
            window["requirelogin"]();
        });

        this.btnRule.onTap(this, () => {
            PanelCtrl.instance.show(RulePanel);
        });

        NetManager.ins.ajaxElement((success: any, res: any) => {
            if (!success && res["code"] != "100201001") { //错误码不是未登录
                return;
            }

            let cfgRes = window["netData"][window['CFG'].getElement];
            if (cfgRes) {
                let element = cfgRes["element"];
                let result: string = "";
                switch (element.status) {
                    case 4:
                        result = '今日无游戏次数';
                        break;
                    case 5:
                        result = "今日免费次数：" + element["freeLimit"];
                        break;
                    case 6:
                        result = `${element.needCredits}${window['CFG'].unitName}/次`;
                        break;
                }

                this.labelFreeTime.text = result;

                this.labelMyCredit.text = "我的积分：" + element["myCredits"];

                if (DataManager.ins.customCfgData["isNotLoginUser"]) {
                    this.btnLogin.visible = true;
                    this.btnStart.visible = false;
                    PanelCtrl.instance.show(ToastPanel, { msg: "您还未登录，请先登录" });
                } else {
                    this.btnLogin.visible = false;
                    this.btnStart.visible = true;
                }
            }
        });

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

        this.btnStart.onTap(this, () => {
            if (!SoundMgr.instance.firstSeted) {
                SoundMgr.instance.musicEnabled = true;
                SoundMgr.instance.effectEnabled = true;
            }

            Loading.instace.show()
            NetManager.ins.doJoin2((success: any) => {
                if (!success) {
                    Loading.instace.hide();
                    return;
                }
                NetManager.ins.getStartStatus((success: any) => {
                    Loading.instace.hide()
                    let res = DataManager.ins.getData(NetName.GAME_START_STATUS_NEW);
                    if (!success) {
                        return;
                    }
                    if (res.code && res.code == "100201007") {
                        PanelCtrl.instance.show(ToastPanel, { msg: `${res["data"]["unitName"]}不足，多赚点${res["data"]["unitName"]}再来吧` });
                        return;
                    }
                    if (res.code && res.code != "0000000000") return;

                    //开始游戏
                    SceneCtrl.instance.change(MainScene);
                }, /* DataManager.ins.getData(NetName.DO_JOIN_DATA2).data */window["netData"][window['CFG'].doJoin]["orderId"], () => {
                    return DataManager.ins.getData(NetName.GAME_START_STATUS_NEW).code != "0000000000";
                }, 10);
            });
        });

        this.btnRecord.onTap(this, () => {
            window.location.href = this.gotoRecord();//window["recordUrl"];
        });
    }

    private gotoRecord(): string {
        let recordUrl: string;
        let oaId: number;
        if (DataManager.ins.customCfgData) {
            oaId = DataManager.ins.customCfgData.oaId;
            recordUrl = DataManager.ins.customCfgData.recordUrl;
        } else {
            oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
            recordUrl = window['recordUrl'];
        }

        if (recordUrl.indexOf('?') != -1) {
            recordUrl += '&origins=' + oaId + '00';
        } else {
            recordUrl += '?origins=' + oaId + '00';
        }

        return recordUrl;
    }
}