import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
import { _ as _object_without_properties } from "@swc/helpers/_/_object_without_properties";
import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array";
import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array";
import React, { useState, useEffect, useRef, useImperativeHandle } from "react";
import classNames from "classnames";
import Popup from "../popup/index";
import { SafeArea } from "../safearea/safearea";
import PickerPanel from "./pickerpanel";
import useRefs from "../../hooks/use-refs";
import { useConfig } from "../configprovider";
import { usePropsValue } from "../../hooks/use-props-value";
import { ComponentDefaults } from "../../utils/typings";
var defaultProps = _object_spread_props(_object_spread({}, ComponentDefaults), {
    title: '',
    options: [],
    value: [],
    defaultValue: [],
    threeDimensional: true,
    closeOnOverlayClick: true,
    duration: 1000
});
var InternalPicker = function(props, ref) {
    var locale = useConfig().locale;
    var _ref = _object_spread({}, defaultProps, props), children = _ref.children, visible = _ref.visible, title = _ref.title, _ref_options = _ref.options, options = _ref_options === void 0 ? [] : _ref_options, closeOnOverlayClick = _ref.closeOnOverlayClick, _ref_popupProps = _ref.popupProps, popupProps = _ref_popupProps === void 0 ? {} : _ref_popupProps, _ref_defaultValue = _ref.defaultValue, defaultValue = _ref_defaultValue === void 0 ? [] : _ref_defaultValue, className = _ref.className, style = _ref.style, threeDimensional = _ref.threeDimensional, duration = _ref.duration, onConfirm = _ref.onConfirm, onCancel = _ref.onCancel, onClose = _ref.onClose, afterClose = _ref.afterClose, onChange = _ref.onChange, rest = _object_without_properties(_ref, [
        "children",
        "visible",
        "title",
        "options",
        "closeOnOverlayClick",
        "popupProps",
        "defaultValue",
        "className",
        "style",
        "threeDimensional",
        "duration",
        "onConfirm",
        "onCancel",
        "onClose",
        "afterClose",
        "onChange"
    ]);
    var classPrefix = 'nut-picker';
    var classes = classNames(classPrefix, className);
    var _usePropsValue = _sliced_to_array(usePropsValue({
        value: props.value,
        defaultValue: _to_consumable_array(defaultValue),
        finalValue: _to_consumable_array(defaultValue),
        onChange: function(val) {
            var _props_onConfirm;
            (_props_onConfirm = props.onConfirm) === null || _props_onConfirm === void 0 ? void 0 : _props_onConfirm.call(props, setSelectedOptions(), val);
        }
    }), 2), selectedValue = _usePropsValue[0], setSelectedValue = _usePropsValue[1];
    var _usePropsValue1 = _sliced_to_array(usePropsValue({
        value: props.visible,
        defaultValue: false,
        finalValue: false,
        onChange: function(val) {
            var _props_onClose;
            (_props_onClose = props.onClose) === null || _props_onClose === void 0 ? void 0 : _props_onClose.call(props, setSelectedOptions(), innerValue);
        }
    }), 2), innerVisible = _usePropsValue1[0], setInnerVisible = _usePropsValue1[1];
    var _useState = _sliced_to_array(useState(selectedValue), 2), innerValue = _useState[0], setInnerValue = _useState[1];
    var _useState1 // 选中列
     = _sliced_to_array(useState(0), 2), columnIndex = _useState1[0], setColumnIndex = _useState1[1];
    var pickerRef = useRef(null);
    var _useRefs = _sliced_to_array(useRefs(), 2), refs = _useRefs[0], setRefs = _useRefs[1];
    var _useState2 // 格式化后每一列的数据
     = _sliced_to_array(useState([]), 2), columnsList = _useState2[0], setColumnsList = _useState2[1];
    var isConfirmEvent = useRef(false);
    var actions = {
        open: function() {
            setInnerVisible(true);
        },
        close: function() {
            setInnerVisible(false);
        }
    };
    useImperativeHandle(ref, function() {
        return actions;
    });
    // 级联数据格式化
    var formatCascade = function(columns, values) {
        var _loop = function() {
            var options = columnOptions.children;
            var value = values[columnIndex];
            var index = options.findIndex(function(columnItem) {
                return columnItem.value === value;
            });
            if (index === -1) index = 0;
            columnOptions = columnOptions.children[index];
            columnIndex++;
            formatted.push(options);
        };
        var formatted = [];
        var columnOptions = {
            text: '',
            value: '',
            children: columns
        };
        var columnIndex = 0;
        while(columnOptions && columnOptions.children)_loop();
        return formatted;
    };
    // 数据类型：多列、嵌套、单列
    var columnsType = function() {
        var firstColumn = options[0];
        if (firstColumn) {
            if (Array.isArray(firstColumn)) {
                return 'multiple';
            }
            if ('children' in firstColumn) {
                return 'cascade';
            }
        }
        return 'single';
    };
    // 传入的数据格式化
    var normalListData = function(innerValue) {
        var type = columnsType();
        switch(type){
            case 'multiple':
                return options;
            case 'cascade':
                // 级联数据处理
                return formatCascade(options, innerValue);
            default:
                return [
                    options
                ];
        }
    };
    var init = function() {
        var normalData = normalListData(innerValue);
        setColumnsList(normalData);
        // 初始化默认选中数据
        var data = [];
        normalData.length > 0 && normalData.map(function(item) {
            item[0] && data.push(item[0].value);
            return item;
        });
        if (!innerValue.length && innerValue.length === 0) {
            setInnerValue(_to_consumable_array(data));
        }
    };
    useEffect(function() {
        setInnerValue(innerValue !== selectedValue ? selectedValue : innerValue);
    }, [
        innerVisible,
        selectedValue
    ]);
    useEffect(function() {
        if (innerVisible) {
            init();
        }
    }, [
        options,
        innerVisible
    ]);
    // 选中值进行修改
    useEffect(function() {
        onChange && onChange(setSelectedOptions(), innerValue, columnIndex);
    }, [
        innerValue,
        columnsList
    ]);
    var setSelectedOptions = function() {
        var options = [];
        var currOptions = [];
        columnsList.forEach(function(columnOptions, index) {
            currOptions = columnOptions.filter(function(item) {
                return item.value === innerValue[index];
            });
            if (currOptions[0]) {
                options.push(currOptions[0]);
            } else {
                columnOptions[0] && options.push(columnOptions[0]);
            }
        });
        return options;
    };
    // 更新已选择数据
    var chooseItem = function(columnOptions, columnIndex) {
        var values = [];
        var start = columnIndex;
        if (columnOptions && Object.keys(columnOptions).length) {
            // 切换数据后，数据有变动才触发。
            if (values[columnIndex] !== columnOptions.value) {
                if (columnsType() === 'cascade') {
                    var _columnOptions_children, _columnOptions_children1;
                    values[columnIndex] = columnOptions.value || '';
                    while(columnOptions === null || columnOptions === void 0 ? void 0 : (_columnOptions_children = columnOptions.children) === null || _columnOptions_children === void 0 ? void 0 : _columnOptions_children[0]){
                        values[columnIndex + 1] = columnOptions.children[0].value;
                        columnIndex++;
                        columnOptions = columnOptions.children[0];
                    }
                    // 当前改变列的下一列 children 值为空
                    if (columnOptions === null || columnOptions === void 0 ? void 0 : (_columnOptions_children1 = columnOptions.children) === null || _columnOptions_children1 === void 0 ? void 0 : _columnOptions_children1.length) {
                        values[columnIndex + 1] = '';
                    }
                    var combineResult = _to_consumable_array(innerValue.slice(0, start)).concat(_to_consumable_array(values.splice(start)));
                    setInnerValue(combineResult);
                    setColumnsList(normalListData(combineResult));
                } else {
                    setInnerValue(function(data) {
                        var cdata = _to_consumable_array(data);
                        cdata[columnIndex] = Object.prototype.hasOwnProperty.call(columnOptions, 'value') ? columnOptions.value : '';
                        return cdata;
                    });
                }
                setColumnIndex(columnIndex);
            }
        }
    };
    var confirm = function() {
        var moving = false;
        refs.forEach(function(ref) {
            if (ref.moving) moving = true;
            ref.stopMomentum();
        });
        if (moving) {
            isConfirmEvent.current = true;
        } else {
            setSelectedValue(innerValue, true);
            setInnerVisible(false);
        }
        setTimeout(function() {
            isConfirmEvent.current = false;
        }, 0);
    };
    var renderTitleBar = function() {
        return /*#__PURE__*/ React.createElement("div", {
            className: "".concat(classPrefix, "-control")
        }, /*#__PURE__*/ React.createElement("span", {
            className: "".concat(classPrefix, "-cancel-btn"),
            onClick: function(e) {
                e.stopPropagation();
                onCancel === null || onCancel === void 0 ? void 0 : onCancel();
                setInnerVisible(false);
            }
        }, locale === null || locale === void 0 ? void 0 : locale.cancel), /*#__PURE__*/ React.createElement("div", {
            className: "".concat(classPrefix, "-title")
        }, title || ''), /*#__PURE__*/ React.createElement("span", {
            className: "".concat(classPrefix, "-confirm-btn"),
            onClick: function(e) {
                e.stopPropagation();
                confirm();
            }
        }, locale.confirm));
    };
    return /*#__PURE__*/ React.createElement(React.Fragment, null, typeof children === 'function' && children(selectedValue), /*#__PURE__*/ React.createElement(Popup, _object_spread_props(_object_spread({}, popupProps), {
        visible: innerVisible,
        position: "bottom",
        onOverlayClick: function() {
            if (closeOnOverlayClick) {
                var _props_onCancel;
                (_props_onCancel = props.onCancel) === null || _props_onCancel === void 0 ? void 0 : _props_onCancel.call(props);
                setInnerVisible(false);
            }
        },
        afterClose: function() {
            afterClose === null || afterClose === void 0 ? void 0 : afterClose(setSelectedOptions(), innerValue, pickerRef);
        }
    }), /*#__PURE__*/ React.createElement("div", _object_spread({
        className: classes,
        style: style
    }, rest), renderTitleBar(), typeof children !== 'function' && children, /*#__PURE__*/ React.createElement("div", {
        className: "".concat(classPrefix, "-panel"),
        ref: pickerRef
    }, columnsList === null || columnsList === void 0 ? void 0 : columnsList.map(function(item, index) {
        return /*#__PURE__*/ React.createElement(PickerPanel, {
            ref: setRefs(index),
            defaultValue: innerValue === null || innerValue === void 0 ? void 0 : innerValue[index],
            options: item,
            threeDimensional: threeDimensional,
            chooseItem: function(value, index) {
                return chooseItem(value, index);
            },
            duration: duration,
            key: index,
            keyIndex: index
        });
    }))), /*#__PURE__*/ React.createElement(SafeArea, {
        position: "bottom"
    })));
};
var Picker = /*#__PURE__*/ React.forwardRef(InternalPicker);
export default Picker;
