<template>
  <el-input
    :model-value="innerValue"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    @input="handleInput"
    @update:model-value="handleChange"
  />
</template>

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

const props = defineProps({
  modelValue: String,
  placeholder: String,
  clearable: Boolean,
  disabled: Boolean,
  inputType: { type: String, default: 'text' },
  decimalDigits: { type: Number, default: 2 }
})

const emit = defineEmits(['update:modelValue'])

const innerValue = ref(props.modelValue)

watch(() => props.modelValue, val => {
  innerValue.value = val
})

function handleInput(value) {
  let result = String(value ?? '').trim()
  if (props.inputType === 'integer') {
    result = result.replace(/[^\d]/g, '')
  } else if (props.inputType === 'decimal') {
    result = result.replace(/[^\d.]/g, '')
    if (result.startsWith('.')) result = '0.' + result.slice(1)
    const parts = result.split('.')
    if (parts.length > 2) result = parts[0] + '.' + parts.slice(1).join('')
    if (result.includes('.')) {
      const [int, dec] = result.split('.')
      if (dec.length > props.decimalDigits) {
        result = int + '.' + dec.slice(0, props.decimalDigits)
      }
    }
  }
  innerValue.value = result
  emit('update:modelValue', result)
}

function handleChange(value) {
  emit('update:modelValue', value)
}
</script>