"use strict";
/**
 * @file Tree
 * @description 树形组件
 * @author fex
 */
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var helper_1 = require("../utils/helper");
var Checkboxes_1 = require("./Checkboxes");
var theme_1 = require("../theme");
var Options_1 = require("../renderers/Form/Options");
var TreeSelector = /** @class */ (function (_super) {
    tslib_1.__extends(TreeSelector, _super);
    function TreeSelector() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TreeSelector.prototype.componentWillMount = function () {
        this.renderList = this.renderList.bind(this);
        this.handleSelect = this.handleSelect.bind(this);
        this.clearSelect = this.clearSelect.bind(this);
        this.handleCheck = this.handleCheck.bind(this);
        this.toggleUnfolded = this.toggleUnfolded.bind(this);
        var props = this.props;
        this.setState({
            value: Checkboxes_1.value2array(props.value, {
                joinValues: props.joinValues,
                extractValue: props.extractValue,
                multiple: props.multiple,
                delimiter: props.delimiter,
                valueField: props.valueField,
                options: props.data,
            }),
            unfolded: this.syncUnFolded(props),
        });
    };
    TreeSelector.prototype.componentWillReceiveProps = function (nextProps) {
        var toUpdate = {};
        if (this.props.value !== nextProps.value || this.props.data !== nextProps.data) {
            toUpdate.value = Checkboxes_1.value2array(nextProps.value, {
                joinValues: nextProps.joinValues,
                extractValue: nextProps.extractValue,
                multiple: nextProps.multiple,
                delimiter: nextProps.delimiter,
                valueField: nextProps.valueField,
                options: nextProps.data,
            });
        }
        if (this.props.data !== nextProps.data) {
            toUpdate.unfolded = this.syncUnFolded(nextProps);
        }
        this.setState(toUpdate);
    };
    TreeSelector.prototype.syncUnFolded = function (props) {
        // 初始化树节点的展开状态
        var unfolded = {};
        var _a = this.props, foldedField = _a.foldedField, unfoldedField = _a.unfoldedField;
        helper_1.eachTree(props.data, function (node, index, level) {
            if (node.children && node.children.length) {
                var ret = true;
                if (unfoldedField && typeof node[unfoldedField] !== 'undefined') {
                    ret = !!node[unfoldedField];
                }
                else if (foldedField && typeof node[foldedField] !== 'undefined') {
                    ret = !node[foldedField];
                }
                else {
                    ret = !!props.initiallyOpen;
                    if (!ret && level <= props.unfoldedLevel) {
                        ret = true;
                    }
                }
                unfolded[node[props.valueField]] = ret;
            }
        });
        return unfolded;
    };
    TreeSelector.prototype.toggleUnfolded = function (node) {
        this.setState({
            unfolded: tslib_1.__assign({}, this.state.unfolded, (_a = {}, _a[node[this.props.valueField]] = !this.state.unfolded[node[this.props.valueField]], _a)),
        });
        var _a;
    };
    TreeSelector.prototype.clearSelect = function () {
        var _this = this;
        this.setState({
            value: [],
        }, function () {
            var _a = _this.props, joinValues = _a.joinValues, rootValue = _a.rootValue, onChange = _a.onChange;
            onChange(joinValues ? rootValue : []);
        });
    };
    TreeSelector.prototype.handleSelect = function (node, value) {
        var _this = this;
        this.setState({
            value: [node],
        }, function () {
            var _a = _this.props, joinValues = _a.joinValues, valueField = _a.valueField, onChange = _a.onChange;
            onChange(joinValues ? node[valueField] : node);
        });
    };
    TreeSelector.prototype.handleCheck = function (item, checked) {
        var _this = this;
        var props = this.props;
        var value = this.state.value.concat();
        var idx = value.indexOf(item);
        var onlyChildren = this.props.onlyChildren;
        if (checked) {
            ~idx || value.push(item);
            if (!props.cascade) {
                var children = item.children ? item.children.concat([]) : [];
                if (onlyChildren) {
                    // 父级选中的时候，子节点也都选中，但是自己不选中
                    !~idx && children.length && value.shift();
                    while (children.length) {
                        var child = children.shift();
                        var index = value.indexOf(child);
                        if (child.children) {
                            children.push.apply(children, child.children);
                        }
                        else {
                            ~index || value.push(child);
                        }
                    }
                }
                else {
                    // 只要父节点选择了,子节点就不需要了,全部去掉勾选.  withChildren时相反
                    while (children.length) {
                        var child = children.shift();
                        var index = value.indexOf(child);
                        if (~index) {
                            value.splice(index, 1);
                        }
                        if (props.withChildren) {
                            value.push(child);
                        }
                        if (child.children && child.children.length) {
                            children.push.apply(children, child.children);
                        }
                    }
                }
            }
        }
        else if (!checked) {
            ~idx && value.splice(idx, 1);
            if (!props.cascade && (props.withChildren || onlyChildren)) {
                var children = item.children ? item.children.concat([]) : [];
                while (children.length) {
                    var child = children.shift();
                    var index = value.indexOf(child);
                    if (~index) {
                        value.splice(index, 1);
                    }
                    if (child.children && child.children.length) {
                        children.push.apply(children, child.children);
                    }
                }
            }
        }
        this.setState({
            value: value,
        }, function () {
            var _a = _this.props, joinValues = _a.joinValues, extractValue = _a.extractValue, valueField = _a.valueField, delimiter = _a.delimiter, onChange = _a.onChange;
            onChange(joinValues
                ? value.map(function (item) { return item[valueField]; }).join(delimiter)
                : extractValue
                    ? value.map(function (item) { return item[valueField]; })
                    : value);
        });
    };
    TreeSelector.prototype.renderList = function (list, value, uncheckable) {
        var _this = this;
        var _a = this.props, itemClassName = _a.itemClassName, showIcon = _a.showIcon, showRadio = _a.showRadio, multiple = _a.multiple, disabled = _a.disabled, _b = _a.nameField, nameField = _b === void 0 ? '' : _b, _c = _a.valueField, valueField = _c === void 0 ? '' : _c, _d = _a.iconField, iconField = _d === void 0 ? '' : _d, _e = _a.disabledField, disabledField = _e === void 0 ? '' : _e, cascade = _a.cascade, selfDisabledAffectChildren = _a.selfDisabledAffectChildren, onlyChildren = _a.onlyChildren, cx = _a.classnames, highlightTxt = _a.highlightTxt, data = _a.data;
        var childrenChecked = 0;
        var ret = list.map(function (item, key) {
            if (!helper_1.isVisible(item, data)) {
                return null;
            }
            var checked = !!~value.indexOf(item);
            var selfDisabled = item[disabledField];
            var selfChecked = !!uncheckable || checked;
            var childrenItems = null;
            var tmpChildrenChecked = false;
            if (item.children && item.children.length) {
                childrenItems = _this.renderList(item.children, value, cascade
                    ? false
                    : uncheckable || (selfDisabledAffectChildren ? selfDisabled : false) || (multiple && checked));
                tmpChildrenChecked = !!childrenItems.childrenChecked;
                if (!selfChecked && onlyChildren && item.children.length === childrenItems.childrenChecked) {
                    selfChecked = true;
                }
                childrenItems = childrenItems.dom;
            }
            if (tmpChildrenChecked || checked) {
                childrenChecked++;
            }
            var nodeDisabled = !!uncheckable || !!disabled || selfDisabled;
            var checkbox = multiple ? (React.createElement("label", { className: cx("Checkbox Checkbox--checkbox Checkbox--sm") },
                React.createElement("input", { type: "checkbox", disabled: nodeDisabled, checked: selfChecked, onChange: function (e) { return _this.handleCheck(item, e.currentTarget.checked); } }),
                React.createElement("i", null))) : showRadio ? (React.createElement("label", { className: cx("Checkbox Checkbox--radio Checkbox--sm") },
                React.createElement("input", { type: "radio", disabled: nodeDisabled, checked: checked, onChange: function () { return _this.handleSelect(item); } }),
                React.createElement("i", null))) : null;
            var isLeaf = !item.children || !item.children.length;
            return (React.createElement("li", { key: key, className: cx("Tree-item " + (itemClassName || ''), {
                    'Tree-item--isLeaf': isLeaf,
                }) },
                React.createElement("a", null,
                    !isLeaf ? (React.createElement("i", { onClick: function () { return _this.toggleUnfolded(item); }, className: cx('Tree-itemArrow', {
                            'is-folded': !_this.state.unfolded[item[valueField]],
                        }) })) : null,
                    showIcon ? (React.createElement("i", { className: cx("Tree-itemIcon " + (item[iconField] ||
                            (childrenItems ? 'Tree-folderIcon' : 'Tree-leafIcon'))) })) : null,
                    checkbox,
                    React.createElement("span", { className: cx('Tree-itemText', {
                            'is-children-checked': multiple && !cascade && tmpChildrenChecked && !nodeDisabled,
                            'is-checked': checked,
                            'is-disabled': nodeDisabled,
                        }), onClick: function () {
                            return !nodeDisabled &&
                                (multiple ? _this.handleCheck(item, !selfChecked) : _this.handleSelect(item));
                        } }, highlightTxt ? Options_1.highlight(item[nameField], highlightTxt) : item[nameField])),
                childrenItems ? (React.createElement("ul", { className: cx('Tree-sublist', {
                        'is-folded': !_this.state.unfolded[item[valueField]],
                    }) }, childrenItems)) : null));
        });
        return {
            dom: ret,
            childrenChecked: childrenChecked,
        };
    };
    TreeSelector.prototype.render = function () {
        var _a = this.props, className = _a.className, placeholder = _a.placeholder, hideRoot = _a.hideRoot, rootLabel = _a.rootLabel, showIcon = _a.showIcon, cx = _a.classnames;
        var data = this.props.data;
        var value = this.state.value;
        return (React.createElement("div", { className: cx("Tree " + (className || '')) }, data && data.length ? (React.createElement("ul", { className: cx('Tree-list') }, hideRoot ? (this.renderList(data, value, false).dom) : (React.createElement("li", { className: cx('Tree-item Tree-rootItem') },
            React.createElement("a", null,
                showIcon ? React.createElement("i", { className: cx('Tree-itemIcon Tree-rootIcon') }) : null,
                React.createElement("label", { className: cx('Tree-itemLabel', {
                        'is-checked': !value || !value.length,
                    }) },
                    React.createElement("span", { className: cx('Tree-itemText'), onClick: this.clearSelect }, rootLabel))),
            React.createElement("ul", { className: cx('Tree-sublist') }, this.renderList(data, value, false).dom))))) : (React.createElement("div", { className: cx('Tree-placeholder') }, placeholder))));
    };
    TreeSelector.defaultProps = {
        showIcon: true,
        initiallyOpen: true,
        unfoldedLevel: 0,
        showRadio: false,
        multiple: false,
        disabled: false,
        withChildren: false,
        onlyChildren: false,
        nameField: 'name',
        valueField: 'value',
        iconField: 'icon',
        unfoldedField: 'unfolded',
        foldedField: 'foled',
        disabledField: 'disabled',
        joinValues: true,
        extractValue: false,
        delimiter: ',',
        hideRoot: true,
        rootLabel: '顶级',
        rootValue: 0,
        cascade: false,
        selfDisabledAffectChildren: true,
    };
    return TreeSelector;
}(React.Component));
exports.TreeSelector = TreeSelector;
exports.default = theme_1.themeable(TreeSelector);
//# sourceMappingURL=./components/Tree.js.map
