<template>
  <el-input v-model="data" @input="onInput" @blur="onBlur" class="asj-input-float" style="width: 100%;">
    <template v-if="prefix.length > 0" #prepend>{{ props.prefix }}</template>
    <template v-if="suffix.length > 0" #append>{{ props.suffix }}</template>
  </el-input>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
  },
  precision: {
    type: Number,
    // default: 2,
  },
  prefix: {
    type: String,
    default: '',
  },
  suffix: {
    type: String,
    default: '',
  }
})
const data = ref(props.modelValue)
const emits = defineEmits(['update:modelValue', 'blur'])

const onInput = (val: string) => {
  data.value = val
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
    .replace(/^\./g, '')
  const index = data.value.indexOf('.')
  if (index > 0) {
    if (data.value.length - index - 1 > props.precision) {
      data.value = val.substring(0, index + props.precision + 1)
    }
  }
  emits('update:modelValue', data.value)
}

const onBlur = () => {
  if (data.value !== '') {
    data.value = Number(data.value).toFixed(props.precision)
    emits('update:modelValue', data.value)
    emits('blur')
  }
}

watch(
  () => props.modelValue,
  () => (data.value = props.modelValue)
)
</script>

<style lang="scss" scoped>
::v-deep(.el-input-group__append) {
  padding: 0 10px !important;
}
::v-deep(.el-input-group__prepend) {
  padding: 0 10px !important;
}
</style>
