<template>
  <div :style="{ width: item.width ? item.width + 'px' : '100%' }">
    <v-text-field
      v-model="value"
      variant="outlined"
      :density="item.dense || 'compact'"
      :type="item.type"
      :rules="item.rules"
      :disabled="item.disabled"
      :style="{width: item.width}"
      :color="item.color || 'primary'"
      :label="item.label"
      :placeholder="item.placeholder || item.label"
      :autofocus="item.autofocus"
      :required="item.required"
      :class="item.class"
      :suffix="item.suffix"
      :append-icon="item.appendIcon"
      :append-inner-icon="item.appendInnerIcon"
      :clearable="item.clearable"
      :readonly="item.readonly"
      :counter="item.counter"
      :prepend-inner-icon="item.prependInnerIcon"
      hide-spin-buttons
      :hide-details="item.hideDetails || false"
      @wheel="$event => handleWheel($event, item)"
      @update:modelValue="modelValueUpDate"
      @click:append="appendClick"
      @click:append-inner="appendInnerClick"
      @keyup.enter="handleKeyup"
      @click:clear="handleClear"
    ></v-text-field>
  </div>
</template>
<script setup>
import { debounce } from 'lodash'
import { defineEmits, ref, watch } from 'vue';
defineOptions({ name:'FormUI-v-text-field'})

const props = defineProps({item: Object, modelValue: [String, Number]})
const emit = defineEmits(['update:modelValue', 'change', 'appendClick', 'appendInnerClick', 'enter'])
const item = props.item
const value = ref(props.modelValue)
const searchDebouncedTime = item?.searchDebouncedTime === 0 ? ref(0) : ref(500)

watch(() => props.modelValue, (newVal) => {
  value.value = newVal
})
const modelValueUpDate = (val) => {
  value.value = val
  emit('update:modelValue', value.value)
  debouncedCallbackUpDate(value.value) // emit('change', value.value)
}
const debouncedCallbackUpDate = debounce(newValue => {
  emit('change', newValue)
}, searchDebouncedTime.value)

const appendClick = () => {
  if (item.appendClick) item.appendClick()
  emit('appendClick', value.value)
}
const appendInnerClick = () => {
  if (item.appendInnerClick) item.appendInnerClick(value.value)
  emit('appendInnerClick', value.value)
}

const handleClear = () => {
  emit('enter', value.value)
}

const handleKeyup = () => {
  emit('enter', value.value)
}

const handleWheel = (event, item) => {
  if (item.type !== 'number') return
  event.preventDefault()
  if (event.deltaY > 0) {
    item.value--
  } else {
    item.value++
  }
}
</script>
<style lang="scss" scoped>

</style>