<template>
  <div
    v-if="(inactiveStatusSchedule.length && !statusSchedule) || (activeStatusSchedule.length && statusSchedule)"
    class="flex-column flex-content-center"
  >
    <!-- SEARCH SCHEDULED -->
    <div class="full-width">
      <base-search-order
        @callbacksearch="(value, bool1, bool2) => searchScheduled(value, bool1, bool2)"
        v-model="orderId"
        class="search-scheduled"
        :width="true"
        :padding="true"
        :place-holder="'Pesquise aqui seu agendamento pelo número do pedido...'"
        :type="true"
      >
      </base-search-order>
    </div>
    <!-- MODAL SEARCH-->
    <base-modal v-if="showModalSearch" title="Informações do agendamento:" size="medium" @close="closeSearchModal()">
      <div class="flex-content-center modalSuccess top-margin-medium">
        <div v-if="loaderSearch" style="position: absolute;">
          <i class="fa-solid fa-circle-notch spinner"></i>
        </div>
        <div v-else class="full-width horizontal-padding-medium">
          <div v-if="foundSchedule">
            <div class="flex between-xs padding-x-small" v-for="(value, label) in foundScheduleDetails" :key="label">
              <span class="text-small" v-text="label + ': '"></span>
              <span class="text-small text-bold text-break" v-text="value"></span>
            </div>
          </div>
          <div v-else class="flex-content-center">
            <span>Agendamento não encontrado!</span>
          </div>
        </div>
      </div>
    </base-modal>

    <div v-if="!loader" id="content-scheduled" :class="!loader && lengthTable ? 'borderSelected' : ''">
      <!-- MODAL TABLE-->
      <base-modal v-if="showModal" title="Informações do dia e horário escolhido:" size="large" @close="clearModal()">
        <div
          :class="modalSuccess ? 'modal-success' : ''"
          class="base-modal text-center flex flex-column content-center items-center"
        >
          <template v-if="!modalSuccess">
            <!-- INFOS SCHEDULE -->
            <div class="full-width flex bottom-margin-large">
              <!-- INFO BLOCK SCHEDULE -->
              <div v-if="scheduleItem.value === 'bloqueado' || scheduleItem.observation" class="flex information-schedule blockSchedule" :style="scheduleItem.observation ? 'background: #e1aa41;' : ''">
                <div class="flex between-xs padding-x-small">
                  <span v-if="scheduleItem.observation" class="text-small text-info">Bloqueado por venda externa: </span>
                  <span v-else class="text-small text-info">Dia e horário bloqueado: </span>
                  <span
                    class="text-small text-info text-bold"
                    v-text="dateFormat(scheduleItem.date) + ' - ' + scheduleItem.time"
                  ></span>
                </div>
                <div v-if="scheduleItem.observation" class="flex padding-x-small top-margin-small">
                  <span v-text="scheduleItem.observation" class="text-small text-info text-dark-opacity text-observation"></span>
                </div>
              </div>
              <!-- INFO FREE SCHEDULE -->
              <div v-else-if="scheduleItem.value === ''" class="flex information-schedule freeSchedule-info">
                <div class="flex between-xs padding-x-small">
                  <span class="text-small text-info">Dia e horário disponível: </span>
                  <span
                    class="text-small text-info text-bold"
                    v-text="dateFormat(scheduleItem.date) + ' - ' + scheduleItem.time"
                  ></span>
                </div>
              </div>
              <!-- INFO TO SCHEDULE -->
              <div v-else class="flex information-schedule toSchedule">
                <div v-if="loading">
                  <i class="fa-solid fa-circle-notch spinner-black"></i>
                </div>
                <div v-else>
                  <div
                    v-for="(item, label) in orderDetailsToSchedule"
                    :key="label"
                    class="flex between-xs padding-x-small"
                  >
                    <span class="text-small text-info" v-text="label + ': '"></span>
                    <a
                      v-if="label === 'Link do pedido'"
                      :href="item"
                      target="_blank"
                      class="text-small text-link text-info text-bold text-break"
                      v-text="'Pedido'"
                    ></a>
                    <span v-else class="text-small text-info text-bold text-break" v-text="item"></span>
                  </div>
                </div>
              </div>
            </div>
            <!-- BUTTONS CHOICE -->
            <div class="full-width flex flex-column content-center between-xs top-margin-large">
              <div class="flex bottom-margin-medium">
                <span class="text-dark text-bold text-ellipsis text-medium"
                  >Escolha a opção desejada abaixo para alterar a tabela.</span
                >
              </div>
              <div class="buttons-modal flex between-xs">
                <base-button
                  apperance="success"
                  square
                  size="medium"
                  @click.native="addScheduleChoice"
                  class="btn-modal-schedule"
                  :disabled="!canSchedule"
                >
                  Agendar
                </base-button>

                <base-button
                  apperance="error"
                  square
                  size="medium"
                  @click.native="blockScheduleChoice"
                  class="btn-modal-schedule"
                  :disabled="!canBlock"
                >
                  Bloquear
                </base-button>

                <base-button
                  apperance="neutral-white"
                  square
                  size="medium"
                  @click.native="freeScheduleChoice"
                  class="btn-modal-schedule"
                  :disabled="!canFree"
                >
                  Deixar livre
                </base-button>
              </div>
            </div>
            <!-- ADD TO SCHEDULE -->
            <div v-if="addSchedule" class="full-width">
              <base-search-order
                @callbacksearch="(value, bool1, bool2) => searchOrder(value, bool1, bool2)"
                v-model="orderId"
                class="search"
                :width="true"
                @change="value => changeSearch(value)"
              >
              </base-search-order>
              <div
                class="dark result-btn-choice flex"
                @click="toggleSelection"
                :style="{ cursor: hasSchedule || hasNoOrder ? 'default' : 'pointer' }"
                :class="buttonClasses"
              >
                <div v-if="shouldShowOrderDetails" class="result-search">
                  <div v-if="loading">
                    <i class="fa-solid fa-circle-notch spinner"></i>
                  </div>
                  <div v-else>
                    <div v-if="!hasNoOrder">
                      <div
                        v-for="(value, label) in orderDetails"
                        :key="label"
                        class="flex between-xs vertical-padding-x-small"
                      >
                        <span class="text-small text-dark" v-text="label + ': '"></span>
                        <span class="text-small text-dark text-break" v-text="value"></span>
                      </div>
                    </div>
                    <div v-else>
                      <span v-text="'O pedido informado não existe!'" class="text-small text-dark"></span>
                    </div>
                  </div>
                </div>
                <div v-else-if="hasSchedule">
                  <span
                    v-text="'Pedido #' + hasSchedule + ' já possui agendamento!'"
                    class="text-small text-dark"
                  ></span>
                </div>
              </div>
            </div>
            <!-- EMPTY TO SCHEDULE -->
            <div
              v-if="shouldShowFreeScheduleBlock"
              class="dark result-btn-choice flex padding-medium top-margin-large content-center cursor-default noHover"
              :class="{ showDeleteOrder: freeSchedule, offDeleteOrder: !freeSchedule, flexCenter: freeSchedule }"
            >
              <div class="flex between-xs">
                <span class="text-small text-dark text-justify"
                  >Ao clicar em confirmar, o pedido será desvinculado da data e horário no qual o mesmo se encontra
                  agendado. Sendo assim, o horário e a data na qual o pedido se encontra ficará disponível novamente
                  para ser agendado.</span
                >
              </div>
            </div>
            <div v-else-if="freeSchedule">
              <div class="flex between-xs top-margin-large">
                <base-radio
                  name="free-hour"
                  :label="'Desbloquear o horário.'"
                  v-model="hourOrDay"
                  required
                  value="hour"
                  value-checked="hour"
                  inline
                ></base-radio>

                <base-radio
                  name="free-day"
                  :label="'Desbloquear o dia inteiro.'"
                  v-model="hourOrDay"
                  required
                  value="day"
                  value-checked="day"
                  inline
                  :disabled="hasHour"
                >
                </base-radio>

                <base-info v-if="hasHour" right="314px" style="margin-top: 13px;">
                  <span class="flex" style="width: 280px;"
                    >Opção indisponível, pois possui algum tipo de agendamento marcado em algum dos horários do dia.</span
                  >
                </base-info>
              </div>
            </div>
            <!-- SCHEDULE BLOCK-->
            <div v-if="blockSchedule">
              <div class="flex between-xs top-margin-large">
                <base-radio
                  name="block-hour"
                  :label="'Bloquear apenas o horário.'"
                  v-model="hourOrDay"
                  required
                  value="hour"
                  value-checked="hour"
                  inline
                ></base-radio>

                <base-radio
                  name="block-day"
                  :label="'Bloquear o dia inteiro.'"
                  v-model="hourOrDay"
                  required
                  value="day"
                  value-checked="day"
                  inline
                  :disabled="hasHour"
                >
                </base-radio>

                <base-radio
                  name="block-out-sale"
                  :label="'Bloquear para venda externa.'"
                  v-model="hourOrDay"
                  required
                  value="sale"
                  value-checked="sale"
                  inline
                >
                </base-radio>

                <textarea v-if="hourOrDay === 'sale'" class="observation-schedule" 
                  maxlength="220" 
                  autocapitalize="sentences" 
                  autofocus="true"           
                  placeholder="Digite as informações sobre a venda externa..."
                  required
                  v-model="outSale"
                >
                </textarea>

                <base-info v-if="hasHour" right="283px" style="margin-top: 13px;">
                  <span class="flex" style="width: 280px;"
                    >Opção indisponível, pois já possui algum tipo de agendamento marcado em algum dos horários disponíveis do
                    dia.</span
                  >
                </base-info>
              </div>
            </div>
            <!-- BUTTONS ACTION -->
            <div class="btn-action-schedule top-margin-large flex gap-2 center-xs">
              <base-button
                apperance="success"
                square
                size="medium"
                @click.native="confirmToSchedule(customerOrder)"
                :disabled="!selected"
              >
                Confirmar
              </base-button>
              <base-button apperance="error" square size="medium" @click.native="clearModal" :disabled="modalSuccess">
                Cancelar
              </base-button>
            </div>
          </template>

          <template v-else>
            <div class="dark modalSuccess flex padding-medium top-margin-large content-center">
              <span v-if="successMessage" class="text-small text-dark text-justify" v-text="successMessage"></span>
            </div>
          </template>
        </div>
      </base-modal>
      <!-- TABLE -->
      <table
        id="table"
        :class="!loader && !lengthTable ? 'borderSelected' : ''"
        :schedule-id="scheduleId"
        @callback="isLoad"
      >
        <thead>
          <tr>
            <th class="hours text-medium text-dark-opacity border-bottom-none">
              Horário
            </th>
            <th
              v-for="(day, index) in parcialDays"
              class="textFormat text-medium text-dark-opacity"
              :class="day.status === '0' ? 'expireDate' : ''"
              :key="index"
              v-text="day.dayName"
            ></th>
          </tr>
          <tr class="borderDays">
            <th class="hours clock">
              <i v-if="statusSchedule" class="fa-regular fa-clock clockIcon"></i>
              <i v-else class="fa-solid fa-lock clockIcon" title="Agendas inativas não podem ser editadas"></i>
            </th>
            <th
              v-for="(numberDay, index) in parcialDays"
              :key="index"
              :class="numberDay.status === '0' ? 'expireDate' : ''"
            >
              <span class="numberFormat" v-text="numberDay.dayNumber"></span>
            </th>
          </tr>
          <!-- PAGINATION -->
          <div class="pagination" :class="!lengthTable ? 'full-width' : ''">
            <button
              @click="toPagination('back')"
              type="button"
              :disabled="!initialIndex || !lengthTable"
              :class="!initialIndex || !lengthTable ? 'disable-pagination' : ''"
            >
              <i class="fa-solid fa-circle-arrow-left arrow-icon"></i>
            </button>

            <div class="month-name">
              <span v-text="monthName" class="text-date text-large text-bold"></span>
              <span v-text="yearName" class="text-date text-x-small text-bold"></span>
            </div>

            <button
              @click="toPagination('next')"
              type="button"
              :disabled="isEnd || !lengthTable"
              :class="isEnd || !lengthTable ? 'disable-pagination' : ''"
            >
              <i class="fa-solid fa-circle-arrow-right arrow-icon"></i>
            </button>
          </div>
        </thead>

        <tbody>
          <tr v-for="(time, timeIndex) in times" :key="timeIndex">
            <div class="hours text-medium text-dark-opacity">
              {{ time.dividTime }}
            </div>
            <td v-for="(day, dayIndex) in parcialDays" :key="dayIndex">
              <div
                class="select"
                :id="getId(schedule[timeIndex][dayIndex].value)"
                :style="
                  isUnavailable(schedule[timeIndex][dayIndex].value) || !statusSchedule ? 'pointer-events: none' : ''
                "
                :class="cellClasses(timeIndex, dayIndex, day)"
                @click="toSchedule(schedule[timeIndex][dayIndex].value, timeIndex, dayIndex)"
              >
                <div
                  v-if="hasValue(schedule[timeIndex][dayIndex].value)"
                  class="flex flex-column between-xs items-center"
                >
                  <span class="text-small text-dark-opacity">Pedido: </span>
                  <span class="text-small text-dark-opacity" v-text="'#' + schedule[timeIndex][dayIndex].value"></span>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <!-- LOADER -->
    <div v-if="loader" class="btn-loader">
      <i class="fa-solid fa-circle-notch spinner"></i>
    </div>
  </div>
  <div v-else class="flex-content-center full-height">
    <span class="inactive shadow-medium">Não possui agenda cadastrada no momento!</span>
  </div>
</template>

<script>
import axiosApi, { param } from '@assets/js/axios-api';
const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;
const token = document.body.getAttribute('data-token');

export default {
  name: 'ScheduleTable',
  components: {
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
    BaseRadio: () => import(/* webpackChunkName: "BaseRadio" */ '@elements/BaseRadio/index.vue'),
    BaseInfo: () => import(/* webpackChunkName: "BaseInfo" */ '@elements/BaseInfo/index.vue'),
    BaseSearchOrder: () => import(/* webpackChunkName: "BaseSearchOrder" */ '@elements/BaseSearchOrder/index.vue'),
  },
  props: {
    scheduleId: {
      type: String,
    },
    status: {
      type: Number,
    },
    inactiveStatusSchedule: {
      type: Array,
    },
    activeStatusSchedule: {
      type: Array,
    },
  },
  data() {
    return {
      days: [],
      times: [],
      schedule: [],
      allDay: [],
      parcialDays: [],
      initialIndex: 0,
      loader: true,
      statusSchedule: true,
      loaderSearch: true,
      isEnd: false,
      showModal: false,
      isSearchorder: false,
      customerOrder: false,
      selected: false,
      addSchedule: false,
      blockSchedule: false,
      freeSchedule: false,
      modalSuccess: false,
      unlinkedOrder: false,
      hourOrDay: false,
      hasHour: false,
      hasSchedule: false,
      loading: false,
      modalTimeOut: false,
      foundSchedule: false,
      lengthTable: false,
      scheduleTimeLoaded: false,
      inactive: false,
      showModalSearch: false,
      rest: false,
      hasNoOrder: false,
      orderId: '',
      timeIndexValue: '',
      dayIndexValue: '',
      date: '',
      time: '',
      monthName: '',
      yearName: '',
      outSale: null,
    };
  },
  computed: {
    cellClasses() {
      return (timeIndex, dayIndex, day) => {
        const value = this.schedule[timeIndex][dayIndex].value;
        const observation = this.schedule[timeIndex][dayIndex].observation;
        return {
          block: this.isBlockedOrUnavailable(value) && !observation,
          outSale: observation,
          scheduled: this.hasValue(value),
          unavailable: this.isUnavailable(value),
          freeSchedule: !value,
          expireDate: day.status === '0' && value === 'indisponivel',
        };
      };
    },
    scheduleItem() {
      return this.schedule[this.timeIndexValue][this.dayIndexValue];
    },
    orderDetailsToSchedule() {
      const { order_id, firstname, lastname, email, date_added_formatted, url_order, telephone } = this.customerOrder;
      return {
        Pedido: '#' + order_id,
        Nome: firstname + ' ' + lastname,
        Email: email,
        Telefone: telephone ? telephone : 'Telefone não cadastrado',
        'Data do pedido': date_added_formatted,
        'Link do pedido': url_order,
      };
    },
    canSchedule() {
      return (
        !(this.customerOrder && this.schedule[this.timeIndexValue][this.dayIndexValue].value !== '') &&
        !(this.schedule[this.timeIndexValue][this.dayIndexValue].value === 'bloqueado')
      );
    },
    canBlock() {
      return (
        !(this.schedule[this.timeIndexValue][this.dayIndexValue].value !== '') &&
        !(this.schedule[this.timeIndexValue][this.dayIndexValue].value === 'bloqueado')
      );
    },
    canFree() {
      return !(this.schedule[this.timeIndexValue][this.dayIndexValue].value === '');
    },
    buttonClasses() {
      return {
        borderSelected: this.selected && !this.hasNoOrder,
        showDeleteOrder: this.isSearchorder,
        offDeleteOrder: !this.isSearchorder,
        noHover: this.hasNoOrder || this.hasSchedule,
      };
    },
    shouldShowOrderDetails() {
      return this.isSearchorder && !this.hasSchedule;
    },
    orderDetails() {
      return {
        Pedido: '#' + this.customerOrder.order_id,
        Nome: this.customerOrder.firstname + ' ' + this.customerOrder.lastname,
        Email: this.customerOrder.email,
        'Data do pedido': this.customerOrder.date_added_formatted,
      };
    },
    shouldShowFreeScheduleBlock() {
      const value = this.schedule[this.timeIndexValue][this.dayIndexValue].value;
      return value !== '' && value !== 'bloqueado';
    },
    successMessage() {
      if (this.unlinkedOrder) {
        return 'Pedido #' + this.unlinkedOrder + ' desvinculado com sucesso!';
      } else if (this.customerOrder) {
        return 'Pedido #' + this.customerOrder.order_id + ' vinculado com sucesso!';
      } else if (this.blockSchedule) {
        return this.hourOrDay === 'hour'
          ? 'Horário: ' + this.time + ' bloqueado com sucesso!'
          : 'Dia: ' + this.date + ' bloqueado com sucesso!';
      } else if (this.freeSchedule && this.hourOrDay) {
        return this.hourOrDay === 'hour'
          ? 'Horário: ' + this.time + ' desbloqueado com sucesso!'
          : 'Dia: ' + this.date + ' desbloqueado com sucesso!';
      } else {
        return '';
      }
    },
    foundScheduleDetails() {
      if (!this.foundSchedule) return {};

      return {
        'Número do pedido': '#' + this.foundSchedule.order_id,
        'Nome da agenda': this.foundSchedule.name,
        'Tipo do agendamento': this.foundSchedule.type,
        'Data do agendamento': this.dateFormat(this.foundSchedule.date),
        'Horário do agendamento': this.foundSchedule.time,
      };
    },
  },
  watch: {
    scheduleId(scheduleId) {
      if (scheduleId && scheduleId !== 'inativo') {
        this.loader = true;
        this.initialIndex = 0;
        this.isEnd = false;
        this.getScheduleTime(scheduleId, null);
        const idSearch = document.getElementById('header__search-field-id');
        if (idSearch) idSearch.value = '';
      } else {
        this.inactive = true;
      }
    },
    hourOrDay(value) {
      if (value && value !== 'sale') this.selected = true;
      else this.selected = false;
    },
    blockSchedule(value) {
      if (value) this.findScheduled();
    },
    freeSchedule(value) {
      if (this.schedule[this.timeIndexValue][this.dayIndexValue].value === 'bloqueado') this.selected = false;
      if (value) this.findScheduled();
    },
    status(value) {
      this.statusSchedule = value;
    },
    outSale(value){
      if (value) this.selected = true;
      else this.selected = false;
    }
  },
  methods: {
    //EMIT
    isLoad() {
      this.$emit('callback', 'true');
    },
    isUnload() {
      this.$emit('callback-unload', 'true');
    },
    //TOGGLE BOOELAN VALUES
    changeSearch(value) {
      if (!value) this.isSearchorder = false;
    },
    clearModal() {
      this.showModal = false;
      this.isSearchorder = false;
      this.customerOrder = false;
      this.selected = false;
      this.addSchedule = false;
      this.blockSchedule = false;
      this.freeSchedule = false;
      this.modalSuccess = false;
      this.unlinkedOrder = false;
      this.hasSchedule = false;
      this.hasHour = false;
      this.hourOrDay = false;
      this.loading = false;
      this.outSale = '';
      this.allDay = [];
      clearTimeout(this.modalTimeOut);
    },
    addScheduleChoice() {
      this.addSchedule = !this.addSchedule;
      this.blockSchedule = false;
      this.freeSchedule = false;
      this.isSearchorder = false;
      this.customerOrder = false;
      this.hasHour = false;
      this.hourOrDay = false;
      this.outSale = '';
    },
    blockScheduleChoice() {
      this.blockSchedule = !this.blockSchedule;
      this.addSchedule = false;
      this.freeSchedule = false;
      this.selected = false;
      this.hasSchedule = false;
      this.isSearchorder = false;
      this.hasHour = false;
      this.hourOrDay = false;
      this.customerOrder = false;
      this.outSale = '';
    },
    freeScheduleChoice() {
      this.freeSchedule = !this.freeSchedule;
      this.addSchedule = false;
      this.blockSchedule = false;
      this.selected = !this.selected;
      this.hasHour = false;
      this.hourOrDay = false;
      this.outSale = '';
    },
    closeSearchModal() {
      this.showModalSearch = !this.showModalSearch;
      this.loaderSearch = true;
      this.foundSchedule = false;
    },
    toggleSelection() {
      if (!this.hasSchedule && !this.hasNoOrder) {
        this.selected = !this.selected;
      }
    },
    //TABLE RENDER
    isBlockedOrUnavailable(value) {
      return value === 'bloqueado' || value === 'indisponivel';
    },
    getId(value) {
      return this.isBlockedOrUnavailable(value) || value === '' ? 'schedule' : value;
    },
    isUnavailable(value) {
      return value === 'indisponivel';
    },
    hasValue(value) {
      return value && !this.isBlockedOrUnavailable(value);
    },
    //FUNCTIONS DEFAULT
    findScheduled() {
      for (var x = 0; x < this.times.length; x++) {
        var scheduleValue = this.schedule[x][this.dayIndexValue].value;
        var scheduleOutSale = this.schedule[x][this.dayIndexValue].observation;
        if ((scheduleValue && scheduleValue !== 'bloqueado') || (scheduleOutSale && scheduleValue === 'bloqueado' )) {
          this.hasHour = true;
          this.allDay = [];
          return;
        } else {
          this.allDay.push(this.schedule[x][this.dayIndexValue].schedule_times_id);
        }
      }
    },
    callToModalSuccess() {
      this.modalSuccess = true;
      this.modalTimeOut = setTimeout(() => {
        this.clearModal();
      }, 3000);
    },
    dateFormat(dateString) {
      if (dateString.includes('/')) {
        return dateString;
      } else {
        const [year, month, day] = dateString.split('-');
        return `${day}/${month}/${year}`;
      }
    },
    toSchedule(value, timeIndex, dayIndex) {
      this.showModal = !this.showModal;
      this.timeIndexValue = timeIndex;
      this.dayIndexValue = dayIndex;

      if (value && value !== 'bloqueado') this.getOrder(value, true, false);
    },
    searchOrder(value, bool1, bool2) {
      this.selected = false;
      this.hasSchedule = false;
      this.isSearchorder = false;
      if (bool2) {
        this.customerOrder = false;
        this.isSearchorder = false;
        this.hasSchedule = false;
        if (this.selected) this.selected = !this.selected;
        return;
      }
      if (value) this.getScheduled(value);
    },
    confirmToSchedule(customerOrder) {
      const schedule_times_id = this.schedule[this.timeIndexValue][this.dayIndexValue].schedule_times_id;
      this.schedule[this.timeIndexValue][this.dayIndexValue].observation = this.outSale;

      if (customerOrder) {
        if (!this.freeSchedule) {
          this.postOrder(customerOrder.order_id, schedule_times_id);
        } else {
          this.updateOrder(customerOrder.order_id);
        }
      } else if (this.freeSchedule) {
        let flag = 0;
        this.updateScheduleBlock(this.hourOrDay === 'hour' ? [schedule_times_id] : this.allDay, flag, this.outSale);
      } else if (this.hourOrDay && this.blockSchedule) {
        let flag = 1;
        this.updateScheduleBlock(this.hourOrDay === 'hour' || this.hourOrDay === 'sale' ? [schedule_times_id] : this.allDay, flag, this.outSale);
      }
    },
    searchScheduled(value, bool1, bool2) {
      if (bool2) return;
      this.showModalSearch = true;
      this.getScheduled(value);
    },
    toPagination(value) {
      this.getScheduleTime(this.scheduleId, value);
    },
    //REQUISITIONS
    async getOrder(orderId, bool1, bool2) {
      this.loading = !this.loading;
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getScheduleOrder&token=' + token,
        data: param({ id: orderId }),
      })
        .then(({ data }) => {
          this.resGetOrder(data);
        })
        .catch(err => console.log(err, err.response));
    },
    async getScheduled(orderId) {
      this.loading = true;
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getScheduled&token=' + token,
        data: param({ id: orderId }),
      })
        .then(({ data }) => {
          if (data) {
            this.resScheduled(orderId, data);
          } else {
            this.getOrder(orderId, true, false);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    async getScheduleTime(scheduleId, value) {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getScheduleTime&token=' + token,
        data: param({ id: scheduleId, increment: value, index: this.initialIndex, restValue: this.rest }),
      })
        .then(({ data }) => {
          if (data) {
            this.resGetscheduleTime(data);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    async updateOrder(orderId) {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/updateOrder&token=' + token,
        data: param({ id: orderId }),
      })
        .then(({ data }) => {
          if (data) {
            this.resUpdateOrder(orderId);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    async updateScheduleBlock(schedule_times_id, flag, obs) {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/updateScheduleBlock&token=' + token,
        data: param({ id: schedule_times_id, flag: flag, observation: obs }),
      })
        .then(({ data }) => {
          if (data) {
            this.resUpdateScheduleBlock(schedule_times_id, flag);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    async postOrder(orderId, schedule_times_id) {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/postOrder&token=' + token,
        data: param({ id: orderId, schedule_times_id: schedule_times_id }),
      })
        .then(({ data }) => {
          if (data) {
            this.resPostOrder(orderId);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    //RESPONSE FOR REQUISITIONS
    resGetscheduleTime(data) {
      this.times = data.dividedTime;
      this.lengthTable = data.lengthTable;
      this.days = data.days;
      this.parcialDays = data.parcialDays;
      this.schedule = data.schedule;
      this.monthName = data.monthName;
      this.isEnd = data.end;
      this.initialIndex = data.blockStartIndex;
      this.rest = data.rest;
      this.yearName = data.yearName;
      this.loader = false;
    },
    resUpdateScheduleBlock(schedule_times_id, flag) {
      this.date = this.dateFormat(this.schedule[this.timeIndexValue][this.dayIndexValue].date);
      this.time = this.schedule[this.timeIndexValue][this.dayIndexValue].time;

      if (schedule_times_id.length > 1) {
        for (var x = 0; x < this.times.length; x++) {
          if (flag) this.schedule[x][this.dayIndexValue].value = 'bloqueado';
          else this.schedule[x][this.dayIndexValue].value = '';
        }
      } else {
        if (flag) this.schedule[this.timeIndexValue][this.dayIndexValue].value = 'bloqueado';
        else this.schedule[this.timeIndexValue][this.dayIndexValue].value = '';
      }
      this.callToModalSuccess();
    },
    resUpdateOrder(orderId) {
      this.unlinkedOrder = orderId;
      this.selected = !this.selected;
      this.customerOrder = false;
      this.schedule[this.timeIndexValue][this.dayIndexValue].value = '';
      this.callToModalSuccess();
    },
    resGetOrder(data) {
      this.loading = false;
      this.loaderSearch = false;
      this.isSearchorder = true;
      if (data) {
        this.hasNoOrder = false;
        this.customerOrder = data;
      } else {
        this.hasNoOrder = true;
        this.customerOrder = false;
        this.selected = false;
      }
    },
    resScheduled(orderId, data) {
      this.loading = false;
      this.hasSchedule = orderId;
      this.isSearchorder = true;
      this.foundSchedule = data;
      this.loaderSearch = false;
    },
    resPostOrder(orderId) {
      this.schedule[this.timeIndexValue][this.dayIndexValue].value = orderId;
      this.callToModalSuccess();
    },
  },
  mounted() {
    this.isLoad();
  },
  beforeDestroy() {
    this.isUnload();
  },
};
</script>

<style scoped>
#content-scheduled {
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  max-width: 794.1px;
  max-height: 617px;
}
#content-scheduled::-webkit-scrollbar-thumb {
  background: gray;
  border-radius: 4px;
}
#content-scheduled::-webkit-scrollbar {
  width: 5px;
  background: lightgray;
  z-index: 1;
}
.btn-loader {
  height: 50px;
  top: 550px;
  position: absolute;
}
.btn-action-schedule {
  bottom: 16px;
  position: absolute;
}
.btn-modal-schedule {
  width: 120px;
}
.buttons-modal {
  width: 100%;
}
.result-btn-choice {
  width: 100%;
  background: #1a1a1a;
  min-height: 110px;
  border-radius: 4px;
  flex-direction: column;
  justify-content: center;
  padding: 8px;
  border: solid 1px transparent;
  transition: 0.3s;
  margin-bottom: 32px;
}
.result-btn-choice:hover {
  box-shadow: rgba(0, 0, 0, 0.35) 0px 0px 15px;
}
.noHover:hover{
  box-shadow: none !important;
}
.modal-success {
  min-height: 250px !important;
  justify-content: center;
}
.base-modal {
  min-height: 600px;
  width: 450px;
  margin: auto;
  padding: 0 16px 16px 16px;
}
.modalSuccess {
  width: 100%;
  background: #1a1a1a;
  min-height: 110px;
  border-radius: 4px;
  flex-direction: column;
  justify-content: center;
  padding: 8px;
  transition: 0.3s;
}
.select {
  width: 102px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.information-schedule {
  width: 100%;
  min-height: 50px;
  border-radius: 4px;
  flex-direction: column;
  justify-content: center;
  padding: 8px;
}
.observation-schedule{
  width: 100%;
  height: 111px;
  resize: none;
}
.division {
  width: 1px;
  height: 100%;
  background: #dddddd;
  position: absolute;
  right: 0;
  top: 0px;
}
.division-bottom {
  width: 100%;
  height: 1px;
  background: #dddddd;
  position: absolute;
  bottom: 0;
  left: 0;
}
.overlayTable {
  position: fixed;
  width: 100%;
  background: rgba(0, 0, 0, 0.3);
  cursor: not-allowed;
  display: none;
  align-items: center;
  justify-content: center;
}
.edit {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 25px;
  color: #fff;
  background: #337ab7;
  border-radius: 4px;
  cursor: pointer;
}
.hours {
  width: 100%;
  height: 40.9px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: solid 1px #dddddd;
  border-right: solid 1px #dddddd;
  background-color: #f2f2f2;
  font-weight: bold;
  position: sticky;
  left: 0;
  z-index: 1;
  padding: 4px 8px;
}
.numberFormat {
  border-radius: 6px;
  background: #a5a5a5;
  text-shadow: 0px 2px gray;
  width: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 25px;
  margin: auto;
  color: #fff;
}
.search {
  margin: 32px 0 16px 0;
  width: 100%;
}
.search-scheduled {
  width: 100%;
  max-width: 794.1px;
  margin-bottom: 16px;
}
.disable-pagination {
  opacity: 0;
  pointer-events: none;
}
.month-name {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 6px;
  padding: 8px 16px;
}
.expireDate {
  filter: contrast(0.5);
  pointer-events: none;
}
.pagination {
  display: flex;
  opacity: 0;
  align-items: center;
  justify-content: space-between;
  position: absolute;
  top: 0;
  z-index: 3;
  height: 82px;
  width: 794px;
  padding: 0 24px;
  background: rgba(0, 0, 0, 0.3);
  transition: 0.3s;
}
.pagination:hover {
  opacity: 1;
}
.arrow-icon {
  color: #000;
  font-size: 28px;
  background: #fff;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 16px;
  width: 20px;
  cursor: pointer;
}
.mont-name span {
  color: #fff;
}
.text-info {
  color: #000000;
  text-decoration: none;
}
.text-link {
  color: #337ab7;
  font-weight: bold;
}
.text-break {
  word-break: break-all;
}
.textFormat {
  text-transform: capitalize;
}
.text-dark-opacity {
  color: rgba(0, 0, 0, 0.8);
}
.text-observation{
  text-align: start;
  word-break: break-all;
}
.clockIcon {
  margin-bottom: 2px;
  font-size: 24px;
}
.clock {
  margin-bottom: -1px !important;
  border-bottom: solid 1px #dddddd !important;
}
.found {
  border: solid 2px #000;
  border-radius: 8px;
}
.block {
  background: #d9534f;
  color: #d9534f;
}
.outSale {
  background: #e1aa41;
  color: #e1aa41;
}
.scheduled {
  background: #5cb85c;
}
.blockSchedule {
  background: #f6d5d8;
}
.toSchedule {
  background: #d9f2df;
}
.freeSchedule {
  background: #fff;
}
.freeSchedule-info {
  background: #fff;
  border: solid 1px #b9b7b7;
}
.unavailable {
  background: #bdbdbd;
}
.borderSelected {
  border: solid 1px lightgray;
}
.borderDays {
  border-bottom: solid 1px gray;
}
.showDeleteOrder {
  transform: scale(1);
}
.offDeleteOrder {
  transform: scale(0);
}
.inactive {
  padding: 64px;
}
.text-date {
  letter-spacing: 1px;
  color: #fff;
}
.spinner {
  font-size: 24px;
  animation-name: spinnerLoad;
  animation-duration: 1s;
  animation-iteration-count: infinite;
}
.spinner-black {
  font-size: 24px;
  animation-name: spinnerLoad;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  color: #000;
}
@keyframes spinnerLoad {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
table {
  border-collapse: collapse;
}
thead {
  background: #dddddd;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 2;
}
td {
  border: 1px solid #dddddd;
  text-align: center;
  border-left: 0;
  background: #fff;
}
th {
  background-color: #f2f2f2;
  border-right: 1px solid #dddddd;
  border-collapse: collapse;
}
</style>
