import type { Directive, DirectiveBinding } from "vue";

// 特殊字符
const reg1 = /^[0-9]\d*$/
// 连输输入多个0，只保留一个0
const zeroReg = /^0+(\d)/
const _reg = /[^\d.]/g; //移除特殊字符
const precisionReg = /(\.\d\d)\d+$/; //最多保留2位小数
const _reg2 = /^\./ //小数点开头
const _reg3 = /(\.\d*\.)/g //连续输入多个小数点，只保留一个

/**只能输入正整数，包含0 */
const positiveNumber: Directive = {
    mounted: (el: HTMLElement) => {
        el.addEventListener('input', (event: Event) => {
            const content = (event.target as HTMLInputElement).value
            if (!reg1.test(content)) {
                (event.target as HTMLInputElement).value = '';
            } else if (zeroReg.test(content)) {
                (event.target as HTMLInputElement).value = '$1';
            }
        })
    }
}
/**minRow-maxRow，最多保留2位小数 */
const precision = {
    mounted: (el: HTMLElement, binding: DirectiveBinding) => {
        const bindingValue = binding.value
        el.addEventListener('keydown', (event: KeyboardEvent) => {
            event.stopPropagation()
            const inputKey = event.key
            const value = (event.target as HTMLInputElement).value
            disabledInput(event, inputKey, value, bindingValue)
        })
        el.addEventListener('input', (event) => {
            const value = (event.target as HTMLInputElement).value;
            if (/[^\d.-]/g.test(value)) {
                event.preventDefault();
                (event.target as HTMLInputElement).value = ''
            }
            bindingValue.update(bindingValue.$index, (event.target as HTMLInputElement).value)
        })
    }
}

let _v = ''

function disabledInput(event: KeyboardEvent, inputKey: string, value: string, bindingValue) {
    if (!bindingValue && !Object.keys(bindingValue).length) return
    const { minRow, maxRow } = bindingValue

    if (inputKey === 'Backspace' || inputKey === 'Shift') {
        _v = '';
        return
    }
    if (value) {
        _v = value + inputKey
    } else {
        _v += inputKey
    }

    if (/[^\d.-]/g.test(_v)) {
        event.preventDefault();
        _v = ''
    } else if (_reg.test(_v)) {
        event.preventDefault();
        _v = ''
    } else if (zeroReg.test(_v)) {
        event.preventDefault();
        _v = ''
    } else if (precisionReg.test(_v)) {
        event.preventDefault();
        _v = ''
    } else if (_reg2.test(_v)) {
        event.preventDefault()
        _v = ''
    } else if (_reg3.test(_v)) {
        event.preventDefault()
        _v = ''
    } else if (_v > maxRow || _v < minRow) {
        event.preventDefault();
        _v = ''
    } else {
        (event.target as HTMLInputElement).value = _v
        bindingValue.update(bindingValue.$index, (event.target as HTMLInputElement).value)
    }
}
export {
    positiveNumber,
    precision
}