<template>
  <el-input-number
    :model-value="modelValue"
    controls-position="right"
    v-bind="$attrs"
    @focus="onFocus"
    @blur="onBlur"
    @change="onChange"
  >
    <template #prefix>
      <slot name="prefix"></slot>
    </template>
    <template #suffix>
      <slot name="suffix"></slot>
    </template>
  </el-input-number>
</template>

<script setup lang="ts">
import { useAttrs, ref } from 'vue'
import { isNumber } from 'lodash-es'

const modelValue = defineModel<number>('modelValue')

defineOptions({
  name: 'InputNumber'
})

const attrs = useAttrs()
const beforeVal = ref<number>()

const onFocus = () => {
  beforeVal.value = modelValue.value
}

const onBlur = () => {
  if (modelValue.value === undefined || modelValue.value === null) {
    // 输入框为空时，恢复之前值
    modelValue.value = beforeVal.value
  }
}
const onChange = (value?: number) => {
  // 处理数字边界问题
  if (value === undefined || value === null) {
    return
  }
  const { min, max } = attrs
  if (isNumber(min) && value < min) {
    modelValue.value = min as number
  } else if (isNumber(max) && value > max) {
    modelValue.value = max as number
  } else {
    modelValue.value = value
  }
}
</script>

<style scoped></style>
