<template>
    <el-input-number
        v-model="warningValue" :min="0" class="w-46px" :controls="false" :step="0.01"
        @input="handleInput"
        @blur="inputBlur"
    />
</template>

<script setup>
import { ref, watch } from 'vue'
import { isNullES } from 'js-fast-way'

defineOptions({
    name: 'HcInputNumberNum',
})

//双向绑定
const modelValue = defineModel('modelValue', {
    type: [String, Number],
    default: '',
})

//监听数据改变
const warningValue = ref('')
watch(() => modelValue.value, (val) => {
    warningValue.value = isNullES(val) ? null : Number(val)
}, { deep: true, immediate:true })


const handleInput = (val) => {
    if (val === null || val === '') return
    // 允许输入多个小数位，不做处理
    warningValue.value = val
    modelValue.value = Number(val) // 确保传递给modelValue的是数字类型
}

//失去焦点时处理小数位数
const inputBlur = () => {
    if (warningValue.value === null || warningValue.value === '') return
    const roundedValue = Number(warningValue.value).toFixed(2)
    warningValue.value = Number(roundedValue)
    // modelValue.value = roundedValue
    modelValue.value = Number(roundedValue) // 确保传递给modelValue的是数字类型
}
</script>
