<template>
  <div id="select">
    <fl-loading-secondary
        v-if="isLoaderSecondary"
        size="big"
        type="global"
    />
    <div class="fl-room-select" ref="select">
      <div class="fl-room-select-container__switcher">
        <div class="fl-room-select-title">Все помещения</div>
        <fl-switcher class="fl-room-select-switcher">
          <fl-switcher-item
              label="Список"
              :active-init="!activeChess"
              @click="setActive(1)"/>
          <fl-switcher-item
              label="Шахматка"
              :active-init="activeChess && !chessPlus"
              @click="setActive(2)"/>
          <fl-switcher-item
              label="Шахматка+"
              :active-init="activeChess && chessPlus"
              @click="setActiveChessPlus"/>
        </fl-switcher>
      </div>
      <fl-filter-rooms
          v-if="hasHouses && (devToken || csrfToken)"
          class="fl-room-select-filter"
          :local-filter="activeChess"
          :init-filter="initFilter"
          @search="searchFilters"
      />
      <fl-choose-district
          v-if="!activeRoomInDeal.id && activeChess && !(filterParameters.districtId && filterParameters.houseId)"
      />
      <slot name="notification"></slot>
        <fl-rooms-list
            v-if="!activeChess"
            :active-room-id="activeRoomId"
            :page="page"
            @set-active="setActiveRoom"
            @set-selected-rooms="$emit('set-selected-rooms', $event)"
            @set-selected-rooms-id="$emit('set-selected-rooms-id', $event)"
        />
        <fl-chess-rooms
            v-if="activeChess && filterParameters.districtId && filterParameters.houseId"
            :active-room-id="activeRoomId"
            :house-id="filterParameters.houseId"
            :chess-plus="chessPlus"
            :district-id="filterParameters.districtId"
            @set-active="setActiveRoom"
            @set-selected-rooms="$emit('set-selected-rooms', $event)"
            @set-selected-rooms-id="$emit('set-selected-rooms-id', $event)"
        />
        <fl-empty-result v-if="!activeChess && !hasResults && !isLoaderSecondary"/>
      <fl-room-panel-info
          :isOpen="isOpenActiveRoom"
          :active-room-id="activeRoomId"
          :active-id-room-in-deal="activeRoomInDeal.id"
          @remove-room="removeRoom"
          @click-create-deal="$emit('click-create-deal', $event)"
          @close="closePanel"
      />
      <fl-pagination
          v-if="Object.keys(paginationRooms).length && !activeChess"
          class="fl-room-select-pagination"
          :pagination="paginationRooms"
          @set-page="setPage"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import resizeMixin from '@/mixins/resizeMixin'
import FlFilterRooms from '@/components/filter/FlFilterRooms'
import { mapState, mapGetters } from 'vuex'
import FlPagination from '@/core-components/FlPagination'
import FlRoomsList from '@/components/list/FlRoomsList'
import FlSwitcher from '@/core-components/switcher/FlSwitcher'
import FlSwitcherItem from '@/core-components/switcher/FlSwithcerItem'
import FlLoadingSecondary from '@/core-components/FlLoadingSecondary'
import FlRoomPanelInfo from '@/components/panel/FlRoomPanelInfo'
import FlChessRooms from '@/components/FlChessRooms'
import FlEmptyResult from '@/components/FlEmptyResult'
import store from './store/index'
import './scss/fonts.css'
import vClickOutside from 'v-click-outside'
import { currency } from '@/lib/filters'
import FlChooseDistrict from '@/components/chees/FlChooseDistrict'
import axios from 'axios'

Vue.use(vClickOutside)
Vue.filter('currency', currency)

export default {
  name: 'IFlatRoomSelection',
  store,

  props: {
    hasSomeRooms: {
      type: Boolean,
      default: true
    },

    actions: {
      default: () => ([
        {
          name: 'Опубликовать',
          type: 'publish'
        },
        {
          name: 'Снять с публикации',
          type: 'unpublish'
        }
      ])
    },

    token: {
      type: String,
      default: ''
    },

    csrfToken: {
      type: String,
      default: ''
    },

    domain: {
      type: String,
      default: process.env.VUE_APP_PROD_URL
    },

    activeRoomInDeal: {
      type: Object,
      default: () => ({})
    },

    openPanelIdDeal: {
      type: Boolean,
      default: true
    },

    isActiveSwitch: {
      type: Number,
      default: 1
    },

    initSelectedRooms: {
      type: Array,
      default: () => ([])
    },

    buttonAddTextPanel: {
      type: String,
      default: 'Добавить в сделку'
    },

    buttonRemoveTextPanel: {
      type: String,
      default: 'Открепить от сделки'
    },

    selectAnyRoom: {
      type: Boolean,
      default: false
    },

    withoutHouse: {
      type: Boolean,
      default: false
    }
  },

  components: {
    FlChooseDistrict,
    FlEmptyResult,
    FlChessRooms,
    FlRoomPanelInfo,
    FlLoadingSecondary,
    FlSwitcherItem,
    FlSwitcher,
    FlRoomsList,
    FlPagination,
    FlFilterRooms
  },
  mixins: [resizeMixin],

  data () {
    return {
      isOpenActiveRoom: false,
      activeRoomId: 0,
      activeSwitch: 1,
      chessPlus: false,
      page: 1
    }
  },

  async created () {
    this.setActive(this.isActiveSwitch)
    this.setDomain()
    if (this.developLogin) {
      await this.$store.dispatch('logInUser')
    } else {
      if (this.token) {
        this.$store.commit('setToken', this.token)
      } else {
        this.$store.commit('setСsrfToken', this.csrfToken)
      }
    }

    this.$store.commit('setOptions', this._props)

    if (!this.hasHouses) {
      this.$store.dispatch('getHousesList')
    }

    !this.activeChess && !Object.keys(this.initFilter).length && await this.getRoomsList()
    this.$root.$on('action', (data) => {
      this.$emit('action', data)
      this.$emit(data.type)
    })
  },

  computed: {
    ...mapState(['isMobile', 'paginationRooms', 'isLoaderSecondary', 'filter', 'devToken']),
    ...mapGetters(['hasHouses', 'hasResults']),

    developLogin () {
      return process.env.NODE_ENV === 'development' && (!this.token || !this.crftToken)
    },

    activeChess () {
      return this.activeSwitch === 2
    },

    filterParameters () {
      const obj = {}
      for (const key in this.filter) {
        if (Object.prototype.hasOwnProperty.call(this.filter, key)) {
          obj[key] = typeof this.filter[key] === 'object' ? this.filter[key].map(item => item.id).join(',') : this.filter[key]
        }
      }
      return obj
    },

    initFilter () {
      return {
        districtId: this.activeRoomInDeal.district_id,
        houseId: this.activeRoomInDeal.house_id
      }
    }
  },

  methods: {
    setDomain () {
      Vue.prototype.$http = axios
      Vue.prototype.$http.defaults.baseURL = this.domain
    },

    setPage (value) {
      this.page = value
      this.getRoomsList(null, this.filterParameters)
    },

    setActiveRoom (id) {
      this.activeRoomId = id
      this.isOpenActiveRoom = true
    },

    setActiveChessPlus () {
      this.chessPlus = true
      this.activeSwitch = 2
    },

    setActive (number) {
      this.activeSwitch = number
      this.chessPlus = false
    },

    searchFilters () {
      this.page = 1
      this.getRoomsList(null, this.filterParameters)
    },

    closePanel () {
      this.isOpenActiveRoom = false
      this.activeRoomId = 0
      this.$emit('close-panel')
    },

    getRoomsList (option, body) {
      this.$store.dispatch('getRoomsList',
        {
          ...option,
          body: {
            ...body,
            page: this.page
          }
        })
        .then(() => {
          if (this.$refs.select) {
            this.$refs.select.scrollTop = 0
          }
        })
    },

    removeRoom () {
      this.closePanel()
      this.$emit('click-remove-deal')
    }
  },

  watch: {
    openPanelIdDeal (value) {
      if (value) {
        this.isOpenActiveRoom = true
        this.activeRoomId = this.activeRoomInDeal.id
      }
    }
  }
}
</script>
<style lang="scss">
@import "scss/configure";

.fl-room-select {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 26px 64px 48px;
  overflow: scroll;

  @include hidden-scrollbar;
}

.fl-room-select-pagination {
  justify-content: center;
  margin-top: 20px;
}

.fl-room-select-filter {
  margin-bottom: 36px;
}

.fl-room-select-container__switcher {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding-bottom: 20px;
  border-bottom: 1px solid $grey-01;
}

.fl-room-select-switcher {
  justify-content: flex-end;
}

.fl-room-select-title {
  font-size: 30px;
  font-family: $main-ff-bold;
}

@include media-max-md {
  .fl-room-select {
    padding-right: 15px;
    padding-left: 15px;
  }

  .fl-room-select-title {
    font-size: 22px;
  }
}
</style>
