/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

import { __assign, __rest, __read, __spreadArray } from 'tslib';
import React__default, { useMemo, useEffect, useRef, useState } from 'react';
import { themeable } from 'amis-core';
import Input from './Input.js';
import isEqualWith from 'lodash/isEqualWith';

var defaultLength = 6;
function isExist(obj) {
    return obj || obj === 0;
}
var Backspace = {
    key: 'Backspace',
    code: 8
};
function isUndefined(obj) {
    return obj === undefined;
}
function usePrevious(value) {
    var ref = useRef();
    useEffect(function () {
        ref.current = value;
    });
    return ref.current;
}
function useMergeValue(defaultStateValue, props) {
    var value = (props || {}).value;
    var firstRenderRef = useRef(true);
    var prevPropsValue = usePrevious(value);
    var _a = __read(useState(!isUndefined(value) ? value : defaultStateValue), 2), stateValue = _a[0], setStateValue = _a[1];
    useEffect(function () {
        if (firstRenderRef.current) {
            firstRenderRef.current = false;
            return;
        }
        if (value === undefined && prevPropsValue !== value) {
            setStateValue(value);
        }
    }, [value]);
    var mergedValue = isUndefined(value) ? stateValue : value;
    return [mergedValue, setStateValue, stateValue];
}
function useVerificationCode(props) {
    var _a = __read(useMergeValue('', props), 2), value = _a[0], setValue = _a[1];
    var length = props.length
        ? +props.length > 0
            ? +props.length
            : defaultLength
        : defaultLength;
    var filledValue = useMemo(function () {
        var newVal = value ? String(value).split('') : [];
        return new Array(length).fill('').map(function (_, index) {
            return isExist(newVal[index]) ? String(newVal[index]) : '';
        });
    }, [value, length]);
    var focusFirstEmptyInput = function () {
        var _a, _b, _c;
        var nodeList = ((_a = props.getInputRefList) === null || _a === void 0 ? void 0 : _a.call(props)) || [];
        // 焦点的元素
        if ((nodeList === null || nodeList === void 0 ? void 0 : nodeList.indexOf(document.activeElement)) === -1) {
            return;
        }
        var index = filledValue.findIndex(function (x) { return !x; });
        if (index > -1) {
            var realIndex = Math.min(index, nodeList.length - 1);
            (_c = (_b = nodeList[realIndex]) === null || _b === void 0 ? void 0 : _b.focus) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
    };
    useEffect(function () {
        var _a, _b, _c;
        focusFirstEmptyInput();
        if (filledValue.length === length && filledValue.every(function (item) { return !!item; })) {
            var nodeList = ((_a = props.getInputRefList) === null || _a === void 0 ? void 0 : _a.call(props)) || [];
            (_c = (_b = nodeList[nodeList.length - 1]) === null || _b === void 0 ? void 0 : _b.blur) === null || _c === void 0 ? void 0 : _c.call(_b);
        }
    }, [JSON.stringify(filledValue)]);
    var tryUpdateValue = function (newVal) {
        var _a, _b;
        if (!isEqualWith(newVal, value)) {
            setValue(newVal);
            (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, newVal);
            if (newVal.length === length) {
                (_b = props.onFinish) === null || _b === void 0 ? void 0 : _b.call(props, newVal);
            }
        }
    };
    var handlePaste = function (e, index) {
        e.preventDefault();
        var clipboardData = e.clipboardData;
        var text = clipboardData.getData('text');
        if (text) {
            tryUpdateValue(filledValue.slice(0, index).concat(text.split('')).join(''));
        }
    };
    return {
        value: value,
        filledValue: filledValue,
        setValue: tryUpdateValue,
        getInputProps: function (index) {
            var indexVal = String(filledValue[index]);
            return {
                key: index,
                value: indexVal,
                onClick: function (e) {
                    e.preventDefault();
                    if (!filledValue[index]) {
                        focusFirstEmptyInput();
                    }
                },
                onKeyDown: function (e) {
                    var keyCode = e.key;
                    if (keyCode === Backspace.key) {
                        if (filledValue[index + 1]) {
                            e.preventDefault();
                            return;
                        }
                        var _index = index;
                        if (!filledValue[index]) {
                            _index -= 1;
                        }
                        var newVal = __spreadArray([], __read(filledValue), false);
                        newVal[_index] = '';
                        tryUpdateValue(newVal.join(''));
                    }
                },
                onChange: function (v) {
                    var char = (v === null || v === void 0 ? void 0 : v.trim()) || '';
                    var newVal = __spreadArray([], __read(filledValue), false);
                    newVal[index] = char.replace(indexVal, '').split('').pop() || '';
                    tryUpdateValue(newVal.join(''));
                },
                onPaste: function (e) {
                    handlePaste(e, index);
                }
            };
        }
    };
}
function VerificationCodeComponent(baseProps) {
    var props = __assign({ length: defaultLength }, baseProps);
    var separator = props.separator, length = props.length, masked = props.masked, disabled = props.disabled, readOnly = props.readOnly, cx = props.classnames, onChange = props.onChange, onFinish = props.onFinish, propsValue = props.value, style = props.style;
    var focusEleRefList = React__default.useRef([]);
    var _a = useVerificationCode({
        value: propsValue,
        length: length,
        getInputRefList: function () { return focusEleRefList.current; },
        onChange: onChange,
        onFinish: onFinish
    }), filledValue = _a.filledValue, getInputProps = _a.getInputProps;
    return (React__default.createElement("div", { className: cx('Verification-code'), style: style }, filledValue.map(function (v, index) {
        var _a = getInputProps(index), InputChange = _a.onChange, onClick = _a.onClick, onPaste = _a.onPaste, onKeyDown = _a.onKeyDown, restInputProps = __rest(_a, ["onChange", "onClick", "onPaste", "onKeyDown"]);
        return (React__default.createElement(React__default.Fragment, { key: index },
            React__default.createElement(Input, __assign({ disabled: disabled, readOnly: readOnly, ref: function (node) {
                    return (focusEleRefList.current[index] = node);
                }, className: cx({
                    'is-disabled': !!disabled
                }) }, restInputProps, { onClick: !readOnly ? onClick : undefined, onPaste: !readOnly ? onPaste : undefined, onKeyDown: !readOnly ? onKeyDown : undefined, onChange: !readOnly
                    ? function (e) {
                        var inputValue = (e.target.value || '').trim();
                        InputChange(inputValue);
                    }
                    : undefined, type: masked ? 'password' : 'text' })), separator === null || separator === void 0 ? void 0 :
            separator({ index: index, character: v })));
    })));
}
var VerificationCode = themeable(VerificationCodeComponent);

export { Backspace, VerificationCodeComponent, VerificationCode as default, isExist, isUndefined, useMergeValue, usePrevious, useVerificationCode };
