"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Cascader", {
    enumerable: true,
    get: function() {
        return Cascader;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _async_to_generator = require("@swc/helpers/_/_async_to_generator");
var _define_property = require("@swc/helpers/_/_define_property");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _ts_generator = require("@swc/helpers/_/_ts_generator");
var _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _classnames = /*#__PURE__*/ _interop_require_default._(require("classnames"));
var _iconsreact = require("@nutui/icons-react");
var _index = /*#__PURE__*/ _interop_require_default._(require("../popup/index"));
var _tabs = require("../tabs/tabs");
var _utils = /*#__PURE__*/ _interop_require_wildcard._(require("./utils"));
var _typings = require("../../utils/typings");
var _usepropsvalue = require("../../hooks/use-props-value");
var _configprovider = require("../configprovider");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    activeColor: '',
    activeIcon: 'checklist',
    popup: true,
    options: [],
    optionKey: {
        textKey: 'text',
        valueKey: 'value',
        childrenKey: 'children'
    },
    format: {},
    closeable: false,
    closeIconPosition: 'top-right',
    closeIcon: 'close',
    lazy: false,
    onLoad: function onLoad() {},
    onClose: function onClose() {},
    onChange: function onChange() {},
    onPathChange: function onPathChange() {}
});
var InternalCascader = function InternalCascader(props, ref) {
    var locale = (0, _configprovider.useConfig)().locale;
    var _$_object_spread = (0, _object_spread._)({}, defaultProps, props), className = _$_object_spread.className, style = _$_object_spread.style, activeColor = _$_object_spread.activeColor, activeIcon = _$_object_spread.activeIcon, popup = _$_object_spread.popup, _object_spread_popupProps = _$_object_spread.popupProps, popupProps = _object_spread_popupProps === void 0 ? {} : _object_spread_popupProps, visible = _$_object_spread.visible, options = _$_object_spread.options, value = _$_object_spread.value, defaultValue = _$_object_spread.defaultValue, optionKey = _$_object_spread.optionKey, format = _$_object_spread.format, closeable = _$_object_spread.closeable, closeIconPosition = _$_object_spread.closeIconPosition, closeIcon = _$_object_spread.closeIcon, lazy = _$_object_spread.lazy, title = _$_object_spread.title, left = _$_object_spread.left, onLoad = _$_object_spread.onLoad, onClose = _$_object_spread.onClose, onChange = _$_object_spread.onChange, onPathChange = _$_object_spread.onPathChange;
    var _useState = (0, _sliced_to_array._)((0, _react.useState)('c1'), 2), tabvalue = _useState[0], setTabvalue = _useState[1];
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)([]), 2), optionsData = _useState1[0], setOptionsData = _useState1[1];
    var isLazy = function isLazy() {
        return state.configs.lazy && Boolean(state.configs.onLoad);
    };
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: value,
        defaultValue: defaultValue,
        finalValue: defaultValue
    }), 2), innerValue = _usePropsValue[0], setInnerValue = _usePropsValue[1];
    var _usePropsValue1 = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: visible,
        defaultValue: undefined,
        finalValue: false
    }), 2), innerVisible = _usePropsValue1[0], setInnerVisible = _usePropsValue1[1];
    var actions = {
        open: function open() {
            setInnerVisible(true);
        },
        close: function close() {
            setInnerVisible(false);
        }
    };
    (0, _react.useImperativeHandle)(ref, function() {
        return actions;
    });
    var _useState2 = (0, _sliced_to_array._)((0, _react.useState)({
        optionsData: [],
        panes: [
            {
                nodes: [],
                selectedNode: [],
                paneKey: ''
            }
        ],
        tree: new _utils.default([], {}),
        tabsCursor: 0,
        initLoading: false,
        currentProcessNode: [],
        configs: {
            lazy: lazy,
            onLoad: onLoad,
            optionKey: optionKey,
            format: format
        },
        lazyLoadMap: new Map()
    }), 1), state = _useState2[0];
    var classPrefix = (0, _classnames.default)("nut-cascader");
    var classesPane = (0, _classnames.default)((0, _define_property._)({}, "".concat(classPrefix, "-pane"), true));
    (0, _react.useEffect)(function() {
        initData();
    }, [
        options,
        format
    ]);
    (0, _react.useEffect)(function() {
        syncValue();
    }, [
        value
    ]);
    var initData = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function() {
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        // 初始化开始处理数据
                        state.lazyLoadMap.clear();
                        if (format && Object.keys(format).length > 0) {
                            state.optionsData = (0, _utils.convertListToOptions)(options, format);
                        } else {
                            state.optionsData = options;
                        }
                        state.tree = new _utils.default(state.optionsData, {
                            value: state.configs.optionKey.valueKey,
                            text: state.configs.optionKey.textKey,
                            children: state.configs.optionKey.childrenKey
                        });
                        if (!(isLazy() && !state.tree.nodes.length)) return [
                            3,
                            2
                        ];
                        return [
                            4,
                            invokeLazyLoad({
                                root: true,
                                loading: true,
                                text: '',
                                value: ''
                            })
                        ];
                    case 1:
                        _state.sent();
                        _state.label = 2;
                    case 2:
                        state.panes = [
                            {
                                nodes: state.tree.nodes,
                                selectedNode: null,
                                paneKey: 'c1'
                            }
                        ];
                        syncValue();
                        setOptionsData(state.panes);
                        return [
                            2
                        ];
                }
            });
        });
        return function initData() {
            return _ref.apply(this, arguments);
        };
    }();
    // 处理有默认值时的数据
    var syncValue = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function() {
            var currentValue, needToSync, parent, last, pathNodes;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        currentValue = innerValue;
                        if (currentValue === undefined || ![
                            defaultValue,
                            value
                        ].includes(currentValue) || !state.tree.nodes.length) {
                            return [
                                2
                            ];
                        }
                        if (currentValue.length === 0) {
                            state.tabsCursor = 0;
                            return [
                                2
                            ];
                        }
                        needToSync = currentValue;
                        if (!(isLazy() && Array.isArray(currentValue) && currentValue.length)) return [
                            3,
                            3
                        ];
                        needToSync = [];
                        parent = state.tree.nodes.find(function(node) {
                            return node.value === currentValue[0];
                        });
                        if (!parent) return [
                            3,
                            3
                        ];
                        needToSync = [
                            parent.value
                        ];
                        state.initLoading = true;
                        return [
                            4,
                            currentValue.slice(1).reduce(/*#__PURE__*/ function() {
                                var _ref = (0, _async_to_generator._)(function(p, value) {
                                    var _parent_children, parent, node;
                                    return (0, _ts_generator._)(this, function(_state) {
                                        switch(_state.label){
                                            case 0:
                                                return [
                                                    4,
                                                    p
                                                ];
                                            case 1:
                                                parent = _state.sent();
                                                return [
                                                    4,
                                                    invokeLazyLoad(parent)
                                                ];
                                            case 2:
                                                _state.sent();
                                                node = parent === null || parent === void 0 ? void 0 : (_parent_children = parent.children) === null || _parent_children === void 0 ? void 0 : _parent_children.find(function(item) {
                                                    return item.value === value;
                                                });
                                                if (node) {
                                                    needToSync.push(value);
                                                }
                                                return [
                                                    2,
                                                    Promise.resolve(node)
                                                ];
                                        }
                                    });
                                });
                                return function(p, value) {
                                    return _ref.apply(this, arguments);
                                };
                            }(), Promise.resolve(parent))
                        ];
                    case 1:
                        last = _state.sent();
                        return [
                            4,
                            invokeLazyLoad(last)
                        ];
                    case 2:
                        _state.sent();
                        state.initLoading = false;
                        _state.label = 3;
                    case 3:
                        if (needToSync.length && [
                            defaultValue,
                            value
                        ].includes(currentValue)) {
                            pathNodes = state.tree.getPathNodesByValue(needToSync);
                            pathNodes.forEach(function(node, index) {
                                state.tabsCursor = index;
                                // 当有默认值时，不触发 chooseItem 里的 emit 事件
                                chooseItem(node, true);
                            });
                        }
                        return [
                            2
                        ];
                }
            });
        });
        return function syncValue() {
            return _ref.apply(this, arguments);
        };
    }();
    var invokeLazyLoad = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function(node) {
            var parent, lazyLoadPromise, nodes;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!node) {
                            return [
                                2
                            ];
                        }
                        if (!state.configs.onLoad) {
                            node.leaf = true;
                            return [
                                2
                            ];
                        }
                        if (state.tree.isLeaf(node, isLazy()) || state.tree.hasChildren(node, isLazy())) {
                            return [
                                2
                            ];
                        }
                        node.loading = true;
                        parent = node.root ? null : node;
                        lazyLoadPromise = state.lazyLoadMap.get(node);
                        if (!lazyLoadPromise) {
                            lazyLoadPromise = new Promise(function(resolve) {
                                var _state_configs_onLoad, _state_configs;
                                (_state_configs_onLoad = (_state_configs = state.configs).onLoad) === null || _state_configs_onLoad === void 0 ? void 0 : _state_configs_onLoad.call(_state_configs, node, resolve);
                            });
                            state.lazyLoadMap.set(node, lazyLoadPromise);
                        }
                        return [
                            4,
                            lazyLoadPromise
                        ];
                    case 1:
                        nodes = _state.sent();
                        if (Array.isArray(nodes) && nodes.length > 0) {
                            state.tree.updateChildren(nodes, parent);
                        } else {
                            // 如果加载完成后没有提供子节点，作为叶子节点处理
                            node.leaf = true;
                        }
                        node.loading = false;
                        state.lazyLoadMap.delete(node);
                        return [
                            2
                        ];
                }
            });
        });
        return function invokeLazyLoad(node) {
            return _ref.apply(this, arguments);
        };
    }();
    var close = function close() {
        setInnerVisible(false);
        onClose && onClose();
    };
    var closePopup = function closePopup() {
        close();
    };
    /* type: 是否是静默模式，是的话不触发事件
  tabsCursor: tab的索引 */ var chooseItem = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function(node, type) {
            var pathNodes, optionParams, level, pathNodes1, optionParams1;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (!type && node.disabled || !state.panes[state.tabsCursor]) {
                            return [
                                2
                            ];
                        }
                        // 如果没有子节点
                        if (state.tree.isLeaf(node, isLazy())) {
                            node.leaf = true;
                            state.panes[state.tabsCursor].selectedNode = node;
                            state.panes = state.panes.slice(0, node.level + 1);
                            if (!type) {
                                pathNodes = state.panes.map(function(item) {
                                    return item.selectedNode;
                                });
                                optionParams = pathNodes.map(function(item) {
                                    return item.value;
                                });
                                onChange(optionParams, pathNodes);
                                onPathChange === null || onPathChange === void 0 ? void 0 : onPathChange(optionParams, pathNodes);
                                setInnerValue(optionParams);
                            }
                            setOptionsData(state.panes);
                            close();
                            return [
                                2
                            ];
                        }
                        // 如果有子节点，滑到下一个
                        if (state.tree.hasChildren(node, isLazy())) {
                            level = node.level + 1;
                            state.panes[state.tabsCursor].selectedNode = node;
                            state.panes = state.panes.slice(0, level);
                            state.tabsCursor = level;
                            state.panes.push({
                                nodes: node.children || [],
                                selectedNode: null,
                                paneKey: "c".concat(state.tabsCursor + 1)
                            });
                            setOptionsData(state.panes);
                            setTabvalue("c".concat(state.tabsCursor + 1));
                            if (!type) {
                                pathNodes1 = state.panes.map(function(item) {
                                    return item.selectedNode;
                                });
                                optionParams1 = pathNodes1.map(function(item) {
                                    return item === null || item === void 0 ? void 0 : item.value;
                                });
                                onPathChange === null || onPathChange === void 0 ? void 0 : onPathChange(optionParams1, pathNodes1);
                            }
                            return [
                                2
                            ];
                        }
                        state.currentProcessNode = node;
                        if (node.loading) {
                            return [
                                2
                            ];
                        }
                        return [
                            4,
                            invokeLazyLoad(node)
                        ];
                    case 1:
                        _state.sent();
                        if (state.currentProcessNode === node) {
                            state.panes[state.tabsCursor].selectedNode = node;
                            chooseItem(node, type);
                        }
                        setOptionsData(state.panes);
                        return [
                            2
                        ];
                }
            });
        });
        return function chooseItem(node, type) {
            return _ref.apply(this, arguments);
        };
    }();
    var renderItem = function renderItem(pane, node, index) {
        var _pane_selectedNode;
        var classPrefix2 = 'nut-cascader-item';
        var checked = ((_pane_selectedNode = pane.selectedNode) === null || _pane_selectedNode === void 0 ? void 0 : _pane_selectedNode.value) === node.value;
        var classes = (0, _classnames.default)({
            active: checked,
            disabled: node.disabled
        }, classPrefix2);
        var classesTitle = (0, _classnames.default)((0, _define_property._)({}, "".concat(classPrefix2, "-title"), true));
        var renderIcon = function renderIcon() {
            if (checked) {
                if (/*#__PURE__*/ (0, _react.isValidElement)(activeIcon)) {
                    return activeIcon;
                }
                return /*#__PURE__*/ _react.default.createElement(_iconsreact.Check, {
                    className: "".concat(checked ? "".concat(classPrefix, "-icon-check") : '')
                });
            }
            return null;
        };
        return /*#__PURE__*/ _react.default.createElement("div", {
            style: {
                color: checked ? activeColor : ''
            },
            className: classes,
            key: index,
            onClick: function onClick() {
                chooseItem(node, false);
            }
        }, /*#__PURE__*/ _react.default.createElement("div", {
            className: classesTitle
        }, node.text), node.loading ? /*#__PURE__*/ _react.default.createElement(_iconsreact.Loading, {
            color: "#969799",
            className: "nut-cascader-item-icon-loading"
        }) : renderIcon());
    };
    var renderTabs = function renderTabs() {
        return /*#__PURE__*/ _react.default.createElement("div", {
            className: "".concat(classPrefix, " ").concat(className),
            style: style
        }, /*#__PURE__*/ _react.default.createElement(_tabs.Tabs, {
            value: tabvalue,
            title: function title() {
                return optionsData.map(function(pane, index) {
                    var _pane_selectedNode, _pane_selectedNode1;
                    return /*#__PURE__*/ _react.default.createElement("div", {
                        onClick: function onClick() {
                            setTabvalue(pane.paneKey);
                            state.tabsCursor = index;
                        },
                        className: "nut-tabs-titles-item ".concat(tabvalue === pane.paneKey ? 'nut-tabs-titles-item-active' : ''),
                        key: pane.paneKey
                    }, /*#__PURE__*/ _react.default.createElement("span", {
                        className: "nut-tabs-titles-item-text"
                    }, !state.initLoading && state.panes.length && (pane === null || pane === void 0 ? void 0 : (_pane_selectedNode = pane.selectedNode) === null || _pane_selectedNode === void 0 ? void 0 : _pane_selectedNode.text), !state.initLoading && state.panes.length && !(pane === null || pane === void 0 ? void 0 : (_pane_selectedNode1 = pane.selectedNode) === null || _pane_selectedNode1 === void 0 ? void 0 : _pane_selectedNode1.text) && "".concat(locale.select), !(!state.initLoading && state.panes.length) && 'Loading...'), /*#__PURE__*/ _react.default.createElement("span", {
                        className: "nut-tabs-titles-item-line"
                    }));
                });
            }
        }, !state.initLoading && state.panes.length ? optionsData.map(function(pane) {
            var _pane_nodes;
            return /*#__PURE__*/ _react.default.createElement(_tabs.Tabs.TabPane, {
                key: pane.paneKey,
                value: pane.paneKey
            }, /*#__PURE__*/ _react.default.createElement("div", {
                className: classesPane
            }, (_pane_nodes = pane.nodes) === null || _pane_nodes === void 0 ? void 0 : _pane_nodes.map(function(node, index) {
                return renderItem(pane, node, index);
            })));
        }) : /*#__PURE__*/ _react.default.createElement(_tabs.Tabs.TabPane, null, /*#__PURE__*/ _react.default.createElement("div", {
            className: classesPane
        }))));
    };
    return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, popup ? /*#__PURE__*/ _react.default.createElement(_index.default, (0, _object_spread_props._)((0, _object_spread._)({}, popupProps), {
        visible: innerVisible,
        position: "bottom",
        round: true,
        closeIcon: closeIcon,
        closeable: closeable,
        closeIconPosition: closeIconPosition,
        title: popup && title,
        left: left,
        // todo 只关闭，不处理逻辑。和popup的逻辑不一致。关闭时需要增加是否要处理回调
        onOverlayClick: closePopup,
        onCloseIconClick: closePopup
    }), renderTabs()) : renderTabs());
};
var Cascader = /*#__PURE__*/ _react.default.forwardRef(InternalCascader);
Cascader.displayName = 'NutCascader';
