<!--
Liste déroulante avec autocompletion

@see https://vuetifyjs.com/en/components/autocompletes/#usage
-->

<template>
  <main>
    <v-autocomplete
      :items="itemsToDisplayed"
      :label="$t(label)"
      item-text="textDisplay"
      :item-value="itemValue"
      :multiple="multiple"
      :loading="isLoading"
      :return-object="returnObject"
      @change="$emit('update', $event, field)"
    />
  </main>
</template>

<script lang="ts">
import { computed, defineComponent, ComputedRef } from '@nuxtjs/composition-api'
import { AnyJson } from '~/types/interfaces'

export default defineComponent({
  props: {
    label: {
      type: String,
      required: false,
      default: null
    },
    field: {
      type: String,
      required: false,
      default: null
    },
    data: {
      type: String,
      required: false,
      default: null
    },
    items: {
      type: Array,
      required: false,
      default: () => []
    },
    readOnly: {
      type: Boolean,
      required: false
    },
    itemValue: {
      type: String,
      default: 'id'
    },
    itemText: {
      type: Array,
      required: true
    },
    returnObject: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    isLoading: {
      type: Boolean,
      default: false
    }
  },
  setup (props) {
    // On reconstruit les items à afficher car le text de l'Item doit être construit par rapport au itemText passé en props
    const itemsToDisplayed: ComputedRef<Array<AnyJson>> = computed(() => {
      return props.items.map((item: any) => {
        const textDisplay: Array<string> = []
        for (const text of props.itemText) {
          textDisplay.push(item[text as string])
        }
        return Object.assign({}, item, { textDisplay: textDisplay.join(' ') })
      })
    })

    return {
      label_field: props.label ?? props.field,
      itemsToDisplayed
    }
  }
})
</script>

<style scoped>

</style>
