<template>
  <v-autocomplete
    v-bind="resolveProps()"
    v-model="searchModel"
    :items="items"
    :class="[variant, { 'absolute-autocomplete': absolute }]"
    @update-items="handleUpdateItems"
    @on-show="autocompleteShow"
    @item-selected="itemSelected"
    ref="autoComplete"
  />
</template>
<script>
import Vue from 'vue'
import EshopAutoCompleteTemplate from '../templates/EshopAutoCompleteTemplate'
import EshopAutoCompleteMemberTemplate from '../templates/EshopAutoCompleteMemberTemplate'

export default Vue.extend({
  props: {
    componentItem: { default: () => null },
    minLen: { type: Number, required: false },
    readonly: { type: Boolean, required: false, default: false },
    wait: { type: Number, required: false },
    variant: { type: String, default: '' },
    absolute: { type: Boolean, default: true },
    value: null,
    getLabel: {
      type: Function,
      default: item => item,
    },
    items: Array,
    autoSelectOneItem: { type: Boolean, default: true },
    placeholder: String,
    inputClass: { type: String, default: 'v-autocomplete-input' },
    disabled: { type: Boolean, default: false },
    inputAttrs: {
      type: Object,
      default: () => {
        return {}
      },
    },
    keepOpen: { type: Boolean, default: false },
    templateName: { type: String, default: '' },
  },
  data() {
    return {
      searchModel: null,
      templateMap: new Map([
        ['member', EshopAutoCompleteMemberTemplate],
        ['', EshopAutoCompleteTemplate],
      ]),
    }
  },
  mounted() {
    this.autocompleteShow()
  },
  methods: {
    handleUpdateItems: function(text) {
      this.$emit('updateItems', text)
    },
    resolveProps: function() {
      return {
        ...this.$props,
        componentItem: this.resolveComponent(),
        inputAttrs: { ...this.inputAttrs, readonly: this.readonly },
      }
    },
    resolveComponent: function() {
      return this.componentItem || this.templateMap.get(this.templateName.toLowerCase())
    },
    autocompleteShow: function() {
      let Vue = this
      Vue.$nextTick(function() {
        let el = Vue.$refs.autoComplete.$el.querySelector('.v-autocomplete-list-wrapper')
        if (el) {
          Vue.$vuebar.initScrollbar(el, {
            preventParentScroll: true,
            resizeRefresh: true,
          })
        }
      })
    },
    itemSelected: function(payload) {
      this.$emit('item-selected', payload)
    },
  },
  watch: {
    searchModel(to) {
      this.$emit('input', to)
    },
    value(val) {
      this.searchModel = val
    },
  },
})
</script>
