import { _decorator, assetManager, find, instantiate, Prefab, Node, Label } from 'cc';
import Scene from "db://assets/core/Module/Scene";
import { changeScene, showPanel, showShareGuide, showToast } from "db://assets/core/Module/UIFast";
import { AudioClipName, AudioMgr } from "db://assets/core/base/AudioMgr";
import { HomeScene } from "db://assets/Scripts/Scenes/HomeScene";
import { RoleCarColorsSysterm } from "./Systerms/RoleCarColorsSysterm";
import { CarCarColorsSysterm } from "./Systerms/CarCarColorsSysterm";
import { PlatformManager } from "db://assets/ScriptFrame/Frame/platformManager";
import gameStore from "db://assets/Scripts/store/gameStore";
import { CarColorsGlobalInstance } from "db://assets/Scripts/Scenes/MainGame/CarColorsGlobalInstance";
import { UnlockPanel } from "db://assets/Scripts/Panels/UnlockPanel";

const { ccclass, property } = _decorator;

@ccclass('MainGame')
export class MainGame extends Scene {

    static ins: MainGame = null;

    static skin: string = "MainGame";
    static bundle: string = "MainGame";

    @property(Node) gamePre: Node = null;
    @property(Node) parkPoints: Node = null;

    onLoad() {
        MainGame.ins = this;
        this.gamePre.active = false;
        this.flushParkPoints();
    }

    onDestroy() {
        MainGame.ins = null;
    }

    async start() {
        // 人物管理系统
        CarColorsGlobalInstance.instance.roleSysterm = this.node.getComponent(RoleCarColorsSysterm)
        await CarColorsGlobalInstance.instance.roleSysterm.loadRolePrefabs();

        // 汽车管理系统
        CarColorsGlobalInstance.instance.carSysterm = this.node.getComponent(CarCarColorsSysterm)

        await this.nextLevel();
    }

    showPre() {
        this.gamePre.active = true;
        const isLevel1 = gameStore.startInfo.level === 1;
        this.gamePre.getChildByName("第二关").active = !isLevel1;
        this.gamePre.getChildByName("第一关").active = isLevel1;
        this.gamePre.getChildByName("txt").getComponent(Label).string = `第 ${gameStore.startInfo.level} 关`;
        this.scheduleOnce(() => {
            this.gamePre.active = false;
        }, 2);
    }

    flushParkPoints() {
        this.parkPoints.children.forEach((child, index) => {
            if (index < 4) {
                child.name = "empty";
            } else if (index == 4) {
                child.name = "lock";
                child.children[0].children[0].active = false;
                if (gameStore.startInfo.shareUnlocked) {
                    child.children[0].children[1].active = false;
                    if (child.children[0].children[2]) {
                        child.children[0].children[2].active = true;
                    }
                } else {
                    child.children[0].children[1].active = true;
                    if (child.children[0].children[2]) {
                        child.children[0].children[2].active = false;
                    }
                }
            } else {
                child.name = "lock";
                child.children[0].children[0].active = false;
                child.children[0].children[1].active = true;
            }
            child.children[1]?.destroy();
            child.children[1]?.removeFromParent();
        });
    }

    getLockPoints() {
        const points = this.parkPoints.children;
        if (points[4].name == "lock") {
            return 4;
        } else if (points[5].name == "lock") {
            return 5;
        } else if (points[6].name == "lock") {
            return 6;
        }
        return null;
    }

    unlockPoint(index: number) {
        const points = this.parkPoints.children;
        points[index].name = "empty";
        points[index].children[0].children[0].active = true;
        points[index].children[0].children[1].active = false;
        AudioMgr.ins.playOneShot(AudioClipName.upgrade);
    }

    shareUnlock() {
        if (gameStore.startInfo.shareUnlocked) {
            CarColorsGlobalInstance.instance.roleSysterm.isGaming = false
            showPanel(UnlockPanel, {
                type: "green",
                onSuccess: () => {
                    this.unlockPoint(4);
                    CarColorsGlobalInstance.instance.roleSysterm.isGaming = true;
                }
            });
        } else {
            showShareGuide();
            this.scheduleOnce(() => {
                if (gameStore.startInfo.shareUnlocked) return;
                gameStore.startInfo.shareUnlocked = true;
                gameStore.unlockPark("share");
                this.unlockPoint(4);
            }, 5);
        }
    }

    videoUnlock1() {
        CarColorsGlobalInstance.instance.roleSysterm.isGaming = false;
        showPanel(UnlockPanel, {
            type: "credits",
            onSuccess: () => {
                this.unlockPoint(5);
                CarColorsGlobalInstance.instance.roleSysterm.isGaming = true;
            }
        });
    }

    videoUnlock2() {
        CarColorsGlobalInstance.instance.roleSysterm.isGaming = false;
        showPanel(UnlockPanel, {
            type: "credits",
            onSuccess: () => {
                this.unlockPoint(6);
                CarColorsGlobalInstance.instance.roleSysterm.isGaming = true;
            }
        });
    }

    async nextLevel() {
        if (gameStore.startInfo.level >= 5) {
            gameStore.submit(true);
            return;
        }

        if (gameStore.startInfo.level != 0) {
            gameStore.middleSubmit();
        }

        gameStore.startInfo.level++;

        this.showPre();
        this.flushParkPoints();

        CarColorsGlobalInstance.instance.roleSysterm.clearAll();
        CarColorsGlobalInstance.instance.carSysterm.clearAll();

        find("Scene/Roles").removeAllChildren();
        find("Scene/Levels").removeAllChildren();

        const level = await new Promise<Prefab>((resolve) => {
            assetManager.getBundle("MainGame")
                .load(`Levels/level${gameStore.startInfo.level}`, Prefab, (err, prefab: Prefab) => {
                    if (err) {
                        resolve(null);
                        return;
                    }
                    resolve(prefab);
                });
        });

        if (!level) {
            showToast("没有更多关卡了");
            changeScene(HomeScene);
            return;
        }

        const levelNode = instantiate(level);
        find("Scene/Levels").addChild(levelNode);
        for (let i = 0; i < levelNode.children.length; i++) {
            CarColorsGlobalInstance.instance.carSysterm.addCar(levelNode.children[i]);
        }
        CarColorsGlobalInstance.instance.roleSysterm.initLevel();

        AudioMgr.ins.playOneShot(AudioClipName.start);
    }

}


