<template>
  <dropdown-menu :label="label" class="d-inline-block position-relative bg-white border rounded" :close-on-click="false">
    <template v-if="items.length > 0">
      <div class="px-2 py-2 d-flex align-items-center dropdown-item" v-for="(item, index) in items" :key="index" @click="() => select(item)">
        <input class="mr-2" type="checkbox" :checked="model.indexOf(item) !== -1" :id="`checkbox-${index}`">
        {{ item.title }}
      </div>
    </template>
    <slot v-else></slot>
  </dropdown-menu>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

import DropdownMenu from './dropdown-menu.vue';

export interface SelectDropdownItem {
  title: string;
  [key: string]: any;
}

@Component({
  components: {
    DropdownMenu
  }
})
export default class SelectDropdownMenu extends Vue {
  @Prop({ type: String, required: true }) readonly placeholder!: string;
  @Prop({ type: Array, required: true }) readonly items!: SelectDropdownItem[];
  @Prop({ type: Array, required: true }) readonly value!: SelectDropdownItem[];

  select(item: SelectDropdownItem) {
    const itemIndex = this.model.indexOf(item);
    itemIndex !== -1 ? this.model.splice(itemIndex, 1) : this.model.push(item);
  }

  get model(): SelectDropdownItem[] {
    return this.value;
  }

  set model(value: SelectDropdownItem[]) {
    this.$emit('input', value);
  }

  get label(): string {
    return this.model.map(item => item.title).join(', ') || this.placeholder;
  }
}
</script>

<style lang="scss" scoped>
.dropdown-item {
  cursor: pointer;

  &:hover {
    background-color: #F8F9FA;
  }
}
</style>
