<template>
  <div :style="{ width: item.width ? item.width + 'px' : '100%' }">
    <v-autocomplete
      v-model="value"
      :rules="item.rules"
      :attach="!item.noAttach"
      :loading="item.loading"
      :label="item.label"
      :placeholder="item.placeholder || item.label"
      :item-title="item.itemText || 'label'"
      :item-value="item.itemValue || 'value'"
      :items="item.items"
      variant="outlined"
      :density="item.dense || 'compact'"
      :append-to-body="true"
      :disabled="item.disabled"
      :multiple="item.multiple"
      :clearable="item.clearable"
      color="primary"
      :hide-no-data="item.hideNoData"
      :no-data-text="item.noDataText || 'No data available'"
      :hide-selected="item.hideSelected"
      @update:search="v => item.search ? debouncedCallbackSearch(v) : null"
      @update:modelValue="modelValueUpDate"
    ></v-autocomplete>
  </div>
</template>
<script setup>
import { debounce } from 'lodash'
import { ref, watch } from 'vue';
defineOptions({ name:'FormUI-v-autocomplete'})

const props = defineProps({item: Object, modelValue: [String, Number, Boolean]})

const value = ref()
watch(
  () => props.modelValue,
  (newVal) => {
    value.value = newVal
  },
  { immediate: true },
  { deep: true }
)

const emit = defineEmits(['update:modelValue', 'change', 'search'])
const item = props.item
const searchDebouncedTime = item.searchDebouncedTime === 0 ? 0 : 500

const modelValueUpDate = (val) => {
  value.value = val
  emit('update:modelValue', value.value)
  emit('change', value.value)
}

const debouncedCallbackSearch = debounce(newValue => {
  emit('search', newValue)
}, searchDebouncedTime)
</script>
<style lang="scss" scoped>
</style>