<script setup>
import { ref, computed, useSlots } from 'vue'
import useStyle from '../hooks/useStyle'
import useSlotConfig from '../hooks/useSlotConfig'

defineOptions({
  name: 'VAutocomplete'
})

const root = ref(null)

const props = defineProps({
  field: {
    type: Object,
    required: true
  }
})

const model = defineModel({ type: String })
const slots = useSlots()

const slotConfig = useSlotConfig(props.field)

const { style } = useStyle(props)

const fieldInfo = computed(() => {
  let { slots, ...rest } = props.field || {}
  return rest
})

defineExpose({
  root,
  get activated() {
    return root.value.activated
  },
  blur() {
    root.value.blur()
  },
  close() {
    root.value.close()
  },
  focus(...rest) {
    root.value.focus(...rest)
  },
  handleSelect(...rest) {
    root.value.handleSelect(...rest)
  },
  handleKeyEnter(...rest) {
    root.value.handleKeyEnter(...rest)
  },
  get highlightedIndex() {
    return root.value.highlightedIndex
  },
  highlight(...rest) {
    root.value.highlight(...rest)
  },
  get inputRef() {
    return root.value.inputRef
  },
  get loading() {
    return root.value.loading
  },
  get popperRef() {
    return root.value.popperRef
  },
  get suggestions() {
    return root.value.suggestions
  }
})
</script>

<template>
  <el-autocomplete ref="root" v-model="model" v-bind="fieldInfo" :style="style">
    <template v-if="slotConfig.default && slots[slotConfig.default]" #default="data">
      <slot :name="slotConfig.default" v-bind="data"></slot>
    </template>
    <template v-if="slotConfig.prefix && slots[slotConfig.prefix]" #prefix>
      <slot :name="slotConfig.prefix"></slot>
    </template>
    <template v-if="slotConfig.suffix && slots[slotConfig.suffix]" #suffix>
      <slot :name="slotConfig.suffix"></slot>
    </template>
    <template v-if="slotConfig.prepend && slots[slotConfig.prepend]" #prepend>
      <slot :name="slotConfig.prepend"></slot>
    </template>
    <template v-if="slotConfig.append && slots[slotConfig.append]" #append>
      <slot :name="slotConfig.append"></slot>
    </template>
    <template v-if="slotConfig.loading && slots[slotConfig.loading]" #loading>
      <slot :name="slotConfig.loading"></slot>
    </template>
  </el-autocomplete>
</template>