<script>
import ButtonModal from '@molecules/ButtonModal/ButtonModal.vue'
import Datepicker from "@molecules/VDatepicker/VDatepicker.vue"
import Tabulator from "@molecules/VTabulator/VTabulator.vue"
import Spinner from "@molecules/VSpinner/VSpinner.vue"
import MachinesModal from "@molecules/MachinesModal/MachinesModal.vue"
import PacksContainer from '@frames/PacksContainer/PacksContainer.vue'
import PacksContainerControl from '@frames/PacksContainer/PacksContainerControl.vue'
import PacksContainerBody from '@frames/PacksContainer/PacksContainerBody.vue'
import tableConfig from './helpers/tableConfig'
import {mapGetters} from 'vuex'
import Input from '@atoms/VInput.vue'
import Button from '@atoms/VButton.vue'
import VueMultiselect from 'vue-multiselect'

export default {
  name: "FreePacks",
  components: {
    Datepicker,
    ButtonModal,
    Tabulator,
    Spinner,
    MachinesModal,
    PacksContainer,
    PacksContainerControl,
    PacksContainerBody,
    Input,
    Button,
    VueMultiselect
  },
  props: {
    serviceOfPacks: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    const paramsFields = {
      dateFormat: 'DD.MM.YYYY',
      dtStart: '',
      dtFinish: new Date(),
      imei: '',
      packNumber: '',
      sortBy: 'pack_dt',
      countEntries: '10',
      sortByOptions: ['pack_dt', 'dt'],
      countEntriesOptions: ['10', '500', '2000', '10000', '50000', '100000']
    }
    return {
      config: tableConfig,
      paramsFields,
      pageState: "await", // await | loading | isLoaded | error
      errorImei: null,
      errorPackNumber: null,
    }
  },
  computed: {
    ...mapGetters('packs', ['freePacks']),
  },
  watch: {
    freePacks: {
      handler (packs) {
        if (packs) {
          this.pageState = "isLoaded"
        }
      }
    }
  },
  methods: {
    editFields (params) {
      const result = this.serviceOfPacks.setPackFields(this.paramsFields, params)
      this.paramsFields = result.paramsFields
      this[result.errorKey] = result.errorValue
    },
    async getPacks () {
      this.pageState = "loading"
      await this.serviceOfPacks.getFreePacks({
        imei: this.paramsFields.imei, 
        packNumber: this.paramsFields.packNumber, 
        dtStart: this.paramsFields.dtStart, 
        dtFinish: this.paramsFields.dtFinish, 
        countEntries: this.paramsFields.countEntries, 
        sortBy: this.paramsFields.sortBy, 
        sortOrder: 'asc', 
        page: 1, 
        format: this.paramsFields.dateFormat
      })
    },
    getCountEntries () {
      if (Number(this.paramsFields.countEntries) > this.freePacks.maxDataLength) return this.freePacks.maxDataLength
      return this.paramsFields.countEntries
    }
  }
}

</script>


<template>
  <PacksContainer>
    <PacksContainerControl>
      <h1 class="font-medium leading-tight text-xl mb-4 text-slate-600">
        Свободный поиск
      </h1>
      <div class="mb-3">
        <label
          for="dtFinish"
          class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"
        >Дата</label>
        <Datepicker
          :defaultDate="paramsFields.dtFinish"
          :enableTime="true"
          dateFormat="d.m.Y"
          :onchange="(e) => editFields({key: 'dtFinish', value: e})"
        />
      </div>
      <div class="grid gap-3 mb-3 ">
        <div class="relative">
          <label
            for="imei"
            class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
          >
            imei
          </label>
          <Input
            id="imei"
            required=""
            class="bg-gray-50 border border-gray-300  text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full !py-0.5 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
            placeholder="imei"
            name="imei"
            type="text"
            autocomplete="off"
            :value="paramsFields.imei"
            :onChange="editFields"
          />
          <div
            v-if="errorImei"
            class="text-red-500 text-xs mt-1"
          >
            {{ errorImei }}
          </div>
        </div>
      </div>
      <div class="grid gap-3 mb-3 ">
        <div class="relative">
          <label
            for="packNumber"
            class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
          >
            Номер пакета
          </label>
          <Input
            id="packNumber"
            required=""
            class="bg-gray-50 border border-gray-300  text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full !py-0.5 pl-2 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500 "
            placeholder="Номер пакета"
            name="packNumber"
            type="text"
            autocomplete="off"
            :value="paramsFields.packNumber"
            :onChange="editFields"
          />
          <div
            v-if="errorPackNumber"
            class="text-red-500 text-xs mt-1"
          >
            {{ errorPackNumber }}
          </div>
        </div>
      </div>
      <div class="grid gap-3 mb-3 ">
        <div class="relative">
          <label
            for="sortBy"
            class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
          >
            Параметр сортировки
          </label>
          <div
            id="packsOptions"
            class="col-span-12 sm:col-span-6 lg:col-span-3 rounded-lg"
          >
            <VueMultiselect
              v-model="paramsFields.sortBy"
              :options="paramsFields.sortByOptions"
              :searchable="false"
              :placeholder="paramsFields.sortBy"
              :showLabels="false"
              @update:model-value="(e) => editFields({key: 'sortBy', value: e})"
            />
          </div>
        </div>
      </div>
      <div class="grid gap-3 mb-3 ">
        <div class="relative">
          <label
            for="countEntries"
            class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
          >
            Число записей
          </label>
          <div
            id="packsOptions"
            class="col-span-12 sm:col-span-6 lg:col-span-3 rounded-lg"
          >
            <VueMultiselect
              v-model="paramsFields.countEntries"
              :options="paramsFields.countEntriesOptions"
              :searchable="false"
              :placeholder="paramsFields.countEntries"
              :showLabels="false"
              @update:model-value="(e) => editFields({key: 'countEntries', value: e})"
            />
          </div>
        </div>
      </div>
      <div class="grid gap-3 grid-cols-4">
        <Button
          type="button"
          class="col-span-4 lg:col-span-4 text-white hover:brightness-90 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-ssm w-full sm:w-auto px-5 py-1 text-center  dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 transition_up"
          :class="{ 'bg-primary cursor-pointer': !errorImei && !errorPackNumber, 'bg-gray-500 cursor-auto': errorImei || errorPackNumber }"
          :disable="errorImei || errorPackNumber"
          title="Выгрузить"
          @click="getPacks"
        />
        <MachinesModal />
        <ButtonModal btnClass="cursor-pointer col-span-4 bg-transparent hover:bg-primary text-primary font-semibold hover:text-white py-1 text-ssm px-4 border border-primary hover:border-transparent rounded-lg text-center transition_up">
          <template #button>
            <div id="question">
              <i class="ri-question-mark" />
            </div>
          </template>
          <div class="overflow-auto min-w-[70vw] h-[70vh] p-4">
            <div style="display: flex; flex-direction: column; gap: 1rem;">
              <span style="font-size: 1.1em; font-weight: bold;">Страница предназначена для получения сведений о последних полученных пакетах от машин<br></span><span style="border-left: 5px solid rgba(0, 0, 0, 0.45); padding: 10px 5px;"><span style="font-weight: bold;">Работа со страницей</span><br><span>Поля выбора находятся на странице. Чтобы загразить данные необходимо -<ol style="font-size: 0.9em; margin-bottom: 0px;"><li>1. ввести пакеты через запятую</li><li>2. ввести imei или выбрать машину/устройство</li><li>3. нажать на кнопку 'загрузить' и дождаться загрузки</li><li style="font-size: 0.9em; color: gray;">(опционально) изменить даты</li></ol></span></span>
            </div>
          </div>
        </ButtonModal>
      </div>
    </PacksContainerControl>
    <PacksContainerBody
      bodyClass="lg:col-span-8 xl:col-span-9 2xl:col-span-10 col-span-12 bg-light shadow"
    >
      <div
        v-if="pageState == 'await'"
        id="report_packs"
        class="tab-pane active relative text-center min-h-[300px] relative rounded-md "
      >
        <span> Выберите машину и нажмите выгрузить</span>
      </div>
      <div
        v-if="pageState === 'loading'"
        id="report_packs"
        class="tab-pane active relative text-center min-h-[300px] relative rounded-md  w-full h-full flex items-center justify-center"
      >
        <Spinner />
      </div>
      <div
        v-if="pageState === 'isLoaded'"
        id="report_packs"
        class="tab-pane active relative text-center min-h-[300px] relative rounded-md "
      >
        <div class="w-full flex justify-end  pr-2 pt-2 pb-1">
          <div>Записей: {{ getCountEntries() }}</div>
        </div>
        <Tabulator 
          :dataSource="freePacks.logs"
          :columns="config.columns"
          :height="config.height"
          layout="fitColumns"
        />
      </div>
    </PacksContainerBody>
  </PacksContainer>
</template>
