import {
    _decorator,
    Button,
    instantiate,
    Label,
    loadWasmModuleBullet,
    Node,
    Prefab,
    ProgressBar,
    Sprite,
    SpriteFrame
} from "cc";
import Scene from "db://assets/core/Module/Scene";
import { changeScene, showPanel } from "db://assets/core/Module/UIFast";
import store from "../store/store";
import { observer, render } from "../store/decorators";
import { _asyncThrottle } from "../Utils/Utils";
import { MainGame } from "./MainGame/MainGame";
import { LOG_TYPE, sendLog, sendWebNet, WebNetName } from "db://assets/Scripts/Utils/WebNet/WebNet";
import { BoxPanel } from "db://assets/Scripts/Panels/BoxPanel";
import gameStore from "db://assets/Scripts/store/gameStore";
import { GuideScene } from "db://assets/Scripts/Scenes/GuideScene";
import RulePanel from "db://assets/Scripts/Panels/RulePanel";
import { PrizeScene } from "db://assets/Scripts/Scenes/PrizeScene";

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(Label) timesLabel: Label = null;


    @property(Node) ruleBtn: Node = null;
    @property(Node) prizeBtn: Node = null;

    @property(ProgressBar) progress: ProgressBar = null;
    @property(Node) boxRoot: Node = null;

    @property(Prefab) boxItemPrefab: Prefab = null;

    @property(SpriteFrame) boxStatus0: SpriteFrame = null;
    @property(SpriteFrame) boxStatus1: SpriteFrame = null;
    @property(SpriteFrame) boxStatus2: SpriteFrame = null;


    onLoad() {
        this.startBtn.on(Button.EventType.CLICK, this.clickStart, this);
        this.ruleBtn.on(Button.EventType.CLICK, this.clickRule, this);
        this.prizeBtn.on(Button.EventType.CLICK, this.clickPrize, this);

        sendLog(LOG_TYPE.EXPOSURE, 2);
        sendLog(LOG_TYPE.EXPOSURE, 3);
        sendLog(LOG_TYPE.EXPOSURE, 4);
        sendLog(LOG_TYPE.EXPOSURE, 5);
    }

    async start() {
        if (this.data.from != "Loading") {
            await store.updateIndex();
        }
    }

    clickRule = () => {
        if (!store.checkActTime(true)) return;
        showPanel(RulePanel);
    };

    clickPrize = () => {
        if (!store.checkActTime(true)) return;
        changeScene(PrizeScene);
    }

    @render
    render() {
        const {
            freeTimes = 0,
            boxConfigs = [],
            gameCreditsEach,
        } = store.homeInfo || {};

        if (+freeTimes) {
            this.timesLabel.string = `免费次数：${freeTimes}`;
        } else {
            this.timesLabel.string = `${gameCreditsEach}积分/次`;
        }

        this.boxRoot.removeAllChildren();
        const len = boxConfigs.length;
        let maxIndex = 0;
        for (let i = 0; i < boxConfigs.length; i++) {

            const { id, status, targetLevel } = boxConfigs[i];

            const item = instantiate(this.boxItemPrefab);
            const sp = item.getComponent(Sprite);
            const txt = item.getComponentInChildren(Label);
            txt.string = `通过${targetLevel}关`;

            if (+status == 1 || +status == 2) {
                sp.spriteFrame = this[`boxStatus${status}`];
                maxIndex = Math.max(maxIndex, i);
            } else {
                sp.spriteFrame = this.boxStatus0;
            }

            this.boxRoot.addChild(item);
            item.setPosition(-500 / 2 + i / Math.max(1, len - 1) * 500, 0);

            item.on(Button.EventType.CLICK, () => {
                sendLog(LOG_TYPE.CLICK, 2 + i);
                this.openBox.bind(this, boxConfigs[i])();
            }, this);
        }

        this.progress.progress = maxIndex / Math.max(1, len - 1);

    }

    openBox = _asyncThrottle(async function (item) {
        if (!store.checkActTime()) return;
        const { id, status, targetLevel } = item;
        if (+status != 1) return;
        const { success, data } = await sendWebNet(WebNetName.openBox, { id });
        store.updateIndex();
        if (!success) return;
        await showPanel(BoxPanel, data);
    }, 500)

    clickStart = _asyncThrottle(async () => {
        sendLog(LOG_TYPE.CLICK, 5);

        if (!store.checkActTime()) return;

        await loadWasmModuleBullet();
        const suc = await gameStore.start();
        if (!suc) return

        if (!gameStore.startInfo.guideFlag) {
            changeScene(GuideScene);
        } else {
            changeScene(MainGame);
        }
    });

}

