// UI遮罩层
import { GUIEvent, NetworkEvent } from "../../../data/const/EventConst";
import { ViewZOrder } from "../../../data/const/ViewZOrder";
import EventMng from "../../../manager/EventMng";
import { uiCommon } from "../../../utils/UICommon";

const { ccclass, menu, property } = cc._decorator;

@ccclass
@menu("UI/persistNode/UIMask")
export default class UIMask extends cc.Component {
    @property(cc.Node)
    uiMask: cc.Node = null
    @property(cc.Node)
    netWaitMask: cc.Node = null
    @property(cc.Node)
    emptyMask: cc.Node = null

    protected onEnable() {
        cc.game.addPersistRootNode(this.node)
        this.node.zIndex = ViewZOrder.MASK
        this.netWaitMask.active = false;
        this.uiMask.setContentSize(cc.winSize)
        this.node.x = cc.winSize.width / 2
        this.node.y = cc.winSize.height / 2

        EventMng.on(GUIEvent.SHOW_MASK, this.showUiLoadMask, this)
        EventMng.on(NetworkEvent.NETWAIT_MASK, this.showNetWaitMask, this)
        EventMng.on(GUIEvent.SHOW_EMPTY_MASK, this.showEmptyMask, this)
        uiCommon.onRegisterEvent(this.uiMask, this.onClick, this)
        this.uiMask.active = false
    }

    protected onDisable() {
        EventMng.off(GUIEvent.SHOW_MASK, this.showUiLoadMask, this)
        EventMng.off(NetworkEvent.NETWAIT_MASK, this.showNetWaitMask, this)
        EventMng.off(GUIEvent.SHOW_EMPTY_MASK, this.showEmptyMask, this)
        uiCommon.unRegisterEvent(this.uiMask)
    }

    uiload: Map<string, boolean> = new Map()

    /**
     * @param loadUi 加载的UI名称
     * @param loading 加载状态 
     * @returns 
     */
    showUiLoadMask(loadUi: string, loading: boolean) {
        if (loading) {
            this.uiload.set(loadUi, true)
            this.uiMask.active = loading
            this.scheduleOnce(() => {
                this.uiMask.getChildByName("imgBg").active = true
                let animNode = this.uiMask.getChildByName("imgBg").getComponent(cc.Animation)
                animNode.play()
            }, 0.5)
        } else {
            this.uiload.set(loadUi, false)
            let loadComplelte = true
            this.uiload.forEach((loading) => {
                if (loading == true) loadComplelte = false
            })
            if (!loadComplelte) return
            this.uiload.clear()
            this.uiMask.active = false
            this.unscheduleAllCallbacks()
            this.uiMask.getChildByName("imgBg").active = false
        }
    }

    showNetWaitMask(show: boolean = false) {
        this.netWaitMask.active = show;
    }

    onClick() {
        console.warn("ui遮罩层被点击")
    }

    showEmptyMask(show: boolean = false) {
        this.emptyMask.active = show;
    }
}
