import { _decorator, Button, game, Label, Node, screen, UI, UITransform, Widget } from 'cc';
import Scene from "db://assets/Module/Scene";
import { MainGame } from "./MainGame/MainGame";
import { changeScene, showPanel } from "db://assets/Module/UIFast";
import store from "../store/store";
import { observer, render } from "../store/decorators";
import { _asyncThrottle } from "../Utils/Utils";
import GameMgr from "../GameMgr";
import RankPanel from "../Panels/RankPanel";
import { UIMgr } from "../../Module/UIMgr";
import BackPanel from "../Panels/BackPanel";
import { GuideGame } from "./MainGame/GuideGame";
import ErrorPanel from "../Panels/ErrorPanel";

const { ccclass, property } = _decorator;

@observer
@ccclass('HomeScene')
export class HomeScene extends Scene {

    static bundle: string = "HomeScene";
    static skin: string = "HomeScene";
    // static group: string[] = ["HomeScene"];


    @property(Node) startBtn: Node = null;
    @property(Node) ruleBtn: Node = null;
    @property(Node) rankBtn: Node = null;
    @property(Node) backBtn: Node = null;

    onLoad() {

        this.startBtn.on(Button.EventType.CLICK, this.clickStart, this);
        this.ruleBtn.on(Button.EventType.CLICK, this.clickRule, this);
        this.rankBtn.on(Button.EventType.CLICK, this.clickRank, this);
        this.backBtn.on(Button.EventType.CLICK, this.clickBack, this);
    }

    async start() {

        await store.updateIndex();

        UIMgr.ins.preloadScene(MainGame);

    }

    @render
    render() {
        // const {} = store.homeInfo || {};
    }

    clickStart = _asyncThrottle(async () => {

      const isTest = location.href.indexOf("credits-test") > -1 || location.href.indexOf("172") > -1;

        if(!store.miniAppQuery.entryTokenId && !isTest) {
            showPanel(ErrorPanel, { code: 400001 });
            return;
        }

        const { alreadyGuideSteps, allGuideSteps } = store.homeInfo;

        // 改成不记录步数
        if (alreadyGuideSteps < 1) {
            changeScene(GuideGame);
        } else {
            const success = await GameMgr.ins.start();
            if (!success) {
                return;
            }
            changeScene(MainGame);
        }

    });

    clickRule = _asyncThrottle(async () => {
        // showPanel(RulePanel);
        changeScene(GuideGame, { from: "HomeScene" });
    });

    clickRank = _asyncThrottle(() => {
        showPanel(RankPanel);
    });

    clickBack = _asyncThrottle(() => {
        showPanel(BackPanel);
    });

}

