/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

import { __extends, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import omit from 'lodash/omit';
import { noop, autobind, themeable, localeable } from 'amis-core';
import Tree from './Tree.js';
import TransferSearch from './TransferSearch.js';

// 递归找到对应选中节点(dfs)
function getDeep(node, cb, pathNodes, valueField) {
    if (node[valueField] && cb(node)) {
        node.isChecked = true;
        for (var i = pathNodes.length - 2; i >= 0; i--) {
            if (!pathNodes[i].isChecked) {
                pathNodes[i].isChecked = true;
                continue;
            }
            break;
        }
    }
    else if (node.children && Array.isArray(node.children)) {
        node.children.forEach(function (n) {
            pathNodes.push(n);
            getDeep(n, cb, pathNodes, valueField);
            pathNodes.pop();
        });
    }
}
// 递归删除树多余的节点
function deepCheckedTreeNode(nodes) {
    var arr = [];
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (node.isChecked) {
            if (node.children && Array.isArray(node.children)) {
                node.children = deepCheckedTreeNode(node.children);
            }
            arr.push(node);
        }
    }
    return arr;
}
// 根据选项获取到结果
function getResultOptions(value, options, valueField) {
    if (value === void 0) { value = []; }
    var newOptions = cloneDeep(options);
    var callBack = function (node) {
        return !!(value || []).find(function (target) { return target[valueField] === node[valueField]; });
    };
    newOptions &&
        newOptions.forEach(function (op) {
            getDeep(op, callBack, [op], valueField);
        });
    return deepCheckedTreeNode(newOptions);
}
// 在包含回调函数情况下，遍历树
function deepTree(nodes, cb) {
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        cb(node);
        if (node.children && Array.isArray(node.children)) {
            deepTree(node.children, cb);
        }
    }
}
// 树的节点删除
function deepDeleteTree(nodes, option, valueField) {
    var arr = [];
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (isEqual(node, option)) {
            continue;
        }
        if (node.children && Array.isArray(node.children)) {
            node.children = deepDeleteTree(node.children, option, valueField);
        }
        if ((node.children && node.children.length > 0) ||
            node[valueField] !== undefined) {
            arr.push(node);
        }
    }
    return arr;
}
var BaseResultTreeList = /** @class */ (function (_super) {
    __extends(BaseResultTreeList, _super);
    function BaseResultTreeList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            searching: false,
            treeOptions: [],
            searchTreeOptions: []
        };
        return _this;
    }
    BaseResultTreeList.itemRender = function (option) {
        return React__default.createElement("span", null, "".concat(option.scopeLabel || '').concat(option.label));
    };
    BaseResultTreeList.getDerivedStateFromProps = function (props) {
        var newOptions = getResultOptions(props.value, props.options, props.valueField);
        return {
            treeOptions: cloneDeep(newOptions)
        };
    };
    BaseResultTreeList.prototype.domSearchRef = function (ref) {
        while (ref && ref.getWrappedInstance) {
            ref = ref.getWrappedInstance();
        }
        this.searchRef = ref;
    };
    // 删除非选中节点
    BaseResultTreeList.prototype.deleteTreeChecked = function (option) {
        var _b = this.props, _c = _b.value, value = _c === void 0 ? [] : _c, onChange = _b.onChange, valueField = _b.valueField;
        var _d = this.state, searching = _d.searching, treeOptions = _d.treeOptions;
        var temNode = [];
        var cb = function (node) {
            // 对比时去掉 parent，因为其无限嵌套
            if (isEqual(omit(node, 'parent'), omit(option, 'parent'))) {
                temNode = [node];
            }
        };
        deepTree(treeOptions || [], cb);
        var arr = [];
        var cb2 = function (node) {
            if (node.isChecked && node[valueField]) {
                arr.push(node);
            }
        };
        deepTree(temNode, cb2);
        onChange &&
            onChange(value.filter(function (item) {
                return !arr.find(function (arrItem) {
                    // 对比时去掉 parent，因为其无限嵌套，且不相等
                    return isEqual(omit(arrItem, ['isChecked', 'childrens', 'parent']), omit(item, 'parent'));
                });
            }));
        // 搜索时，重新生成树
        searching && this.deleteResultTreeNode(option);
    };
    // 搜索树点击删除时，删除对应节点
    BaseResultTreeList.prototype.deleteResultTreeNode = function (option) {
        var arr = deepDeleteTree(cloneDeep(this.state.searchTreeOptions) || [], option, this.props.valueField);
        this.setState({ searchTreeOptions: arr });
    };
    BaseResultTreeList.prototype.search = function (inputValue) {
        // 结果为空，直接清空
        if (!inputValue) {
            this.clearSearch();
            return;
        }
        var _b = this.props, valueField = _b.valueField, onSearch = _b.onSearch;
        var temOptions = this.state.treeOptions || [];
        var cb = function (node) {
            node.isChecked = false;
            return true;
        };
        deepTree(temOptions, cb);
        var callBack = function (node) { return onSearch === null || onSearch === void 0 ? void 0 : onSearch(inputValue, node); };
        temOptions &&
            temOptions.forEach(function (op) {
                getDeep(op, callBack, [op], valueField);
            });
        this.setState({
            searching: true,
            searchTreeOptions: deepCheckedTreeNode(temOptions)
        });
    };
    BaseResultTreeList.prototype.clearSearch = function () {
        this.setState({
            searching: false,
            searchTreeOptions: []
        });
    };
    BaseResultTreeList.prototype.clearInput = function () {
        var _b, _c;
        if (this.props.searchable) {
            (_c = (_b = this.searchRef) === null || _b === void 0 ? void 0 : _b.clearInput) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
        this.clearSearch();
    };
    BaseResultTreeList.prototype.renderTree = function () {
        var _this = this;
        var _b = this.props, className = _b.className, cx = _b.classnames, value = _b.value, valueField = _b.valueField, itemRender = _b.itemRender, __ = _b.translate, placeholder = _b.placeholder, virtualThreshold = _b.virtualThreshold; _b.itemHeight; var loadingConfig = _b.loadingConfig, testIdBuilder = _b.testIdBuilder;
        var _c = this.state, treeOptions = _c.treeOptions, searching = _c.searching, searchTreeOptions = _c.searchTreeOptions;
        return (React__default.createElement("div", { className: cx('ResultTreeList', className) }, Array.isArray(value) && value.length ? (React__default.createElement(Tree, { className: cx('Transfer-tree'), options: !searching ? treeOptions : searchTreeOptions, valueField: valueField, value: [], onChange: noop, showIcon: false, itemRender: itemRender, removable: true, loadingConfig: loadingConfig, onDelete: function (option) { return _this.deleteTreeChecked(option); }, virtualThreshold: virtualThreshold, 
            // itemHeight={itemHeight}
            testIdBuilder: testIdBuilder })) : (React__default.createElement("div", { className: cx('Selections-placeholder') }, __(placeholder)))));
    };
    BaseResultTreeList.prototype.render = function () {
        var _b = this.props, cx = _b.classnames, className = _b.className, title = _b.title, searchable = _b.searchable, __ = _b.translate, _c = _b.searchPlaceholder, searchPlaceholder = _c === void 0 ? __('Transfer.searchKeyword') : _c;
        return (React__default.createElement("div", { className: cx('Selections', className) },
            title ? React__default.createElement("div", { className: cx('Selections-title') }, title) : null,
            searchable ? (React__default.createElement(TransferSearch, { ref: this.domSearchRef, placeholder: searchPlaceholder, onSearch: this.search, onCancelSearch: this.clearSearch })) : null,
            this.renderTree()));
    };
    var _a;
    _a = BaseResultTreeList;
    BaseResultTreeList.defaultProps = {
        placeholder: 'placeholder.selectData',
        itemRender: _a.itemRender
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], BaseResultTreeList.prototype, "domSearchRef", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], BaseResultTreeList.prototype, "deleteTreeChecked", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [String]),
        __metadata("design:returntype", void 0)
    ], BaseResultTreeList.prototype, "search", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], BaseResultTreeList.prototype, "clearSearch", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], BaseResultTreeList.prototype, "clearInput", null);
    return BaseResultTreeList;
}(React__default.Component));
var ResultTreeList = themeable(localeable(BaseResultTreeList));

export { BaseResultTreeList, ResultTreeList as default };
