<template>
  <fl-select
    v-model="value"
    v-bind="$attrs"
    :list="housesList"
    :init-list="initList"
    placeholder="Дом"
    class="fl-filter-select-house"
    has-one-value
    clear
    @change="activeHouses = $event"
    @clear="clearHouses"
    @apply="$emit('apply')"
  />
</template>

<script>
import { mapState } from 'vuex'
import { declinationWord, HOUSES } from '@/lib/data/words'
import FlSelect from '@/core-components/FlSelect'

export default {
  name: 'FlSelectHouse',
  components: { FlSelect },
  props: {
    listHouses: {
      type: Array,
      default: () => ([])
    },

    initValue: {
      type: Number,
      default: 0
    },

    districtId: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    return {
      value: '',
      activeHouses: [],
      initList: []
    }
  },

  computed: {
    ...mapState(['houses']),

    housesList () {
      const array = this.listHouses.length ? this.listHouses : this.houses
      return array.map(item => ({
        id: item.id,
        value: item.address
      }))
    }
  },

  created () {
    this.setInitList()
  },

  methods: {
    clearHouses () {
      this.value = ''
    },

    setInitList () {
      const id = this.activeHouses[0] ? this.activeHouses[0].id : this.initValue
      this.initList = this.housesList.filter(item => item.id === id)
    }
  },

  watch: {
    activeHouses () {
      const count = this.activeHouses.length
      if (count <= 1) {
        this.value = this.activeHouses.map(item => item.value).toString()
      } else {
        this.value = `Выбрано ${count} ${declinationWord(count, HOUSES)}`
      }
      this.$emit('change', this.activeHouses)
    },

    initValue: {
      handler () {
        this.setInitList()
      },
      immediate: true
    },

    housesList () {
      this.activeHouses.length && this.setInitList()
    }
  }
}
</script>
<style lang="scss" scoped>
  .fl-filter-select-house ::v-deep {
    .fl-filter-select__dropdown {
      min-width: 300px;
    }

    .fl-filter-select__list--item span {
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
</style>
