<template>
  <ui-select
    v-on="$listeners"
    v-bind="$attrs"
    :value="value"
    @input="input"
    @filter="search"
    use-input
    hide-selected
    emit-value
    fill-input
    map-options
    label="Кому"
    :options="clients"
    class="full-width select"
    dropdown-icon="la la-angle-double-down"
    :option-label="optionLabel"
    option-value="id"
    name="clientId"
    :outlined="false"
    :input-debounce="250"
  >
    <template v-slot:option="scope">
      <q-item v-bind="scope.itemProps" v-on="scope.itemEvents">
        <q-item-section side>
          <client-select-avatar :client="scope.opt" />
        </q-item-section>
        <q-item-section>
          <q-item-label class="matched" v-html="scope.opt.matched" />
          <q-item-label class="text-blue-grey">
            {{ getDescription(scope.opt) }}
          </q-item-label>
        </q-item-section>
      </q-item>
    </template>
    <template v-slot:no-option>
      <q-item>
        <q-item-section class="text-blue-grey">
          Клиенты не найдены
        </q-item-section>
      </q-item>
    </template>
  </ui-select>
</template>

<script lang="ts">
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator'
import UiSelect from '@/lib-components/form/UiSelect.vue'
import SearchedClient from '@/widgets/base/types/SearchedClient'
import Client from '@/widgets/base/types/Client'
import ClientSelectAvatar from '@/widgets/base/components/client-form/ClientSelectAvatar.vue'
import { QItem, QItemLabel, QItemSection } from 'quasar'

@Component({
  inheritAttrs: false,
  components: { ClientSelectAvatar, UiSelect, QItem, QItemSection, QItemLabel },
})
export default class ClientSelect extends Vue {
  @Prop(Number)
  value!: number

  @Prop(Function)
  searchFn!: (val: string) => Promise<SearchedClient[]>

  @Prop(Function)
  getClientByIdFn!: (clientId: number) => Promise<Client>

  @Prop(Array)
  defaultClients!: SearchedClient[]

  clients: SearchedClient[] | Client[] = []

  search(val: string, update: Function, abort: Function) {
    if (!val) {
      abort()
    } else {
      this.searchFn(val).then(clients => {
        update(() => (this.clients = clients))
      })
    }
  }

  getDescription(client: SearchedClient): string {
    return (
      (client.matchedByName ? client.email || client.phone : client.fullName) ||
      '-'
    )
  }

  optionLabel(client: Client): string {
    return client.fullName || client.email || client.phone
  }

  @Watch('value', { immediate: true })
  loadClientById() {
    if (this.value && !this.clients.length) {
      this.getClientByIdFn(this.value).then(client => (this.clients = [client]))
    }
  }

  @Emit()
  input(value: string) {
    return parseInt(value)
  }
}
</script>
