<template>
  <div>
    <base-alert v-show="alert.type" :apperance="alert.type" @close="alert = {}">
      <span v-html="alert.message"></span>
    </base-alert>

    <base-modal
      v-if="showForm"
      title="Faça seu agendamento"
      size="medium"
      @close="handleCloseForm"
      :slotDefaultOverflowAuto="true"
    >
      <validation-observer
        tag="div"
        ref="validationObserver"
        v-slot="{ handleSubmit }"
        @submit.prevent="onValidationObserverSubmit()"
      >
        <form
          class="col-xs-12 col-md-12 no-padding horizontal-padding-medium"
          method="post"
          ref="form"
          @submit.prevent="handleSubmit(onSubmit)"
        >
          <!-- Meet Type  -->
          <group-radio label="Selecione o tipo de agendamento:" :inline="true">
            <base-radio
              label="Presencial"
              name="meet_type"
              value="Presencial"
              v-model="settings.meet_type"
              @change="getScheduleDates"
              :inline="true"
              required
            />
            <base-radio
              label="Virtual"
              name="meet_type"
              value="Virtual"
              v-model="settings.meet_type"
              :inline="true"
              @change="getScheduleDates"
              required
            />
          </group-radio>

          <!-- Select Date -->
          <validation-provider name="meet_date" class="col-xs-12 col-md-6" rules="required" v-slot="{ errors, valid }">
            <base-input
              name="meet_date"
              type="date"
              mask="date"
              class="pointer"
              format="DD/MM/YYYY"
              value-type="format"
              description="Clique para selecionar a data"
              label="Datas disponíveis para agendamento:"
              v-model="settings.meet_date"
              :autocomplete="false"
              :disabled="!showOptions.meet_date ? true : false"
              :error="errors[0]"
              :valid="valid"
              :disabled-date="disabledInvalidDates"
              :editable="false"
              @input="getScheduleTimes"
              required
            />
          </validation-provider>

          <!-- Select Time -->
          <validation-provider name="meet_time" rules="required" class="col-xs-12 col-md-6" v-slot="{ errors, valid }">
            <base-select
              name="meet_time"
              label="Horários disponíveis para agendamentos:"
              class="top-margin-small"
              description="Clique para selecionar o horário"
              v-model="settings.meet_time"
              :valid="valid"
              :error="errors[0]"
              :disabled="!showOptions.meet_time ? true : false"
              required
            >
              <option value="">Selecione o horário</option>
              <option :value="item" v-for="(item, index) in timeList" :key="index">{{ item }}</option>
            </base-select>
          </validation-provider>

          <!-- Button confirm and cancel -->
          <div class="top-margin-medium flex flex-row gap-2 justify-start items-center">
            <base-button
              apperance="confirm"
              type="submit"
              square
              size="medium"
              class="w-120px"
              :disabled="!settings.meet_time ? true : false"
            >
              Salvar
            </base-button>
            <base-button 
              apperance="cancel" 
              square 
              size="medium" 
              class="w-120px" 
              @click.native="handleCloseForm"
            >
              Cancelar
            </base-button>
          </div>
        </form>
      </validation-observer>
    </base-modal>
  </div>
</template>

<script>
import formMixin from '@mixins/formMixin';
import axiosApi, { param } from '@assets/js/axios-api';

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

export default {
  name: 'ScheduleCustomerSelect',
  components: {
    BaseAlert: () => import(/* webpackChunkName: "BaseAlert" */ '@elements/BaseAlert/index.vue'),
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "Basebutton" */ '@elements/BaseButton/index.vue'),
    BaseSelect: () => import(/* webpackChunkName: "BaseSelect" */ '@elements/BaseSelect/index.vue'),
  },
  props: {
    showForm: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: String || Number,
      default: 0,
    },
  },
  mixins: [formMixin],
  data() {
    return {
      alert: {},
      dateList: [],
      timeList: [],
      settings: {
        order_id: this.orderId,
      },
      showOptions: {
        meet_date: false,
        meet_time: false,
      },
    };
  },
  methods: {
    async onSubmit() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'index.php?route=common/schedule/setOrderScheduled',
        data: param(this.settings),
      })
        .then(({ data }) => {
          this.alert = {
            type: data.type,
            message: data.message,
          };

          if (data.type == 'success') {
            this.$emit('setinfos', this.settings);
            this.$refs.validationObserver.reset();
            setTimeout(() => this.handleCloseForm(), 2000);
          }  
        })
        .catch((err) => console.error(err))
    },
    async getScheduleDates() {
      this.settings.meet_date = '';
      this.settings.meet_time = '';
      this.showOptions.meet_date = false;
      this.showOptions.meet_time = false;

      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'index.php?route=common/schedule/getScheduleDates',
        data: param({ meet_type: this.settings.meet_type }),
      })
        .then(({ data }) => {
          if (data.length <= 0) {
            return (this.alert = {
              type: 'warning',
              message: 'Nenhuma agenda disponível nesta opção de reunião. Troque a opção ou contate-nos!',
            });
          }
          this.dateList = data;
          this.showOptions.meet_date = true;
        })
        .catch((err) => console.log(err, err.response));
    },
    async getScheduleTimes() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'index.php?route=common/schedule/getScheduleTimes',
        data: param({ meet_type: this.settings.meet_type, meet_date: this.settings.meet_date }),
      })
        .then(({ data }) => {
          if (data.length <= 0) {
            return (this.alert = {
              type: 'warning',
              message: 'Verifique as opções do formulário e preencha corretamente!',
            });
          }
          this.timeList = data;
          this.showOptions.meet_time = true;
        })
        .catch((err) => console.log(err, err.response));
    },
    disabledInvalidDates(date) {
      const formattedDate = this.formatDate(date);
      return !this.dateList.includes(formattedDate);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleCloseForm() {
      this.$emit('callback', false);
    },
  },
};
</script>
