"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Range", {
    enumerable: true,
    get: function() {
        return Range;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
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 _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _classnames = /*#__PURE__*/ _interop_require_default._(require("classnames"));
var _usetouch = require("../../hooks/use-touch");
var _useclientrect = require("../../hooks/use-client-rect");
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), {
    range: false,
    min: 0,
    max: 100,
    step: 1,
    vertical: false,
    marks: {}
});
var classPrefix = 'nut-range';
var verticalClassPrefix = "".concat(classPrefix, "-vertical");
var isSameValue = function isSameValue(newValue, oldValue) {
    return JSON.stringify(newValue) === JSON.stringify(oldValue);
};
var handleOverlap = function handleOverlap(value) {
    if (value[0] > value[1]) {
        return value.slice(0).reverse();
    }
    return value;
};
var Range = function Range(props) {
    var rtl = (0, _configprovider.useRtl)();
    var _$_object_spread = (0, _object_spread._)({}, defaultProps, props), className = _$_object_spread.className, style = _$_object_spread.style, range = _$_object_spread.range, disabled = _$_object_spread.disabled, button = _$_object_spread.button, vertical = _$_object_spread.vertical, marks = _$_object_spread.marks, minDescription = _$_object_spread.minDescription, maxDescription = _$_object_spread.maxDescription, currentDescription = _$_object_spread.currentDescription, min = _$_object_spread.min, max = _$_object_spread.max, step = _$_object_spread.step, value = _$_object_spread.value, defaultValue = _$_object_spread.defaultValue, onChange = _$_object_spread.onChange, onStart = _$_object_spread.onStart, onEnd = _$_object_spread.onEnd;
    var rtlClassPrefix = (0, _react.useMemo)(function() {
        return "rtl-".concat(vertical ? verticalClassPrefix : classPrefix);
    }, [
        vertical
    ]);
    var _useState = (0, _sliced_to_array._)((0, _react.useState)(0), 2), buttonIndex = _useState[0], setButtonIndex = _useState[1];
    var _useState1 = (0, _sliced_to_array._)((0, _react.useState)('start'), 2), dragStatus = _useState1[0], setDragStatus = _useState1[1];
    var touch = (0, _usetouch.useTouch)();
    var root = (0, _react.useRef)(null);
    var _useState2 = (0, _sliced_to_array._)((0, _react.useState)([]), 2), marksList = _useState2[0], setMarksList = _useState2[1];
    var _useState3 = (0, _sliced_to_array._)((0, _react.useState)(0), 2), startValue = _useState3[0], setStartValue = _useState3[1];
    var scope = (0, _react.useMemo)(function() {
        if (max < min || max === min) {
            console.log('max 的值需要大于 min的值');
        }
        return max - min;
    }, [
        max,
        min
    ]);
    var handleChange = function handleChange(value) {
        onChange && onChange(value);
    };
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: value,
        defaultValue: defaultValue,
        finalValue: 0,
        onChange: handleChange
    }), 2), current = _usePropsValue[0], setCurrent = _usePropsValue[1];
    var _useState4 = (0, _sliced_to_array._)((0, _react.useState)(function() {
        return value || defaultValue || 0;
    }), 2), exactValue = _useState4[0], setExactValue = _useState4[1];
    var marksRef = (0, _react.useRef)({});
    (0, _react.useEffect)(function() {
        if (marks) {
            if (Array.isArray(marks)) {
                var list = marks.sort(function(a, b) {
                    return a.value - b.value;
                }).filter(function(point) {
                    return point.value >= min && point.value <= max;
                });
                setMarksList(list.map(function(mark) {
                    return mark.value;
                }));
                list.forEach(function(mark) {
                    marksRef.current[mark.value] = mark.label !== undefined ? mark.label : mark.value;
                });
            } else {
                var marksKeys = Object.keys(marks);
                var list1 = marksKeys.map(parseFloat).sort(function(a, b) {
                    return a - b;
                }).filter(function(point) {
                    return point >= min && point <= max;
                });
                setMarksList(list1);
            }
        }
    }, [
        marks,
        max,
        min
    ]);
    var _obj;
    var classes = (0, _classnames.default)(classPrefix, (_obj = {}, (0, _define_property._)(_obj, "".concat(classPrefix, "-disabled"), disabled), (0, _define_property._)(_obj, verticalClassPrefix, vertical), _obj));
    var containerClasses = (0, _classnames.default)("".concat(classPrefix, "-container"), (0, _define_property._)({}, "".concat(verticalClassPrefix, "-container"), vertical), className);
    var markClassName = (0, _react.useCallback)(function(mark) {
        var classPrefix = 'nut-range-mark';
        var verticalClassPrefix = 'nut-range-vertical-mark';
        var lowerBound = min;
        var upperBound = max;
        if (range && Array.isArray(current)) {
            lowerBound = current[0];
            upperBound = current[1];
        } else {
            upperBound = current;
        }
        var isActive = mark <= upperBound && mark >= lowerBound;
        var _$classNames = [
            "".concat(classPrefix, "-text-wrapper"),
            "".concat(isActive ? "".concat(classPrefix, "-text-wrapper-active") : '')
        ];
        if (vertical) {
            _$classNames.push("".concat(verticalClassPrefix, "-text-wrapper"));
            isActive && _$classNames.push("".concat(verticalClassPrefix, "-text-active-wrapper"));
        }
        if (rtl) {
            _$classNames.push("".concat(rtlClassPrefix, "-mark-text-wrapper"));
        }
        return _$classNames.join(' ');
    }, [
        min,
        max,
        range,
        current,
        vertical,
        rtl,
        rtlClassPrefix
    ]);
    var isRange = (0, _react.useCallback)(function(val) {
        return !!range && Array.isArray(val);
    }, [
        range
    ]);
    var calcMainAxis = (0, _react.useCallback)(function() {
        var modelVal = current;
        return isRange(modelVal) ? "".concat((modelVal[1] - modelVal[0]) * 100 / scope, "%") : "".concat((modelVal - min) * 100 / scope, "%");
    }, [
        current,
        isRange,
        min,
        scope
    ]);
    var calcOffset = (0, _react.useCallback)(function() {
        var modelVal = current;
        return isRange(modelVal) ? "".concat((modelVal[0] - min) * 100 / scope, "%") : "0%";
    }, [
        current,
        isRange,
        min,
        scope
    ]);
    var barStyle = (0, _react.useCallback)(function() {
        if (vertical) {
            return {
                height: calcMainAxis(),
                top: calcOffset(),
                transition: dragStatus ? 'none' : undefined
            };
        }
        var dir = rtl ? 'right' : 'left';
        var _obj;
        return _obj = {
            width: calcMainAxis()
        }, (0, _define_property._)(_obj, dir, calcOffset()), (0, _define_property._)(_obj, "transition", dragStatus ? 'none' : undefined), _obj;
    }, [
        calcMainAxis,
        calcOffset,
        dragStatus,
        rtl,
        vertical
    ]);
    var marksStyle = (0, _react.useCallback)(function(mark) {
        var dir = rtl ? 'right' : 'left';
        var style = (0, _define_property._)({}, dir, "".concat((mark - min) / scope * 100, "%"));
        if (vertical) {
            style = {
                top: "".concat((mark - min) / scope * 100, "%")
            };
        }
        return style;
    }, [
        min,
        rtl,
        scope,
        vertical
    ]);
    var tickClass = (0, _react.useCallback)(function(mark) {
        if (range && Array.isArray(current)) {
            return mark <= current[1] && mark >= current[0];
        }
        return mark <= current;
    }, [
        current,
        range
    ]);
    var format = (0, _react.useCallback)(function(value) {
        value = Math.max(+min, Math.min(value, +max));
        return Math.round(value / +step) * +step;
    }, [
        max,
        min,
        step
    ]);
    var updateValue = (0, _react.useCallback)(function(value, end) {
        if (isRange(value)) {
            value = handleOverlap(value).map(format);
        } else {
            value = format(value);
        }
        if (!isSameValue(value, current)) {
            setCurrent(value);
        }
        end && onEnd && onEnd(value);
    }, [
        current,
        format,
        isRange,
        onEnd,
        setCurrent
    ]);
    var click = (0, _react.useCallback)(function(event) {
        if (disabled || !root.current) {
            return;
        }
        setDragStatus('');
        var rect = (0, _useclientrect.getRect)(root.current);
        var delta = event.clientX - rect.left;
        var total = rect.width;
        if (vertical) {
            delta = event.clientY - rect.top;
            total = rect.height;
        }
        var value = min + delta / total * scope;
        setExactValue(current);
        if (isRange(current)) {
            var _current = (0, _sliced_to_array._)(current, 2), left = _current[0], right = _current[1];
            var middle = (left + right) / 2;
            if (value <= middle) {
                updateValue([
                    value,
                    right
                ], true);
            } else {
                updateValue([
                    left,
                    value
                ], true);
            }
        } else {
            updateValue(value, true);
        }
    }, [
        current,
        disabled,
        isRange,
        min,
        scope,
        updateValue,
        vertical
    ]);
    var onTouchStart = (0, _react.useCallback)(function(event) {
        if (disabled) {
            return;
        }
        touch.start(event);
        setExactValue(current);
        if (isRange(current)) {
            setStartValue(current.map(format));
        } else {
            setStartValue(format(current));
        }
        setDragStatus('start');
    }, [
        current,
        disabled,
        format,
        isRange,
        touch
    ]);
    var onTouchMove = (0, _react.useCallback)(function(event) {
        event.stopPropagation();
        if (disabled || !root.current) {
            return;
        }
        if (dragStatus === 'start') {
            onStart && onStart();
        }
        touch.move(event);
        setDragStatus('draging');
        var rect = (0, _useclientrect.getRect)(root.current);
        var delta = touch.deltaX.current;
        var total = rect.width;
        var diff = delta / total * scope;
        diff = rtl ? -diff : diff;
        if (vertical) {
            delta = touch.deltaY.current;
            total = rect.height;
            diff = delta / total * scope;
        }
        var newValue;
        if (isRange(startValue)) {
            newValue = exactValue.slice();
            newValue[buttonIndex] = startValue[buttonIndex] + diff;
        } else {
            newValue = startValue + diff;
        }
        setExactValue(newValue);
        updateValue(newValue);
    }, [
        buttonIndex,
        disabled,
        dragStatus,
        exactValue,
        isRange,
        onStart,
        rtl,
        scope,
        startValue,
        touch,
        updateValue,
        vertical
    ]);
    var onTouchEnd = (0, _react.useCallback)(function() {
        if (disabled) {
            return;
        }
        if (dragStatus === 'draging') {
            updateValue(current, true);
        }
        setDragStatus('');
    }, [
        current,
        disabled,
        dragStatus,
        updateValue
    ]);
    var curValue = (0, _react.useCallback)(function(idx) {
        var modelVal = current;
        var value = typeof idx === 'number' ? modelVal[idx] : modelVal;
        return value;
    }, [
        current
    ]);
    var renderButton = (0, _react.useCallback)(function(index) {
        var buttonNumberTransform = vertical ? 'translate(100%, -50%)' : 'translate(-50%, -100%)';
        var _obj, _obj1;
        return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, button || /*#__PURE__*/ _react.default.createElement("div", {
            className: (0, _classnames.default)("".concat(classPrefix, "-button"), (_obj = {}, (0, _define_property._)(_obj, "".concat(verticalClassPrefix, "-button"), vertical), (0, _define_property._)(_obj, "".concat(rtlClassPrefix, "-button"), rtl), _obj)),
            style: {
                transform: 'translate(-50%, -50%)'
            }
        }, currentDescription !== null && /*#__PURE__*/ _react.default.createElement("div", {
            className: (0, _classnames.default)("".concat(classPrefix, "-button-number"), (_obj1 = {}, (0, _define_property._)(_obj1, "".concat(verticalClassPrefix, "-button-number"), vertical), (0, _define_property._)(_obj1, "".concat(rtlClassPrefix, "-button-number"), rtl), _obj1)),
            style: {
                transform: buttonNumberTransform
            }
        }, currentDescription ? currentDescription(curValue(index)) : curValue(index))));
    }, [
        button,
        curValue,
        currentDescription,
        rtl,
        rtlClassPrefix,
        vertical
    ]);
    var renderMarks = (0, _react.useCallback)(function() {
        if (marksList.length <= 0) return null;
        var _obj;
        var markcls = (0, _classnames.default)("".concat(classPrefix, "-mark"), (_obj = {}, (0, _define_property._)(_obj, "".concat(verticalClassPrefix, "-mark"), vertical), (0, _define_property._)(_obj, "".concat(rtlClassPrefix, "-mark"), rtl), _obj));
        var textcls = (0, _classnames.default)("".concat(classPrefix, "-mark-text"), (0, _define_property._)({}, "".concat(verticalClassPrefix, "-mark-text"), vertical));
        return /*#__PURE__*/ _react.default.createElement("div", {
            className: markcls
        }, marksList.map(function(mark) {
            var _obj;
            return /*#__PURE__*/ _react.default.createElement("span", {
                key: mark,
                className: markClassName(mark),
                style: marksStyle(mark)
            }, /*#__PURE__*/ _react.default.createElement("span", {
                className: textcls
            }, Array.isArray(marks) ? marksRef.current[mark] : marks[mark]), /*#__PURE__*/ _react.default.createElement("span", {
                className: (0, _classnames.default)("".concat(vertical ? verticalClassPrefix : classPrefix, "-tick"), (_obj = {}, (0, _define_property._)(_obj, "".concat(vertical ? verticalClassPrefix : classPrefix, "-tick-active"), tickClass(mark)), (0, _define_property._)(_obj, "".concat(rtlClassPrefix, "-tick"), rtl), _obj))
            }));
        }));
    }, [
        markClassName,
        marks,
        marksList,
        marksStyle,
        rtl,
        rtlClassPrefix,
        tickClass,
        vertical
    ]);
    var getWrapperTransform = (0, _react.useCallback)(function() {
        var wrapperTransform = 'translate(-50%, -50%)';
        return wrapperTransform;
    }, []);
    var renderRangeButton = (0, _react.useCallback)(function() {
        return [
            0,
            1
        ].map(function(item, index) {
            var isLeft = index === 0;
            var suffix = isLeft ? 'left' : 'right';
            var transform = 'translate(-50%, -50%)';
            var _obj;
            var cls = (0, _classnames.default)("".concat(classPrefix, "-button-wrapper-").concat(suffix), (_obj = {}, (0, _define_property._)(_obj, "".concat(verticalClassPrefix, "-button-wrapper-").concat(suffix), vertical), (0, _define_property._)(_obj, "".concat(rtlClassPrefix, "-button-wrapper-").concat(suffix), rtl), _obj));
            return /*#__PURE__*/ _react.default.createElement("div", {
                key: index,
                className: cls,
                style: {
                    transform: transform
                },
                onTouchStart: function onTouchStart1(e) {
                    setButtonIndex(index);
                    onTouchStart(e);
                },
                onTouchMove: onTouchMove,
                onTouchEnd: onTouchEnd,
                onTouchCancel: onTouchEnd,
                onClick: function onClick(e) {
                    return e.stopPropagation();
                }
            }, renderButton(index));
        });
    }, [
        onTouchEnd,
        onTouchMove,
        onTouchStart,
        renderButton,
        vertical,
        rtl,
        rtlClassPrefix
    ]);
    var renderSingleButton = (0, _react.useCallback)(function() {
        return /*#__PURE__*/ _react.default.createElement("div", {
            className: (0, _classnames.default)("".concat(classPrefix, "-button-wrapper"), (0, _define_property._)({}, "".concat(verticalClassPrefix, "-button-wrapper"), vertical)),
            style: {
                // @ts-ignore
                transform: getWrapperTransform()
            },
            onTouchStart: onTouchStart,
            onTouchMove: onTouchMove,
            onTouchEnd: onTouchEnd,
            onTouchCancel: onTouchEnd,
            onClick: function onClick(e) {
                return e.stopPropagation();
            }
        }, renderButton());
    }, [
        getWrapperTransform,
        onTouchEnd,
        onTouchMove,
        onTouchStart,
        renderButton,
        vertical
    ]);
    var renderButtonWrapper = (0, _react.useCallback)(function() {
        if (range) {
            return renderRangeButton();
        }
        return renderSingleButton();
    }, [
        renderRangeButton,
        renderSingleButton,
        range
    ]);
    return /*#__PURE__*/ _react.default.createElement("div", {
        className: containerClasses,
        style: style
    }, minDescription !== null && /*#__PURE__*/ _react.default.createElement("div", {
        className: "".concat(classPrefix, "-min")
    }, minDescription || min), /*#__PURE__*/ _react.default.createElement("div", {
        ref: root,
        className: classes,
        onClick: function onClick(e) {
            return click(e);
        }
    }, renderMarks(), /*#__PURE__*/ _react.default.createElement("div", {
        className: "".concat(classPrefix, "-bar"),
        style: barStyle()
    }, renderButtonWrapper())), maxDescription !== null && /*#__PURE__*/ _react.default.createElement("div", {
        className: "".concat(classPrefix, "-max")
    }, maxDescription || max));
};
Range.displayName = 'NutRange';
