<template>
    <!-- 数字输入框 -->
    <up-input
        v-model="inputVal"
        type="number"
        :inputAlign="inputAlign"
        :border="border"
        :placeholder="placeholder"
        :clearable="clearable"
        @change="change"
        @blur="blur"
    ></up-input>
</template>

<script setup>
import { ref, watch } from 'vue'

const es = defineEmits(['update:modelValue', 'change'])
const ps = defineProps({
    modelValue: {
        type: [Number, String],
        default: null
    },
    inputAlign: {
        type: String,
        default: 'right'
    },
    border: {
        type: String,
        default: 'none'
    },
    placeholder: {
        type: String,
        default: '请输入'
    },
    clearable: {
        type: Boolean,
        default: true
    },
    precision: {
        type: Number,
        default: 0
    },
    min: {
        type: Number,
        default: 0
    },
    max: {
        type: Number,
        default: Infinity
    },
    // 大于
    greater: {
        type: Number,
        default: -Infinity
    }
})
const inputVal = ref(ps.modelValue)
watch(
    () => ps.modelValue,
    (newValue) => {
        inputVal.value = newValue
    }
)
const change = (value) => {
    if (value.includes('.')) {
        if (ps.precision === 0) {
            value = value.replace('.', '')
        } else {
            const nums = String(value).split('.')
            if (nums[1].length >= ps.precision) {
                value = nums[0] + '.' + nums[1].substring(0, ps.precision)
            }
        }
    }
    let val = value ? parseFloat(value) : ''
    if (val < ps.min || val > ps.max) {
        val = Math.min(Math.max(val, ps.min), ps.max)
    }
    setTimeout(() => {
        inputVal.value = val
        es('update:modelValue', val)
    }, 10)
}
const blur = (value) => {
    if (parseFloat(value) <= ps.greater) {
        setTimeout(() => {
            inputVal.value = ''
            es('update:modelValue', '')
        }, 10)
    }
}
</script>
<style lang="scss" scoped></style>
