<template>
  <el-input
    v-model.trim="val"
    type="text"
    :placeholder="placeholder"
    class="amountInput"
    :size="size"
    :disabled="props.isDisabled"
    @input="iptFn"
  >
    <template v-if="hasSuffix" #suffix>{{ suffix }}</template>
    <template v-if="hasAppend" #append>
      <component :is="appendRender" />
    </template>
  </el-input>
</template>
<script lang="tsx" setup>
import { isNumFloat } from '@/utils/validate'
const props = withDefaults(
  defineProps<{
    modelValue?: string | number
    suffix?: string
    placeholder?: string
    size?: '' | 'default' | 'small' | 'large'
    hasSuffix?: boolean
    hasAppend?: boolean
    appendRender?: () => JSX.Element
    isDisabled?: boolean
  }>(),
  {
    modelValue: '',
    suffix: '元',
    placeholder: '请输入费用',
    size: 'default',
    hasSuffix: true,
    isDisabled: false,
    hasAppend: false,
    appendRender: undefined,
  },
)
const emits = defineEmits<{
  (e: 'update:modelValue', data: string | number | null): void
  (e: 'input', data: string | number): void
}>()

const val = ref<string | number | null>(props.modelValue)

const iptFn = (e: string) => {
  const bool = isNumFloat(e) // 只允许输入数字和最多一个小数点
  if (e === '') {
    val.value = null
    emits('input', '')
  } else {
    if (bool) {
      const parts = e.split('.') // 将输入的数字按小数点分割成整数部分和小数部分
      if (parts[1] && parts[1].length > 2) {
        // 如果小数部分超过两位，则只保留两位小数
        val.value = `${parts[0]}.${parts[1].slice(0, 2)}`
      } else {
        val.value = e
      }
    } else {
      const decimalCount = (e.match(/\./g) || []).length // 计算小数点的个数
      if (decimalCount > 1) {
        // 如果小数点个数大于1，则将多余的小数点替换为空字符串
        val.value = e.replace(/\./g, (match: string, offset: number) => {
          console.log(67, match)
          return offset === e.lastIndexOf('.') ? '.' : ''
        })
      } else {
        val.value = e.replace(/[^\d.]/g, '')
      }
    }
  }
  emits('input', val.value || '')
}

watch(
  () => val.value,
  (newVal) => {
    if (newVal === '') {
      emits('update:modelValue', null)
    } else {
      emits('update:modelValue', newVal)
    }
  },
)

watch(
  () => props.modelValue,
  (newVal: string | number) => {
    if (newVal !== undefined) {
      val.value = newVal
    }
  },
  {
    immediate: true,
  },
)
</script>
<style lang="scss" scoped>
:deep() {
  .el-form-item__content {
    line-height: 0 !important;
  }
}
</style>
