import {
    shortcut,
    extend,
    i18nText,
    each,
    createWidget,
    Controller,
    isArray, isNotEmptyArray, UUID, defaults, Tree, VerticalLayout
} from "@/core";
import { Pane } from "@/base";
import { BasicTreeItem, BasicTreeNode, LevelTree, TreeExpander } from "@/case";

@shortcut()
export class SelectTreePopup extends Pane {
    static xtype = "bi.select_level_tree";

    static EVENT_CHANGE = "EVENT_CHANGE";

    _defaultConfig() {
        return extend(super._defaultConfig(...arguments), {
            baseCls: "bi-select-level-tree",
            tipText: i18nText("BI-No_Selected_Item"),
            items: [],
            value: "",
        });
    }

    _formatItems(nodes, layer, pNode) {
        const self = this;
        each(nodes, (i, node) => {
            const extend = {
                layer,
                isFirstNode: i === 0,
                isLastNode: i === nodes.length - 1,
                height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT,
                pNode,
            };
            node.id = node.id || UUID();

            if (
                node.isParent === true ||
                node.parent === true ||
                isNotEmptyArray(node.children)
            ) {
                extend.type = BasicTreeNode.xtype;
                extend.selectable = true;
                defaults(node, extend);
                self._formatItems(node.children, layer + 1, node);
            } else {
                extend.type = BasicTreeItem.xtype;
                defaults(node, extend);
            }
        });

        return nodes;
    }

    _init() {
        super._init(...arguments);

        const self = this,
            o = this.options;

        this.tree = createWidget({
            type: LevelTree.xtype,
            expander: {
                type: TreeExpander.xtype,
                // isDefaultInit: true,
                selectable: true,
            },
            items: this._formatItems(Tree.transformToTreeFormat(o.items), 0),
            value: o.value,
            chooseType: Selection.Single,
        });

        createWidget({
            type: VerticalLayout.xtype,
            element: this,
            vgap: 5,
            items: [this.tree],
        });

        this.tree.on(Controller.EVENT_CHANGE, function () {
            self.fireEvent(Controller.EVENT_CHANGE, arguments);
        });

        this.tree.on(LevelTree.EVENT_CHANGE, () => {
            self.fireEvent(SelectTreePopup.EVENT_CHANGE);
        });

        this.check();
    }

    getValue() {
        return this.tree.getValue();
    }

    setValue(v) {
        v = isArray(v) ? v : [v];
        this.tree.setValue(v);
    }

    populate(items) {
        super.populate(...arguments);
        this.tree.populate(
            this._formatItems(Tree.transformToTreeFormat(items))
        );
    }
}