<script>
import {computed} from 'vue'
import {mapGetters, mapMutations, mapActions, useStore} from "vuex"
import {useRoute} from 'vue-router'
import Button from "@atoms/VButton.vue"
import VueMultiselect from 'vue-multiselect'
import Filters from "./Filters.vue"
import Machine from "./Machine.vue"
import Charts from "./Charts.vue"
import HistoryViews from "./HistoryViews.vue"
import Table from "./Table.vue"
import MapModal from '@molecules/MapModal/MapModal.vue'
import DataModal from "./DataModal/DataModal.vue"
import Spinner from "@molecules/VSpinner/VSpinner.vue"
import {PushAfterTimeout} from '@store/hooks/PushAfterTimeout'
import {EventStore} from '@store/hooks/EventStore'

export default {
  name: 'MachinesComponent',
  components: {
    Button,
    Filters,
    VueMultiselect,
    Machine,
    Table,
    Charts,
    HistoryViews,
    MapModal,
    DataModal,
    Spinner
  },
  props: {
    status: {
      type: String,
      default: 'static',
    },
  },
  setup () {
    const initLocalStorage = new EventStore()
    const store = useStore()
    const route = useRoute()
    const path = computed(() => route.path)
    const query = computed(() => route.query)

    const historyData = initLocalStorage.localStoreGetData({key: 'historyViews', onlyGet: true})
    const isHistoryData = historyData && historyData.length > 0
    const updatedData = isHistoryData ? historyData.filter((el, idx, arr) => arr.findIndex((item) => item.machine_id === el.machine_id) === idx).slice(0, 20) : []
    
    const urlParams = path.value === '/' && query?.value?.mode ? query.value.mode : ''
    const externalParams = {historyData: updatedData, urlParams: urlParams}

    store.commit('layout_machines/setHistoryData', updatedData)
    store.dispatch('layout_machines/uploadData', externalParams)
  },
  data () {
    return {
      openMap: false,
      openData: false,
    }
  },
  computed: {
    ...mapGetters('layout_machines', ['searchModes', 'searchValue', 'selectedSearchMode', 'leftTopButtons', 'rightTopButtons', 'selectedMode', 'toggleFilter', 'activeFilterBtn', 'mapData', 'machinesData']),
    ...mapGetters('layout', ['isOpenMenu']),
  },
  watch: {
    isSuccessSearch: {
      handler(newValue, oldValue)  {
        console.log('isSuccessSearch', newValue, oldValue)
      },
      deep: true
    },
  },
  mounted () {

  },
  updated () {
    this.$nextTick(function () {
      const path = this.$route.path
      const query = this.$route.query
      if (path === '/' && query?.mode) {
        this.setSelectedMode(query?.mode)
      }
      if (path === '/' && !query?.mode) {
        this.setSelectedMode('cards')
      }
    })
  },
  unmounted() {
    const store = useStore();
    store.dispatch('layout_machines/resetStore')
  },
  methods: {
    ...mapMutations('layout_machines', ['setSearchMode', 'setSelectedMode', 'setToggleFilter', 'setActiveFilterBtn']),
    ...mapActions('layout_machines', ['updateSearch', 'clearFilters']),
    updateSearchMode: function(selectedSearchMode) {
      this.setSearchMode(selectedSearchMode)
    },
    updateSearchValue: function(e) {
      const searchInput = new PushAfterTimeout('searchInput', 1500)
      if (searchInput.input) {
        setTimeout(() => {
          this.updateSearch(e.target.value)
        }, 1500)

      }
    },
    setFilteredAction (filteredAction) {
      this.setActiveFilterBtn(filteredAction)
      if (filteredAction === 'filter') {
        this.setToggleFilter()
      }
      if (filteredAction ==='clearFilter') {
        this.clearFilters()
      }
    },
    updateMode: function(mode) {
      if (mode) {
        const path = this.$route.path
        const params = mode === 'charts' ? {mode: mode, type: 'main'} : {mode: mode}
        this.$router.push({ path: path, query: params })
        return this.setSelectedMode(mode)
      }
    },
    toggleMap () {
      this.openMap = !this.openMap
    },
    toggleData () {
      this.openData = !this.openData
    },
    closeMap () {
      return this.openMap = !this.openMap
    },
    closeData () {
      return this.openData = !this.openData
    }
  }
}

</script>


<template>
  <div class="px-2 sm:px-5 pt-1 bg-light">
    <div class="relative">
      <div class="grid grid-cols-12 gap-4 md:gap-3 lg:gap-4 pb-3">
        <div class="flex items-center col-span-12 sm:col-span-8 lg:col-span-5 xl:col-span-4 2xl:col-span-3">
          <div
            id="search"
            class="relative w-full max-w-[150px] h-[31px] pl-1 py-1 bg-white border border-primary rounded-l-md z-30"
          >
            <VueMultiselect
              v-model="selectedSearchMode"
              label="name"
              :options="searchModes"
              :searchable="false"
              placeholder=""
              :showLabels="false"
              @update:model-value="updateSearchMode"
            />
          </div>
          <div
            id="searchInput"
            class="relative w-full border-r border-t border-b border-primary rounded-r-md"
          >
            <input
              :value="searchValue"
              :status="status"
              class="pl-1 py-1 rounded-r-md w-full max-h-[29px] border-none focus-visible:outline-blue-300"
              @change="updateSearchValue"
            >
          </div>
        </div>
        <!-- {{ console.log('machinesData', machinesData) }} -->
        <ul
          id="machinesMode"
          class="flex col-span-6 sm:col-span-4 md:col-span-4 lg:col-span-3 xl:col-span-2 justify-center"
        >
          <li
            v-for="(mode, idx) in leftTopButtons"
            :key="idx"
          >
            <Button
              :onClick="updateMode"
              :selected="mode.key"
              :classIcon="mode.class"
              :classBtn="[mode.key === 'cards' ? 'rounded-r-none' : 'rounded-l-none', selectedMode === mode.key ? 'text-white bg-primary focus:ring-4 focus:outline-none focus:ring-blue-300' : 'bg-transparent', 'w-full min-w-[88px] h-[30px] border border-primary rounded-md']"
            />
          </li>
        </ul>
        <div
          id="historyMode"
          class="flex col-span-6 sm:col-span-4 md:col-span-4 lg:col-span-3 xl:col-span-2 justify-center"
        >
          <Button
            :onClick="updateMode"
            selected="history"
            title="Просмотры"
            :classBtn="[selectedMode === 'history' ? 'focus:ring-4 focus:outline-none focus:ring-blue-300' : '', 'w-full min-w-[88px] h-[30px] bg-primary text-white border border-primary rounded-md']"
          />
        </div>
        <div
          id="chartsMode"
          class="flex col-span-6 sm:col-span-4 md:col-span-4 lg:col-span-3 xl:col-span-2 justify-center"
        >
          <Button
            :onClick="updateMode"
            selected="charts"
            classIcon="ri-pie-chart-2-line"
            :classBtn="[selectedMode === 'charts' ? 'focus:ring-4 focus:outline-none focus:ring-blue-300' : '', 'w-full min-w-[88px] h-[30px] bg-primary text-white border border-primary rounded-md']"
          />
        </div>
        <ul
          id="filtersButtons"
          class="flex col-span-6 sm:col-span-4 md:col-span-4 lg:col-span-3 xl:col-span-2 justify-center"
        >
          <li
            v-for="(mode, idx) in rightTopButtons"
            :key="idx"
          >
            <Button
              :onClick="setFilteredAction"
              :selected="mode.key"
              :title="mode.name"
              :classIcon="mode.iconClass"
              :classBtn="[activeFilterBtn === mode.key ? 'focus:ring-4 focus:outline-none focus:ring-blue-300' : '', mode.key === 'filter' ? 'rounded-r-none' : 'rounded-l-none', mode.classBtn, 'w-full min-w-[88px] h-[30px] border border-primary rounded-md']"
            />
          </li>
        </ul>
      </div>
      <div
        v-if="toggleFilter"
        id="filters"
      >
        <Filters />
      </div>
      <div class="border-2 rounded-lg w-full bottom-0" />
      <div
        v-if="selectedMode === 'cards'"
        id="listMachines"
        class="w-full min-h-[80vh] p-4 bg-light dark:bg-slate-900 dark:text-slate-300 relative"
      >
        <ul
          v-if="selectedMode === 'cards'"
          class="flex flex-wrap gap-4 w-full justify-center align-center"
        >
          <!-- <li v-for="machine in machinesData" class="w-full sm:w-1/2 md:w-1/2 lg:w-1/2 xl:w-1/2 p-2 border-2 border-primary rounded-md"> -->
          <li
            v-for="(machine, idx) in machinesData"
            :key="idx"
            class=""
          >
            <Machine
              :machine="machine"
              :openMap="toggleMap"
              :openData="toggleData"
            />
          </li>
        </ul>
      </div>
      <div
        v-if="selectedMode === 'table'"
        id="tableMachines"
        class="tab-pane bg-light relative py-4 text-center min-h-[300px] relative rounded-md w-full"
      >
        <Table />
      </div>
      <div
        v-if="selectedMode === 'history'"
        id="historyViews"
        class="tab-pane bg-light relative shadow  text-center min-h-[300px] relative w-full p-4"
      >
        <HistoryViews />
      </div>
      <div
        v-if="selectedMode === 'charts'"
        id="charts"
        class="w-full min-h-[80vh] pb-5 bg-light dark:bg-slate-900 dark:text-slate-300 relative"
      >
        <!-- <.loader :if={@display_config.is_loading_charts} /> -->
        <div>
          <Charts />
        </div>
      </div>
      <!-- <div id="no_data" :if={@display_config.no_data && @display_config.machines_display_mode != "history_views"} class="w-full min-h-[80vh] bg-light dark:bg-slate-900 dark:text-slate-300 relative">
        <.loader :if={@list == [] && !@display_config.no_data || @display_config.is_loading_list} />
        <div class="flex items-center justify-center text-lg font-bold pt-5">Нет данных</div>
      </div> -->
      <MapModal
        id="mapModal"
        :open="openMap"
        :close="closeMap"
        :data="mapData"
        headerClass="border-b p-4 font-bold"
      >
        <template #header>
          <div id="headerTitle">
            Карта
          </div>
        </template>
        <div
          v-if="!mapData"
          id="map_loader"
          class="flex justify-center"
          style="width: 95vw; height: 82vh;"
        >
          <Spinner />
        </div>
        <div
          v-if="mapData"
          id="mapModal"
          style="width: 95vw; height: 82vh;"
        />
        <div
          id="popup"
          class="ol-popup hidden transition-all"
        >
          <a
            id="popup-closer"
            href="#"
            class="ol-popup-closer hover:no-underline top-2 right-2 "
          >
            <i class="ri-close-fill" />
          </a>
          <div id="popup-content" />
        </div>
      </MapModal>
      <DataModal
        id="dataModal"
        :open="openData"
        :close="closeData"
      />
    </div>
  </div>
</template>

<style scoped>
</style>
