<template>
    <div class="layout-px-spacing">
        <div class="row layout-top-spacing">
            <div class="col-xl-12 col-lg-12 col-sm-12 layout-spacing">
                <div class="panel p-3">
                    <div class="row">
                        <div class="col-xl-12 col-lg-12 col-sm-12">
                            <div class="text-center titulo-dorado">
                                <h1 class="pull-left">Horarios</h1>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    @click="refrescar"
                                >
                                    Refrescar
                                </button>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    data-bs-toggle="modal"
                                    data-bs-target="#registerModal"
                                    @click="initializeCreate"
                                >
                                    Nuevo
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="custom-table">
                        <v-client-table
                            :data="obtener_horarios"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #actions="item">
                                <a
                                    href="javascript:void(0);"
                                    title="Delete"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="deleteItem(item.row.id)"
                                >
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        width="24"
                                        height="24"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="1.5"
                                        stroke-linecap="round"
                                        stroke-linejoin="round"
                                        class="feather feather-trash"
                                    >
                                        <polyline
                                            points="3 6 5 6 21 6"
                                        ></polyline>
                                        <path
                                            d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"
                                        ></path>
                                    </svg>
                                </a>
                            </template>
                        </v-client-table>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register Modal -->
        <div
            class="modal fade"
            id="registerModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="registerModalLabel"
            aria-hidden="true"
            v-show="true"
        >
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div
                        class="modal-header titulo-dorado"
                        id="registerModalLabel"
                    >
                        <h4 class="modal-title">
                            {{ editedIndex === -1 ? "Nuevo " : "Editar " }}
                        </h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <form
                            class="mt-0"
                            ref="formComponent"
                            @submit.stop.prevent=""
                        >
                            <div class="row">
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Sucursal</label>
                                        <multiselect
                                            v-model="sucursal_id"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsSucursales"
                                            :class="[
                                                is_entrada
                                                    ? !errors.sucursal_id
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccionar opción"
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeSucursal"
                                            label="nombre"
                                            track-by="nombre"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.sucursal_id">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Día</label>
                                        <multiselect
                                            v-model="dia_id"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsDia"
                                            :class="[
                                                is_entrada
                                                    ? !errors.dia
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            placeholder="Seleccionar opción"
                                            @update:model-value="changeDia"
                                            label="dia_name"
                                            track-by="dia_name"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.dia">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Hora Entrada</label>
                                        <flat-pickr v-model="form.hora_entrada" :config="{ noCalendar: true, enableTime: true, time_24hr: false, dateFormat: 'H:i', minTime:'00:30:00', minTime: '08:00:00', maxTime:'20:00:00', minuteIncrement:30 }" class="form-control flatpickr active"></flat-pickr>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Hora Salida</label>
                                        <flat-pickr v-model="form.hora_salida" :config="{ noCalendar: true, enableTime: true, time_24hr: false, dateFormat: 'H:i', minTime:'00:30:00', minTime: '08:00:00', maxTime:'20:00:00', minuteIncrement:30 }" class="form-control flatpickr active"></flat-pickr>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <button
                                        type="button"
                                        class="btn btn-black w-100"
                                        v-show="editedIndex === -1"
                                        @click="createHorario"
                                        >
                                        Guardar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- Eliminar Modal -->
        <div
            class="modal fade"
            id="deleteModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
        >
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">
                            ¿Estás seguro de eliminar este horario?
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-footer">
                        <button
                            type="button"
                            class="btn"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                        >
                            <i class="flaticon-cancel-12"></i> Cancelar
                        </button>
                        <button
                            type="button"
                            class="btn btn-black"
                            @click="deleteHorario()"
                        >
                            Aceptar
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <loading 
        v-model:active="isLoading"
        :can-cancel="false"
        :is-full-page="true"/>
    </div>
</template>
<style>
.table3 .actions svg {
    padding: 2px;
}
</style>
<script setup>
import { onMounted, ref } from "vue";
import "@/assets/sass/elements/tooltip.scss";
import { useMeta } from "@/composables/use-meta";
import { useAuthStore } from "@/store/AuthStore";
import * as UserRepository from "@/repositories/UserRepository";
import * as SucursalRepository from "@/repositories/SucursalRepository";
import * as HorarioRepository from "@/repositories/HorarioRepository";
import { useStateStore } from "@/store/StateStore";
import axios from "axios";
import { useRoute } from "vue-router";
import Multiselect from "@suadelabs/vue3-multiselect";
import "@suadelabs/vue3-multiselect/dist/vue3-multiselect.css";

import "@/assets/sass/scrollspyNav.scss";

// flatPickr
import flatPickr from "vue-flatpickr-component";
import "flatpickr/dist/flatpickr.css";
import "@/assets/sass/forms/custom-flatpickr.css";
import { Spanish } from "@/assets/sass/flatpickr/dist/l10n/es.js";
flatpickr.localize(Spanish);

// loading
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/css/index.css';

useMeta({ title: "EGURROLA" });

const store = useAuthStore();
const storeState = useStateStore();
const obtener_horarios = ref([]);
const route = useRoute();

//formulario crear y eliminar
let registerModal = ref(false);
let deleteModal = ref(false);
const is_entrada = ref(false);
const editedIndex = ref(-1);
const formComponent = ref(null);
const errors = ref({});
const form = ref({
    sucursal_id:storeState.current_state.sucursal_mode,
    dia:null,
    hora_entrada:'08:00:00',
    hora_salida:'20:00:00'
});

const isLoading = ref(true);

//select2
const sucursal_id = ref({
    id: storeState.current_state.sucursal_mode,
    nombre: storeState.current_state.sucursal_name_mode,
});
const optionsSucursales = ref([]);
const changeSucursal = async(data) => {
    isLoading.value=true;
    form.value.sucursal_id = data.id;
    if(data.id){
        const model_dia = await getDiasAll(data.id);
        optionsDia.value = model_dia;
    } else {
        optionsDia.value = [];
    }
    isLoading.value=false;
};
//dia
const dia_id = ref(null);
const optionsDia = ref([]);
const changeDia= (data) => {
    form.value.dia = data.id;
};
const filteredOptions= ref([]);

//table 2
const columns1 = ref([
    "id",
    'sucursal',
    'dia_name',
    'hora_entrada_temp',
    'hora_salida_temp',
    "actions",
]);

const table_option1 = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        hora_entrada_temp: (h, row, index) => {
            return "Hora Entrada";
        },
        hora_salida_temp: (h, row, index) => {
            return "Hora Salida";
        },
        dia_name: (h, row, index) => {
            return "Día";
        },
        actions: (h, row, index) => {
            return "";
        },
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: { actions: "actions text-center" },
    sortable: ["id", "sucursal",  "dia_name",  "hora_entrada_temp", "hora_salida_temp"],
    sortIcon: {
        base: "sort-icon-none",
        up: "sort-icon-asc",
        down: "sort-icon-desc",
    },
    pagination: { nav: "scroll", chunk: 5 },
    texts: {
        count: "Mostrando {from} a {to} de {count}",
        filter: "",
        filterPlaceholder: "Buscar...",
        limit: "Resultados:",
        noResults:"No hay registros"
    },
    resizableColumns: true,
});

const createHorario = async () => {
    try {
        isLoading.value=true;
        is_entrada.value = true;
        const response = await HorarioRepository.createHorario(
            form.value
        );
        showMessage("Guardado correctamente");
        initializeCreate();
        close();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
};

const close = () => {
    registerModal.hide();
    editedIndex.value = -1;
};

const deleteItem = (id) => {
    editedIndex.value = id;
    deleteModal.show();
};

const deleteHorario = async () => {
    try {
        isLoading.value=true;
        const response = await HorarioRepository.deleteHorario(
            editedIndex.value
        );
        showMessage("Eliminado correctamente");
        closeDelete();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
        console.log(error);
    }
};

const closeDelete = () => {
    deleteModal.hide();
    initializeCreate();
};

const initializeCreate = async() => {
    sucursal_id.value = {
        id: storeState.current_state.sucursal_mode,
        nombre: storeState.current_state.sucursal_name_mode,
    };
    form.value = {
        sucursal_id:storeState.current_state.sucursal_mode,
        dia:null,
        hora_entrada:'08:00:00',
        hora_salida:'20:00:00'
    };
    errors.value = {};
    editedIndex.value = -1;
    if(form.value.sucursal_id){
        const model_dia = await getDiasAll(form.value.sucursal_id);
        optionsDia.value = model_dia;
    } else {
        optionsDia.value = [];
    }
};

const getHorarioAll = async () => {
    try {
        const response = await HorarioRepository.getAll();
        return response.data;
    } catch (error) {
        console.log(error);
    }
};

const obtener_user = async () => {
    try {
        const response = await UserRepository.getuser();
        return response;
    } catch (error) {
        console.log(error);
    }
};

const getSucursalAll = async () => {
    try {
        const response = await SucursalRepository.getAll();
        return response.data;
    } catch (error) {
        console.log(error);
    }
};

const getDiasAll = async (sucursal_id) => {
    try {
        const response = await HorarioRepository.getDias(sucursal_id);
        return response.data;
    } catch (error) {
        console.log(error);
    }
};

const initialize = async () => {
    isLoading.value=true;
    const resp = await getHorarioAll();
    obtener_horarios.value = resp;
    table_option1.value = {
        headings: {
            id: (h, row, index) => {
                return "Folio";
            },
            hora_entrada_temp: (h, row, index) => {
                return "Hora Entrada";
            },
            hora_salida_temp: (h, row, index) => {
                return "Hora Salida";
            },
            dia_name: (h, row, index) => {
                return "Día";
            },
            actions: (h, row, index) => {
                return "";
            },
        },
        perPage: 100,
        perPageValues: [20, 50, 100],
        skin: "table table-hover",
        columnsClasses: { actions: "actions text-center" },
        sortable: ["id", "sucursal",  "dia_name",  "hora_entrada_temp", "hora_salida_temp"],
        sortIcon: {
            base: "sort-icon-none",
            up: "sort-icon-asc",
            down: "sort-icon-desc",
        },
        pagination: { nav: "scroll", chunk: 5 },
        texts: {
            count: "Mostrando {from} a {to} de {count}",
            filter: "",
            filterPlaceholder: "Buscar...",
            limit: "Resultados:",
            noResults:"No hay registros"
        },
        resizableColumns: true,
    };
    const model_sucursal = await getSucursalAll();
    optionsSucursales.value = model_sucursal;
    is_entrada.value = false;
    isLoading.value=false;
};

const refrescar = () => {
    initialize();
    showMessage("Completado correctamente");
};

const showMessage = (msg = "", type = "success") => {
    const toast = window.Swal.mixin({
        toast: true,
        position: "top",
        showConfirmButton: false,
        timer: 3000,
    });
    toast.fire({
        icon: type,
        title: msg,
        padding: "10px 20px",
    });
};

onMounted(async () => {
    const response = await obtener_user();
    store.current_user.id = response.id;
    store.current_user.name = response.name;
    store.current_user.email = response.email;
    registerModal = new window.bootstrap.Modal(
        document.getElementById("registerModal")
    );
    deleteModal = new window.bootstrap.Modal(
        document.getElementById("deleteModal")
    );
    initialize();
});
</script>
