<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="showEditModal" 
      title="Editar Agenda" 
      size="medium" 
      :slotDefaultOverflowAuto="true"
      @close="handleCloseEdit"
    >
      <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)"
        >
          <!-- 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 de Abril"
              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 bottom-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>

           <!-- 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"
            >
              Salvar
            </base-button>
            <base-button 
              apperance="error" 
              square 
              size="medium" 
              class="w-120px"
              @click.native="handleCloseEdit"
            >
              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";
import store from "@components/Schedule/storeSchedule.js";

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'),
    BaseCheckbox: () => import(/* webpackChunkName: "BaseCheckbox" */ '@elements/BaseCheckbox/index.vue'),
  },
  props: {
    scheduleID: {
    type: String | Number,
    },  
    showEditModal: {
      type: Boolean,
      default: false
    }  
  },
  mixins: [formMixin],
  data() {
    return {
      alert: {},
      settings: {},
    };
  },
  methods: {
    async onSubmit() {     
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/editSchedule&token=' + token,
        data: param(this.settings),
      })
        .then(({ data }) => {
          this.alert = {
            type: data.type,
            message: data.message,
          };

          if (data.type == 'success') {
            store.dispatch('getScheduleEditForm', this.settings)
            this.$refs.validationObserver.reset();
            setTimeout(() => this.handleCloseEdit(), 3000);
          }  
        })
        .catch((err) => console.error(err))
    },
    async getSettings() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'admin/index.php?route=sale/schedule/getSchedule&token=' + token,
        data: param({ id: this.scheduleID }),
      })
        .then(({ data }) => {
          
          if (!data[0]) {
            this.alert = {
              type: 'warning',
              message: `Atenção: Um erro inesperado aconteceu ao consultar as informações da agenda!`
            }; 
          }

          this.settings = data[0]; 

        })
        .catch(err => console.log(err, err.response));
    },
    handleCloseEdit() {
      this.$emit('callbackEditModal', false);
    },
  },
  mounted () {
    this.getSettings();
  },
}
</script>
