import { h } from "@stencil/core";
import { createClickOutsideHandler } from "../../utils/click-outside";
/**
 * TreeSelect 树形选择器
 * 类似 Select，但下拉选项以树形结构展示，支持单选与多选
 */
export class TreeSelect {
    el;
    /**
     * 可选项数据源（与 Tree 相同的递归树结构）
     */
    data = [];
    /**
     * （受控）绑定值，单选为 string，多选为 string[]
     */
    modelValue = '';
    /**
     * 是否多选
     * @default false
     */
    multiple = false;
    /**
     * 占位文本
     * @default '请选择'
     */
    placeholder = '请选择';
    /**
     * 是否禁用
     * @default false
     */
    disabled = false;
    /**
     * 是否显示 checkbox（多选模式下推荐开启）
     * @default false
     */
    checkable = false;
    /**
     * 是否默认展开全部节点
     * @default false
     */
    defaultExpandAll = false;
    isOpen = false;
    internalExpanded = [];
    internalSelected = [];
    internalChecked = [];
    /**
     * 值变化事件（单选为 string，多选为 string[]）
     */
    hbChange;
    /**
     * 下拉浮层显隐变化事件
     */
    hbVisibleChange;
    clickOutside = createClickOutsideHandler({
        host: null,
        isOpen: () => this.isOpen,
        onClose: () => this.closeDropdown(),
    });
    componentWillLoad() {
        this.syncFromModelValue();
        if (this.defaultExpandAll) {
            const all = [];
            this.collectExpandableKeys(this.data, all);
            this.internalExpanded = all;
        }
    }
    componentDidLoad() {
        this.clickOutside = createClickOutsideHandler({
            host: this.el,
            isOpen: () => this.isOpen,
            onClose: () => this.closeDropdown(),
        });
        this.clickOutside.connect();
    }
    disconnectedCallback() {
        this.clickOutside.disconnect();
    }
    syncFromModelValue() {
        if (this.multiple) {
            const arr = Array.isArray(this.modelValue) ? this.modelValue : [];
            this.internalSelected = [...arr];
            this.internalChecked = [...arr];
        }
        else {
            const single = typeof this.modelValue === 'string' ? this.modelValue : '';
            this.internalSelected = single ? [single] : [];
            this.internalChecked = single ? [single] : [];
        }
    }
    collectExpandableKeys(nodes, out) {
        for (const node of nodes) {
            if (node.children && node.children.length > 0) {
                out.push(node.key);
                this.collectExpandableKeys(node.children, out);
            }
        }
    }
    findTitle(nodes, key) {
        for (const node of nodes) {
            if (node.key === key)
                return node.title;
            if (node.children) {
                const found = this.findTitle(node.children, key);
                if (found)
                    return found;
            }
        }
        return null;
    }
    getDisplayText() {
        if (this.multiple) {
            const arr = Array.isArray(this.modelValue) ? this.modelValue : [];
            if (arr.length === 0)
                return '';
            const titles = arr.map((k) => this.findTitle(this.data, k) || k);
            return titles.join(' / ');
        }
        const single = typeof this.modelValue === 'string' ? this.modelValue : '';
        return single ? this.findTitle(this.data, single) || single : '';
    }
    openDropdown = () => {
        if (this.disabled || this.isOpen)
            return;
        this.isOpen = true;
        this.hbVisibleChange.emit(true);
    };
    closeDropdown = () => {
        if (!this.isOpen)
            return;
        this.isOpen = false;
        this.hbVisibleChange.emit(false);
    };
    toggleDropdown = () => {
        if (this.disabled)
            return;
        if (this.isOpen)
            this.closeDropdown();
        else
            this.openDropdown();
    };
    handleNodeSelect = (key) => {
        if (this.multiple) {
            const current = [...this.internalSelected];
            const idx = current.indexOf(key);
            if (idx >= 0)
                current.splice(idx, 1);
            else
                current.push(key);
            this.internalSelected = current;
            this.modelValue = current;
            this.hbChange.emit(current);
        }
        else {
            this.internalSelected = [key];
            this.modelValue = key;
            this.hbChange.emit(key);
            this.closeDropdown();
        }
    };
    handleNodeCheck = (key) => {
        // TODO: 父子联动 —— 当前仅管理单个节点勾选状态。
        const current = [...this.internalChecked];
        const idx = current.indexOf(key);
        if (idx >= 0)
            current.splice(idx, 1);
        else
            current.push(key);
        this.internalChecked = current;
        this.modelValue = current;
        this.hbChange.emit(current);
    };
    handleToggleExpand = (node, e) => {
        e.stopPropagation();
        const current = [...this.internalExpanded];
        const idx = current.indexOf(node.key);
        if (idx >= 0)
            current.splice(idx, 1);
        else
            current.push(node.key);
        this.internalExpanded = current;
    };
    handleClear = (e) => {
        e.stopPropagation();
        if (this.disabled)
            return;
        this.internalSelected = [];
        this.internalChecked = [];
        this.modelValue = this.multiple ? [] : '';
        this.hbChange.emit(this.modelValue);
    };
    renderNode = (node, level) => {
        const hasChildren = !!(node.children && node.children.length > 0);
        const expanded = this.internalExpanded.includes(node.key);
        const selected = this.internalSelected.includes(node.key);
        const checked = this.internalChecked.includes(node.key);
        const disabled = !!node.disabled;
        return (h("li", { class: { 'hb-tree-select__node': true, 'hb-tree-select__node--disabled': disabled }, role: "treeitem" }, h("div", { class: {
                'hb-tree-select__node-content': true,
                'hb-tree-select__node-content--selected': selected,
                'hb-tree-select__node-content--checked': checked,
            }, style: { paddingLeft: `${level * 18 + 8}px` } }, h("span", { class: "hb-tree-select__switcher", onClick: (e) => hasChildren && this.handleToggleExpand(node, e) }, hasChildren ? (h("span", { class: { 'hb-tree-select__arrow': true, 'hb-tree-select__arrow--expanded': expanded } }, "\u25B6")) : null), this.checkable && (h("span", { class: {
                'hb-tree-select__checkbox': true,
                'hb-tree-select__checkbox--checked': checked,
                'hb-tree-select__checkbox--disabled': disabled,
            }, onClick: () => !disabled && this.handleNodeCheck(node.key) }, checked ? '✓' : '')), h("span", { class: "hb-tree-select__title", onClick: () => !disabled && this.handleNodeSelect(node.key) }, node.title)), hasChildren && expanded && (h("ul", { class: "hb-tree-select__children", role: "group" }, node.children.map((child) => this.renderNode(child, level + 1))))));
    };
    render() {
        const displayText = this.getDisplayText();
        const hasValue = this.multiple
            ? Array.isArray(this.modelValue) && this.modelValue.length > 0
            : typeof this.modelValue === 'string' && this.modelValue !== '';
        return (h("div", { key: '38d8a150ce1436bbea77250dd0bb3a44b9722cbc', class: {
                'hb-tree-select': true,
                'hb-tree-select--open': this.isOpen,
                'hb-tree-select--disabled': this.disabled,
                'hb-tree-select--multiple': this.multiple,
            } }, h("div", { key: '5928b61ce45dabece866b8de93a4353804ed05e4', class: "hb-tree-select__input-wrapper", onClick: this.toggleDropdown }, h("span", { key: 'af7b313ec51033487044aa3b9ef1620fbe292490', class: {
                'hb-tree-select__display': true,
                'hb-tree-select__display--placeholder': !hasValue,
            } }, hasValue ? displayText : this.placeholder), h("span", { key: 'ab26baf601b42f2e5d28768d70927a38afbf612f', class: "hb-tree-select__suffix" }, hasValue && (h("span", { key: '0095371d8cdb31f569e53117a36d93de1f09b304', class: "hb-tree-select__clear", onClick: this.handleClear }, "\u00D7")), h("span", { key: 'b824565183607eb6341223fcfc0110b224d9d156', class: { 'hb-tree-select__arrow-icon': true, 'hb-tree-select__arrow-icon--open': this.isOpen } }, "\u25BC"))), this.isOpen && (h("div", { key: 'e03726804631a7e69c86319f9f5ec81fecb60bf0', class: "hb-tree-select__dropdown" }, this.data.length === 0 ? (h("div", { class: "hb-tree-select__empty" }, "\u6682\u65E0\u6570\u636E")) : (h("ul", { class: "hb-tree-select__tree", role: "tree" }, this.data.map((node) => this.renderNode(node, 0))))))));
    }
    static get is() { return "hb-tree-select"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["tree-select.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["tree-select.css"]
        };
    }
    static get properties() {
        return {
            "data": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "TreeNode[]",
                    "resolved": "TreeNode[]",
                    "references": {
                        "TreeNode": {
                            "location": "import",
                            "path": "../Tree/Tree",
                            "id": "src/components/Tree/Tree.tsx::TreeNode"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u53EF\u9009\u9879\u6570\u636E\u6E90\uFF08\u4E0E Tree \u76F8\u540C\u7684\u9012\u5F52\u6811\u7ED3\u6784\uFF09"
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "modelValue": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string | string[]",
                    "resolved": "string | string[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\uFF08\u53D7\u63A7\uFF09\u7ED1\u5B9A\u503C\uFF0C\u5355\u9009\u4E3A string\uFF0C\u591A\u9009\u4E3A string[]"
                },
                "getter": false,
                "setter": false,
                "attribute": "model-value",
                "reflect": false,
                "defaultValue": "''"
            },
            "multiple": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u591A\u9009"
                },
                "getter": false,
                "setter": false,
                "attribute": "multiple",
                "reflect": false,
                "defaultValue": "false"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "'\u8BF7\u9009\u62E9'"
                        }],
                    "text": "\u5360\u4F4D\u6587\u672C"
                },
                "getter": false,
                "setter": false,
                "attribute": "placeholder",
                "reflect": false,
                "defaultValue": "'\u8BF7\u9009\u62E9'"
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u7981\u7528"
                },
                "getter": false,
                "setter": false,
                "attribute": "disabled",
                "reflect": false,
                "defaultValue": "false"
            },
            "checkable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u663E\u793A checkbox\uFF08\u591A\u9009\u6A21\u5F0F\u4E0B\u63A8\u8350\u5F00\u542F\uFF09"
                },
                "getter": false,
                "setter": false,
                "attribute": "checkable",
                "reflect": false,
                "defaultValue": "false"
            },
            "defaultExpandAll": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "default",
                            "text": "false"
                        }],
                    "text": "\u662F\u5426\u9ED8\u8BA4\u5C55\u5F00\u5168\u90E8\u8282\u70B9"
                },
                "getter": false,
                "setter": false,
                "attribute": "default-expand-all",
                "reflect": false,
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "isOpen": {},
            "internalExpanded": {},
            "internalSelected": {},
            "internalChecked": {}
        };
    }
    static get events() {
        return [{
                "method": "hbChange",
                "name": "hbChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u503C\u53D8\u5316\u4E8B\u4EF6\uFF08\u5355\u9009\u4E3A string\uFF0C\u591A\u9009\u4E3A string[]\uFF09"
                },
                "complexType": {
                    "original": "string | string[]",
                    "resolved": "string | string[]",
                    "references": {}
                }
            }, {
                "method": "hbVisibleChange",
                "name": "hbVisibleChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u4E0B\u62C9\u6D6E\u5C42\u663E\u9690\u53D8\u5316\u4E8B\u4EF6"
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
}
//# sourceMappingURL=TreeSelect.js.map
