<template>
  <div class="fl-rooms-list-container">
    <div class="fl-rooms-list">
      <div class="fl-rooms-list-header">
        <div v-if="hasSomeRooms" class="fl-rooms-list-data__cell">
          <fl-checkbox
              :checked="selectedAll"
              @change="setSelectedAll"
              class="fl-rooms-data-row__checkbox"
          />
        </div>
        <div
            v-for="(item, i) in headersList"
            :key="`header-${i}`"
            class="fl-rooms-list-header__cell"
            :style="getWidthCell(item)"
        >
          {{ item.value }}
        </div>
      </div>
      <div class="fl-rooms-list-data">
        <div v-for="(room, i) in roomsList"
             :key="room.id"
             class="fl-rooms-data-row"
             :class="{'active': room.id === activeRoomId || isCheckedRoom(room.id).checked}"
             @click.stop="setActiveRoom(room.id, $event)"
        >
          <div class="fl-rooms-list-data__cell"
               v-if="hasSomeRooms"
               @click.stop.prevent="checkRoom(i)"
          >
            <fl-checkbox
                :checked="isCheckedRoom(room.id).checked"
                class="fl-rooms-data-row__checkbox"
            />
          </div>
          <div
              v-for="item in headersList"
              :key="`${item.key}-${i}`"
              class="fl-rooms-list-data__cell"
              :style="getWidthCell(item)"
          >
            <div v-if="item.key !== 'status'">{{ room[item.key] }}</div>
            <div
                v-else
                :style="`background: ${room[item.key].color}`"
                class="fl-rooms-list-header__cell--status"
            >
              {{ room[item.key].value }}
            </div>
          </div>
        </div>
      </div>
      <transition name="fade">
        <div v-if="countSelectedRoom" class="fl-rooms-list-modal">
          <span>{{ countTitle }}</span>
          <fl-button
              type="is-primary"
              :title="options.actions[0].name"
              class="fl-rooms-list-modal__button"
              @click="$root.$emit('action', options.actions[0])"
          />
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import cardMixin from '@/mixins/cardMixin'
import FlCheckbox from '@/core-components/FlCheckbox'
import FlButton from '@/core-components/form/FlButton'
import { declinationWord } from '@/lib/data/words'
import { deepClone, uniqInArray } from '@/lib/helpTools'

export default {
  name: 'FlRoomsList',
  components: { FlButton, FlCheckbox },
  mixins: [cardMixin],
  props: {
    activeRoomId: {
      type: Number
    },

    page: {
      type: Number
    }
  },

  data () {
    return {
      countSelectedRoom: 0,
      selectedAll: false,
      selectedList: {},
      selectedListId: [],
      headersList: [{ value: 'Тип помещения', key: 'room_type' },
        { value: '№ помещения', key: 'number' }, { value: 'Цена', key: 'price' },
        { value: 'Площадь', key: 'area', width: 8 }, { value: 'Комнат', key: 'room', width: 8 }, {
          value: 'Этаж',
          key: 'floor',
          width: 8
        },
        { value: 'Адрес', key: 'house', width: 15 }, { value: 'ЖК', key: 'district', width: 15 }, {
          value: 'Статус',
          key: 'status'
        }
      ]
    }
  },

  computed: {
    ...mapState(['rooms', 'options']),
    ...mapGetters(['nameDistrict', 'hasSomeRooms']),

    widthCell () {
      return this.headersList.reduce((accum, item) => item.width
        ? { width: accum.width + item.width, count: accum.count + 1 }
        : { width: accum.width, count: accum.count }, { width: 0, count: 0 })
    },

    roomsList () {
      return this.rooms.map(item => {
        return {
          number: item.number,
          house: this.getHouse(item),
          floor: this.floorTitle(item),
          district: this.nameDistrict(item.house_id),
          room_type: item.room_type.name,
          area: this.getArea(item),
          id: item.id,
          house_id: item.house_id,
          price: this.getPrice(item),
          room: item.room_count,
          status: this.getTitleStatus(item)
        }
      })
    },

    isCheckAllRooms () {
      return this.selectedList[this.page] && this.selectedList[this.page].length === this.roomsList.length
    },

    countTitle () {
      return `${declinationWord(this.countSelectedRoom, ['Выбран', 'Выбрано', 'Выбрано'])} ${this.countSelectedRoom}
      ${declinationWord(this.countSelectedRoom, ['oбъект', 'oбъекта', 'oбъектов'])}`
    }
  },

  methods: {
    setInitRooms () {
      if (this.selectedListId.length) {
        this.setSelectedList(this.rooms.filter((room) => this.selectedListId.indexOf(room.id) !== -1))
      }
    },

    setSelectedAll () {
      this.selectedAll = !this.selectedAll
      if (this.selectedAll) {
        this.setSelectedList(deepClone(this.rooms))
        this.selectedListId = uniqInArray([...this.selectedListId, ...this.rooms.map(room => room.id)])
      } else {
        this.setSelectedList([])
        this.rooms.forEach(room => {
          this.delIdSelectedRoom(room.id)
        })
      }
    },

    getWidthCell (item) {
      const width = !item.width ? (100 - this.widthCell.width) / (this.headersList.length - this.widthCell.count) : item.width
      return `width: ${width}%; max-width: ${width}%`
    },

    isCheckedRoom (id) {
      if (!this.selectedList[this.page]) this.setSelectedList([])
      const index = this.selectedList[this.page].findIndex(room => room.id === id)
      return {
        checked: index !== -1,
        index: index
      }
    },

    checkRoom (i) {
      const room = this.rooms[i]
      const roomCheck = this.isCheckedRoom(room.id)
      if (roomCheck.checked) {
        this.selectedList[this.page].splice(roomCheck.index, 1)
        this.setSelectedList(this.selectedList[this.page])
        this.delIdSelectedRoom(room.id)
      } else {
        this.setSelectedList([...this.selectedList[this.page], room])
        this.selectedListId.push(room.id)
      }
      this.setSelectedAllCheckbox()
    },

    setActiveRoom (id) {
      this.$emit('set-active', id)
    },

    setSelectedList (data) {
      this.$set(this.selectedList, this.page, data)
    },

    setSelectedAllCheckbox () {
      this.selectedAll = this.isCheckAllRooms
    },

    delIdSelectedRoom (id) {
      const i = this.selectedListId.indexOf(id)
      i !== -1 && this.selectedListId.splice(i, 1)
    }
  },

  watch: {
    selectedList: {
      handler: function () {
        let unitRooms = []
        this.countSelectedRoom = 0
        for (const key in this.selectedList) {
          if (Object.prototype.hasOwnProperty.call(this.selectedList, key)) {
            unitRooms = [...unitRooms, ...this.selectedList[key]]
          }
        }
        this.countSelectedRoom += this.selectedListId.length
        this.$emit('set-selected-rooms-id', this.selectedListId)
        this.$emit('set-selected-rooms', unitRooms)
      },
      deep: true
    },

    page () {
      this.setSelectedAllCheckbox()
    },

    'options.initSelectedRooms': {
      handler () {
        this.selectedListId = this.options.initSelectedRooms || []
        this.selectedListId.length && this.setInitRooms()
      },
      immediate: true
    },

    rooms () {
      this.setInitRooms()
      this.setSelectedAllCheckbox()
    }
  }
}
</script>

<style lang="scss" scoped>
.fl-rooms-list {
  overflow-x: scroll;
}

.fl-rooms-list-header {
  position: sticky;
  top: 0;
  z-index: 1;
  display: flex;
  box-sizing: border-box;
  min-width: 1200px;
  padding: 16px 44px 15px 12px;
  background: $light-01;
  border-bottom: 1px $light-02 solid;
}

.fl-rooms-list-header__cell {
  display: flex;
  align-items: center;
  justify-content: left;
  color: $grey-02;
  white-space: nowrap;
}

.fl-rooms-list-header__cell--status {
  width: 120px;
  padding: 4px;
  color: $light-01;
  border-radius: $border-radius-01;

  @include flex-center;
}

.fl-rooms-list-data {
  min-width: 1200px;
}

.fl-rooms-data-row__checkbox {
  margin-right: 15px;
}

.fl-rooms-data-row {
  display: flex;
  padding: 16px 44px 16px 12px;
  border-bottom: 1px $light-02 solid;
  cursor: pointer;

  &:hover {
    background: $grey-03;
  }
}

.fl-rooms-list-data__cell {
  display: flex;
  align-items: center;
  justify-content: left;
  word-break: break-word;
}

.active {
  background-color: $grey-03;
}

.fl-rooms-list-modal {
  position: fixed;
  bottom: 88px;
  left: 50%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-width: 580px;
  padding: 11px 16px 11px 25px;
  background-color: #2E3039;
  border-radius: $border-radius-01;
  transform: translateX(-50%);

  span {
    color: $light-01;
    line-height: 20px;
    letter-spacing: -0.2px;

  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.4s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

@include media-max-md {
  .fl-rooms-list-modal {
    flex-direction: column;
    width: 80%;
    min-width: auto;

    span {
      margin-bottom: 20px;
    }
  }
}
</style>
