<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="Nova Agenda" 
      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), loader = true"
        >
          <!-- Name -->
          <validation-provider
            name="name"
            rules="required|min: 3|max: 60"
            v-slot="{ errors, valid, passed}"
          >
            <base-input
              name="name"
              mask="alphanumeric"
              maxlength="60"
              minlength="3"
              required
              label="Nome da agenda:"
              placeholder="Ex: Agenda 1 - Virtual"
              v-model="settings.name"
              :autocomplete="false"
              :valid="valid && passed"
              :error="errors[0]"
            />
          </validation-provider>

          <!-- Status and Type  -->
          <div class="flex row top-margin-x-small">
            <validation-provider
              name="status"
              rules="required"
              class="col-xs-12 col-md-6"
              v-slot="{ errors, valid }"
            >
              <base-select
                name="status"
                label="Status:"
                v-model="settings.status"
                :valid="valid"
                :error="errors[0]"
                :disabled="disableForm"
              >
                <option value="1">Ativo</option>
                <option value="0">Inativo</option>
              </base-select>
            </validation-provider>  

            <validation-provider
              name="type"
              rules="required"
              class="col-xs-12 col-md-6"
              v-slot="{ errors, valid }"
            >
              <base-select
                name="type"
                label="Tipo da agenda:"
                v-model="settings.type"
                :valid="valid"
                :error="errors[0]"
                :disabled="disableForm"
              >
                <option value="Presencial">Presencial</option>
                <option value="Virtual">Virtual</option>
              </base-select>
            </validation-provider>
          </div>

          <!-- Date Start and Date End   -->
          <div class="flex row top-margin-x-small">
            <validation-provider
              name="date_start"
              class="col-xs-12 col-md-6"
              :rules="{
                required: true,
                date_smaller_than_today: { data: settings.date_start }
              }"
              v-slot="{ errors, valid }"
            >
              <base-input
                name="date_start"
                type="date"
                mask="date"
                format="DD/MM/YYYY"
                value-type="format"
                label="Data de início:"
                :autocomplete="false"
                required
                v-model="settings.date_start"
                :error="errors[0]"
                :valid="valid"
              />
            </validation-provider>

            <validation-provider
              name="date_end"
              class="col-xs-12 col-md-6"
              :rules="{
                required: true,
                date_smaller_than_today: { data: settings.date_end },
                date_greater_than_start: { start: settings.date_start },
              }"
              v-slot="{ errors, valid }"
            >
              <base-input
                name="date_end"
                type="date"
                mask="date"
                format="DD/MM/YYYY"
                value-type="format"
                label="Data final:"
                required
                :autocomplete="false"
                v-model="settings.date_end"
                :disabled="!settings.date_start ? true : false"
                :error="errors[0]"
                :valid="valid"
              />
            </validation-provider>
          </div>

          <!-- Time Start and Time End -->
          <div class="flex row top-margin-x-small">
            <validation-provider
              name="time_start"
              class="col-xs-12 col-md-6"
              rules="required"
              v-slot="{ errors, valid }"
            >
              <base-input
                name="time_start"
                type="time"
                label="Horário inicial:"
                required
                v-model="settings.time_start"
                :error="errors[0]"
                :valid="valid"
              />
            </validation-provider>

            <validation-provider
              name="time_end"
              class="col-xs-12 col-md-6"
              :rules="{
                required: true,
                time_greater_than_start: { start: settings.time_start },
              }"
              v-slot="{ errors, valid }"
            >
              <base-input
                name="time_end"
                type="time"
                label="Horário final:"
                required
                v-model="settings.time_end"
                :disabled="!settings.time_start ? true : false"
                :error="errors[0]"
                :valid="valid"
              />
            </validation-provider>
          </div>

          <!-- Work on Weekend -->
          <base-checkbox
            type="checkbox"
            name="work_on_weekend"
            label="Trabalha de fim de semana"
            class="flex center-xs text-small top-margin-small"
            v-model="settings.work_on_weekend"
          />

          <!-- Interval to meet -->
          <div class="relative flex items-center">
            <input 
              type="checkbox" 
              name="interval_to_meet_checkbox" 
              class="checkbox-entry"
              checked
            >
            <label for="interval_to_meet" class="checkbox-text not-allowed">Intervalo entre as reuniões: </label>
              <input 
                min="0"
                max="480"
                step="15"
                type="number" 
                name="interval_to_meet" 
                class="input-interval horizontal-margin-x-small"
                placeholder="00"
                required
                v-model.number="settings.interval_to_meet" 
              >
            <span class="not-allowed">minutos.</span>
          </div>

          <!-- Interval for lunch -->
          <div class="relative flex items-baseline bottom-margin-medium text-dark-opacity">
            <base-checkbox
              type="checkbox"
              name="interval_for_lunch_status"
              label="Pausa para almoço com inicio ás: "
              v-model="settings.interval_for_lunch_status"
              :inline="true"
            /> 

            <input 
              type="time" 
              name="interval_for_lunch" 
              class="input-interval"
              :required="settings.interval_for_lunch_status ? true : false"
              v-show="settings.interval_for_lunch_status"
              v-model="settings.interval_for_lunch" 
            >
          </div>

          <!-- Notes -->
          <validation-provider
            name="notes"
            rules="min: 3|max: 200"
            v-slot="{ errors, valid }"
          >
            <base-textarea
              name="notes"
              maxlength="200"
              minlength="3"
              mask="alphanumeric"
              rows="3"
              label="Observações:"
              v-model="settings.notes"
              maxheight="100px"
              :error="errors[0]"
              :valid="valid"
              :disabled="disableForm"
            />
          </validation-provider>

          <!-- Button confirm and cancel -->
          <div class="top-margin-x-large flex flex-row gap-2 justify-start items-center">
            <base-button 
              apperance="success" 
              type="submit" 
              square 
              size="medium" 
              class="w-120px"
              :loading="loader"
            >
              Salvar
            </base-button>
            <base-button 
              apperance="error" 
              square 
              size="medium" 
              class="w-120px"
              @click.native="handleCloseForm"
            >
              Cancelar
            </base-button>
          </div>
        </form>
      </validation-observer>
    </base-modal>
  </div>
</template>

<script>
import store from "@components/Schedule/storeSchedule.js";
import formMixin from "@mixins/formMixin";
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: 'ScheduleForm',
  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'),
    BaseCheckbox: () => import(/* webpackChunkName: "BaseCheckbox" */ '@elements/BaseCheckbox/index.vue'),
  },
  props: {
    showForm: {
      type: Boolean,
      default: false,
    },
  },
  mixins: [formMixin],
  data() {
    return {
      alert: {},
      settings: {},
      loader: false,
    };
  },
  methods: {
    async onSubmit() {           
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/newSchedule&token=' + token,
        data: param(this.settings),
      })
        .then(({ data }) => {
          if (data.success.status) {
            this.settings.schedule_id = data.success.schedule_id;

            store.dispatch('getScheduleForm', this.settings).then(() => {
              this.alert = {
                type: 'success',
                message: 'Agenda criada com sucesso!',
              };
            });

            this.$refs.validationObserver.reset();
            setTimeout(() => this.handleCloseForm(), 3000);
          }
        })
        .catch((err) => console.error(err))
        .finally(() => this.loader = false);
    },
    handleCloseForm() {
      this.$emit('callback', false);
    },
  },
}
</script>

<style scoped>
.relative {
  position: relative;
}

.justify-start {
  justify-content: flex-start;
}

.items-center {
  align-items: center;
}

.items-baseline {
  align-items: baseline;
}

.w-120px {
  width: 7.5rem;
}

.not-allowed {
  cursor: not-allowed;
}
.input-interval {
  border: 1px solid #9ca3af;
  padding: 0.25rem;
  border-radius: 0.25rem;

  outline: none;
}
</style>