<template>
  <div>
     <b-autocomplete
       placeholder=""
       icon="magnify"
       expanded
       :data="data"
       :open-on-focus="first? true : false"
       keep-first
       :field="field"
       v-model="value"
       @typing="beginSearch"
       @select="option => doSelect(option)">
         <template slot-scope="props">
           <p>{{ props.option[field] }}</p>
         </template>
         <template slot="empty">Không có giá trị thỏa mãn</template>
     </b-autocomplete>
 </div>
</template>
<script>
export default {
 props: ['api', 'field', 'column', 'first', 'optionid', 'filter', 'storeval'],
 data() {
   return {
     search: undefined,
     data: [],
     timer: undefined,
     value: undefined,
     selected: undefined,
     params: this.$findapi(this.api)['params']
   }
 },
 async created() {
  if(this.first) {
    this.data = await this.$getdata(this.api, this.filter)
    if(this.optionid) this.selected = this.$find(this.data, {id: this.optionid})
  } else if(this.optionid) {
    this.selected = await this.$getdata(this.api, {id: this.optionid.id}, undefined, true)
  }
  if(this.selected) this.doSelect(this.selected)
 },
 methods: {
   doSelect(option) {
     if(this.$empty(option)) return
     this.$emit('option', option)
     this.selected = option
     this.value = this.selected[this.field]
   },
   async getApi(val) {
    let text = val? val.toLowerCase() : ''
    let f = {}
    this.column.map(v=>{
      f[`${v}__icontains`] = text
    })
    this.params.filter_or = f
    if(this.filter) this.params.filter = this.$copy(this.filter)
    this.data = await this.$getdata(this.api, undefined, this.params)
   },
   beginSearch(val) {
     this.search = val
     if (this.timer) clearTimeout(this.timer)
     this.timer = setTimeout(() => this.getApi(val), 150)
   }
 }
}
</script>