<template>
  <el-input-number
    :model-value="modelValue"
    :placeholder="placeholder"
    :disabled="isDisabled"
    :readonly="readonly"
    :min="min"
    :max="max"
    :step="step"
    :precision="precision"
    :controls-position="controlsPosition"
    controls
    @update:model-value="handleChange"
    @blur="handleBlur"
    @focus="handleFocus"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue'
import type { FieldConfig } from '@/types/form'

interface Props {
  modelValue: number
  field: FieldConfig
  disabled?: boolean
  readonly?: boolean
  step?: number
  precision?: number
  controlsPosition?: 'right' | ''
}

interface Emits {
  (e: 'update:modelValue', value: number | undefined): void
  (e: 'blur', event: FocusEvent): void
  (e: 'focus', event: FocusEvent): void
}

const props = withDefaults(defineProps<Props>(), {
  step: 1,
  precision: 0,
  controlsPosition: ''
})

const emit = defineEmits<Emits>()

const placeholder = computed(() => props.field.placeholder || `请输入${props.field.label}`)

const isDisabled = computed(() => {
  if (props.disabled) return true
  if (typeof props.field.disabled === 'function') {
    return false
  }
  return props.field.disabled || false
})

const min = computed(() => props.field.validationRules?.min)
const max = computed(() => props.field.validationRules?.max)

const handleChange = (value: number | undefined) => {
  emit('update:modelValue', value)
}

const handleBlur = (event: FocusEvent) => {
  emit('blur', event)
}

const handleFocus = (event: FocusEvent) => {
  emit('focus', event)
}
</script>

<style scoped lang="scss">
.el-input-number {
  width: 100%;
}
</style>
