<template>
  <q-slide-transition>
    <ui-menu-group v-if="sourceOrders.length" title="Привязка к заказу">
      <div class="q-px-md q-pb-sm">
        <ui-autocomplete
          @filter="filter"
          v-on="$listeners"
          v-bind="$attrs"
          :options="orders"
          dense
          emit-value
          option-label="name"
          option-value="name"
        />
      </div>
    </ui-menu-group>
  </q-slide-transition>
</template>

<style scoped>
::v-deep i:not(.q-select__dropdown-icon) {
  font-size: 20px !important;
}
</style>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { Order } from '@/widgets/base/types/Order'
import UiAutocomplete from '@/lib-components/form/UiAutocomplete.vue'
import ClientService from '@/widgets/messages/services/ClientService'
import UiMenuGroup from '@/lib-components/menu/UiMenuGroup.vue'
import { QSlideTransition } from 'quasar'

@Component({
  inheritAttrs: false,
  components: { UiMenuGroup, UiAutocomplete, QSlideTransition },
})
export default class SubjectOrderSelect extends Vue {
  @Prop({ type: Number, required: true })
  clientId!: number

  sourceOrders: Order[] = []
  orders: Order[] = []

  filter(query: string, update: Function) {
    if (!query) {
      update(() => (this.orders = this.sourceOrders))
    } else {
      update(() => {
        this.orders = this.sourceOrders.filter(order =>
          order.name.toLowerCase().includes(query.toLowerCase())
        )
      })
    }
  }

  created() {
    ClientService.getOrdersByClientId(this.clientId).then(orders => {
      this.sourceOrders = orders
      this.orders = orders
    })
  }
}
</script>
