<template>
  <fl-select
      v-model="value"
      v-bind="$attrs"
      :list="listDistricts"
      :init-list="initList"
      :has-checkbox="false"
      width-auto
      has-one-value
      placeholder="Жилой комплекс"
      @change="activeDistrict = $event"
      @apply="$emit('apply')"
  />
</template>

<script>
import FlSelect from '@/core-components/FlSelect'
import { mapGetters } from 'vuex'
export default {
  name: 'FlSelectDistrict',
  components: { FlSelect },

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

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

  data () {
    return {
      value: '',
      activeDistrict: [],
      initList: []
    }
  },

  computed: {
    ...mapGetters(['districts', 'housesObject']),

    listDistricts () {
      return this.districts.map(item => ({ value: item.name, id: item.id }))
    }
  },

  methods: {
    setInitList (initId) {
      const id = initId || this.initValue
      this.initList = this.listDistricts.filter(item => item.id === id)
    },

    initDistrict () {
      if (!this.houseId) {
        this.setInitList(-1)
        return
      }
      const house = this.housesObject[this.houseId]
      house && house.district_id && this.setInitList(house.district_id)
    }
  },

  watch: {
    activeDistrict () {
      if (!this.activeDistrict.length) {
        this.value = ''
      } else {
        this.value = this.activeDistrict[0].value
      }
      this.$emit('change', this.activeDistrict)
    },

    districts () {
      this.initValue && this.setInitList()
    },

    initValue () {
      this.setInitList()
    },

    housesObject: {
      handler () {
        this.initDistrict()
      },
      immediate: true
    },

    houseId (value) {
      if (!value) return
      this.initDistrict()
    }
  }
}
</script>
