const { ccclass, property } = cc._decorator;
@ccclass
export default class BaseUI extends cc.Component {
    public nodeDict: { [name: string]: cc.Node } = {};
    onLoad() {
        this.linkWidget(this.node);
    }

    // 遍历节点树,获取重要节点
    // 节点名字以$开头的节点为重要节点，放进nodeDict中，可以直接拿到，不用拖拽绑定
    // $btn为按钮类型，放进nodeDict，并且绑定按钮点击事件
    // $ui为ui节点，放进nodeDict，并且上面绑定了BaseUI脚本，所以不继续遍历该节点的子节点
    // $btnUI为按钮类型ui节点，放进nodeDict，并且上面绑定了BaseUI脚本，所以不继续遍历该节点的子节点，并且绑定按钮点击事件
    private linkWidget(node: cc.Node) {
        let children = node.children;
        for (let i = 0; i < children.length; i++) {
            let nodeName = children[i].name;
            if (nodeName.substring(0, 1) !== "$") {
                this.linkWidget(children[i]);
                continue;
            }

            let realName = nodeName.substring(1);
            if (this.nodeDict[realName]) {
                cc.error("节点名字重复!" + realName);
                this.linkWidget(children[i]);
                continue;
            }
            let isUI = false;
            this.nodeDict[realName] = children[i];
            if (nodeName.substring(1, 6) === "btnUI") {
                children[i].on('click', this.buttonListener, this);
                isUI = true;
            } else if (nodeName.substring(1, 4) === "btn") {
                children[i].on('click', this.buttonListener, this);
                isUI = false;
            } else if (nodeName.substring(1, 3) === "ui") {
                isUI = true;
            }
            children[i].name = realName;
            this.nodeDict[realName] = children[i];

            if (!isUI) {
                this.linkWidget(children[i]);
            }
        }
    }

    public getNodeByName(name: string): cc.Node {
        return this.nodeDict[name];
    }

    buttonListener(button: cc.Button): void { }
}