<script>
import ButtonModal from '@molecules/ButtonModal/ButtonModal.vue'
import Tabulator from "@molecules/VTabulator/VTabulator.vue"
import Spinner from "@molecules/VSpinner/VSpinner.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 { validatePacks, splitePacks } from './helpers/helpers'

export default {
  name: "LastMachinesByPackNum",
  components: {
    ButtonModal,
    Tabulator,
    Spinner,
    PacksContainer,
    PacksContainerControl,
    PacksContainerBody,
    Input,
    Button
  },
  props: {
    serviceOfMachines: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      packs: '',
      config: tableConfig,
      pageState: "await", // await | loading | isLoaded | error
      errorPacks: null,
    }
  },
  computed: {
    ...mapGetters('machines', ['lastMachinesByPackNumber']),
  },
  watch: {
    lastMachinesByPackNumber: {
      handler (machines) {
        if (machines) {
          this.pageState = "isLoaded"
        }
      }
    }
  },
  methods: {
    editPacks (v) {
      const isError = validatePacks(v)
      if (!isError) {
        this.errorPacks = null
        return this.packs = v
      }
      return this.errorPacks = isError
    },
    async getMachines () {
      this.errorPacks = validatePacks(this.packs)
      if (this.errorPacks) return false
      const arrPacks = splitePacks(this.packs)
      this.pageState = "loading"
      await this.serviceOfMachines.fetchAndSetLastMachinesByPackNum([arrPacks])
    }
  }
}

</script>


<template>
  <PacksContainer>
    <PacksContainerControl>
      <h1 class="font-medium leading-tight text-xl mb-4 text-slate-600">
        Посл. данные(по пакетам)
      </h1>
      <div class="grid gap-3 mb-3 ">
        <div class="relative">
          <label
            for="packs"
            class="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300 text-left "
          >
            Номера пакетов
          </label>
          <Input
            id="selected_pack"
            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-1 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="packs"
            type="text"
            autocomplete="off"
            :value="packs"
            @input="(e) => editPacks(e.target.value)"
          />
          <div
            v-if="errorPacks"
            class="text-red-500 text-xs mt-1"
          >
            {{ errorPacks }}
          </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': !errorPacks, 'bg-gray-500 cursor-auto': errorPacks }"
          :disable="errorPacks"
          title="Выгрузить"
          @click="getMachines"
        />
        <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] pt-10 px-4">
            <div style="display: flex; flex-direction: column; gap: 1rem;">
              <span style="font-size: 1.1em; font-weight: bold;">Страница предназначена для получения сведений о последних полученных пакетах, в результате выдающая список машин, которые имели данный пакет за 3х месячный период (иначе запрос становится слишком долгим)<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. нажать на кнопку 'загрузить' и дождаться загрузки</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 "
      >
        <Tabulator 
          :dataSource="lastMachinesByPackNumber"
          :columns="config.columns"
          :height="config.height"
        />
      </div>
    </PacksContainerBody>
  </PacksContainer>
</template>
