<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">
                                <h3 class="pull-left">Productos</h3>
                                <button
                                    class="btn btn-black pull-right rounded-pill shadow-sm m-1"
                                    @click="refrescar"
                                    >
                                    Refrescar
                                </button>
                                <button
                                    class="btn btn-dark pull-right rounded-pill shadow-sm m-1"
                                    @click="limpiar"
                                >
                                    Limpiar filtros
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="w-100">
                        <div class="container">
                            <div class="row align-items-center">
                                <div class="col-lg-10 col-md-10 mb-2">
                                    <label class="form-label fw-bold text-muted"
                                        ></label
                                    >
                                    <input
                                        v-model="search"
                                        class="form-control w-100 product-search rounded-pill shadow-sm"
                                        placeholder="Buscar productos..."
                                        @keyup.enter="getBuscar"
                                    />
                                </div>
                                <div class="col-lg-2 col-md-2 mb-2 text-end">
                                    <label class="form-label fw-bold text-muted"
                                        >Resultados</label
                                    >
                                    <multiselect
                                        v-model="pageSize"
                                        :options="options_select2"
                                        :searchable="true"
                                        :preselect-first="true"
                                        placeholder="Seleccione..."
                                        selected-label=""
                                        select-label="Presione para seleccionar"
                                        deselect-label="Presione para deseleccionar"
                                        @update:model-value="getBuscar"
                                        class="shadow-sm"
                                    />
                                </div>
                            </div>
                            <div class="row g-3">
                                <div class="col-md-3 col-sm-6">
                                    <label class="form-label fw-bold text-muted"
                                        >Marca</label
                                    >
                                    <multiselect
                                        v-model="marca_id"
                                        mode="tags"
                                        :close-on-select="true"
                                        :searchable="true"
                                        :options="optionsMarca"
                                        placeholder="Seleccione..."
                                        selected-label=""
                                        select-label="Presione para seleccionar"
                                        deselect-label="Presione para deseleccionar"
                                        @update:model-value="changeMarca"
                                        label="marca"
                                        track-by="marca"
                                        class="shadow-sm"
                                    />
                                </div>
                                <div class="col-md-3 col-sm-6">
                                    <label class="form-label fw-bold text-muted"
                                        >Tipo Producto</label
                                    >
                                    <multiselect
                                        v-model="tipo_producto_id"
                                        mode="tags"
                                        :close-on-select="true"
                                        :searchable="true"
                                        :options="optionsTipoProducto"
                                        placeholder="Seleccione..."
                                        selected-label=""
                                        select-label="Presione para seleccionar"
                                        deselect-label="Presione para deseleccionar"
                                        @update:model-value="changeTipoProducto"
                                        label="descripcion"
                                        track-by="descripcion"
                                        class="shadow-sm"
                                    />
                                </div>
                                <div class="col-md-3 col-sm-6">
                                    <label class="form-label fw-bold text-muted"
                                        >Tratamiento</label
                                    >
                                    <multiselect
                                        v-model="tipo_servicio_id"
                                        mode="tags"
                                        :close-on-select="true"
                                        :searchable="true"
                                        :options="optionsTipoServicio"
                                        placeholder="Seleccione..."
                                        selected-label=""
                                        select-label="Presione para seleccionar"
                                        deselect-label="Presione para deseleccionar"
                                        @update:model-value="changeTipoServicio"
                                        label="descripcion"
                                        track-by="descripcion"
                                        class="shadow-sm"
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="custom-table">
                        <div class="container mt-4">
                            <div class="row">
                                <div
                                    class="col-md-4 mb-4"
                                    v-for="producto in obtener_productos"
                                    :key="producto.id"
                                >
                                    <div
                                        class="card h-100 shadow-sm position-relative"
                                    >
                                        <button
                                            class="btn btn-success btn-sm position-absolute top-0 end-0 m-2"
                                            @click="
                                                getProductoIdDetalle(producto)
                                            "
                                        >
                                            Ver más...
                                        </button>
                                        <img
                                            class="card-img-top"
                                            :src="
                                                urls +
                                                producto.path.replace(
                                                    'public',
                                                    '/storage'
                                                )
                                            "
                                            alt=""
                                            style="
                                                height: 200px;
                                                object-fit: cover;
                                            "
                                        />
                                        <div class="card-body text-center">
                                            <h6
                                                class="card-title font-weight-bold"
                                            >
                                                {{ producto.nombre }}
                                            </h6>
                                            <p class="card-text mb-2">
                                                Marca:
                                                <b>{{ producto.marca }}</b>
                                            </p>
                                            <p
                                                class="card-text font-weight-bold text-primary"
                                            >
                                                ${{ producto.total }}
                                            </p>
                                        </div>
                                        <div
                                            v-if="token"
                                            class="card-footer bg-white text-center"
                                        >
                                            <button
                                                class="btn btn-primary w-75"
                                                @click="getProductoId(producto)"
                                            >
                                                Agregar a carrito
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="VueTables VueTables--client">
                            <div class="text-center">
                                <pagination
                                    v-model="page"
                                    :records="totalPages"
                                    :per-page="pageSize"
                                    @paginate="getProductoAll"
                                    :options="options_page"
                                />
                            </div>
                        </div>
                    </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-md" role="document">
                <div class="modal-content">
                    <div
                        class="modal-header titulo-dorado"
                        id="registerModalLabel"
                    >
                        <h4 class="modal-title">Agregar al carrito</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-12">
                                <h3>
                                    <b>{{ dataPreview.nombre }}</b>
                                </h3>
                            </div>
                            <div class="col-12">
                                <div class="justify-content-center">
                                    <form
                                        class="mt-0 text-center"
                                        ref="formComponent"
                                        @submit.stop.prevent=""
                                    >
                                        <table class="mt-3">
                                            <tbody>
                                                <tr>
                                                    <td colspan="1">
                                                        <h5>
                                                            <b>Precio:</b>
                                                        </h5>
                                                    </td>
                                                    <td colspan="1">
                                                        <h5>
                                                            <b>Total:</b>
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="1">
                                                        <h5>
                                                            {{
                                                                currency(
                                                                    dataPreview.total
                                                                )
                                                            }}
                                                        </h5>
                                                    </td>
                                                    <td colspan="1">
                                                        <h5>
                                                            {{
                                                                currency(
                                                                    dataPreview.total *
                                                                        form.cantidad
                                                                )
                                                            }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2">
                                                        <div
                                                            class="input-group mt-4"
                                                        >
                                                            <button
                                                                type="button"
                                                                class="btn btn-warning"
                                                                @click="
                                                                    () => {
                                                                        form.cantidad--;
                                                                    }
                                                                "
                                                            >
                                                                <svg
                                                                    viewBox="0 0 16 16"
                                                                    width="1em"
                                                                    height="1em"
                                                                    focusable="false"
                                                                    role="img"
                                                                    aria-label="dash"
                                                                    aria-hidden="true"
                                                                    xmlns="http://www.w3.org/2000/svg"
                                                                    fill="currentColor"
                                                                    class="bi-dash b-icon bi"
                                                                >
                                                                    <g
                                                                        transform="translate(8 8) scale(1.25 1.25) translate(-8 -8)"
                                                                    >
                                                                        <path
                                                                            d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"
                                                                        ></path>
                                                                    </g>
                                                                </svg>
                                                            </button>
                                                            <number-spinner
                                                                v-model="
                                                                    form.cantidad
                                                                "
                                                                :min="1"
                                                                class="form-control"
                                                                :vertical="true"
                                                                :circular="true"
                                                                :max="1000"
                                                            />

                                                            <button
                                                                type="button"
                                                                class="btn btn-danger"
                                                                @click="
                                                                    () => {
                                                                        form.cantidad++;
                                                                    }
                                                                "
                                                            >
                                                                <svg
                                                                    viewBox="0 0 16 16"
                                                                    width="1em"
                                                                    height="1em"
                                                                    focusable="false"
                                                                    role="img"
                                                                    aria-label="plus"
                                                                    aria-hidden="true"
                                                                    xmlns="http://www.w3.org/2000/svg"
                                                                    fill="currentColor"
                                                                    class="bi-plus b-icon bi"
                                                                >
                                                                    <g
                                                                        transform="translate(8 8) scale(1.25 1.25) translate(-8 -8)"
                                                                    >
                                                                        <path
                                                                            d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"
                                                                        ></path>
                                                                    </g>
                                                                </svg>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="2">
                                                        <div
                                                            class="form-group mt-4"
                                                        >
                                                            <button
                                                                type="button"
                                                                class="btn btn-black w-100"
                                                                @click="
                                                                    createTienda
                                                                "
                                                            >
                                                                Agregar al carrito
                                                            </button>
                                                        </div>
                                                    </td>
                                                    <td></td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register Modal detalle -->
        <div
            class="modal fade"
            id="registerModalDetalle"
            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">Ver más</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-12">
                                <h3>
                                    <b>{{ dataPreview.nombre }}</b>
                                </h3>
                            </div>
                            <div
                                class="col-md-6 col-sm-12 col-6"
                                style="text-align: center"
                            >
                                <img
                                    :src="
                                        urls +
                                        dataPreview.path.replace(
                                            'public',
                                            '/storage'
                                        )
                                    "
                                    alt=""
                                    style="height: 100%"
                                />
                            </div>
                            <div class="col-md-6 col-sm-12 col-6">
                                <div
                                    class="custom-file-container__image-preview_update_presentacion_tienda"
                                >
                                    <table class="mt-3">
                                        <tbody>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        <b>Marca:</b>
                                                    </h6>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        {{ dataPreview.marca }}
                                                    </h6>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        <b>Tipo producto:</b>
                                                    </h6>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        {{
                                                            dataPreview.tipo_producto
                                                        }}
                                                    </h6>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        <b>Tipo tratamiento:</b>
                                                    </h6>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2">
                                                    <h6>
                                                        {{
                                                            dataPreview.tipo_tratamiento
                                                        }}
                                                    </h6>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="col-sm-12 mt-4">
                                <span v-html="dataPreview.descripcion"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <loading
            v-model:active="isLoading"
            :can-cancel="false"
            :is-full-page="true"
        />
    </div>
</template>
<style>
.table3 .actions svg {
    padding: 2px;
}
.descripcion-recortada {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    max-height: 3em; /* Ajusta según el tamaño de la fuente */
    line-height: 1.5em; /* Ajusta si es necesario */
}
</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 ProductoRepository from "@/repositories/ProductoRepository";
import * as TiendaRepository from "@/repositories/TiendaRepository";
import * as MarcaRepository from "@/repositories/MarcaRepository";
import * as TipoServicioRepository from "@/repositories/TipoServicioRepository";
import * as TipoProductoRepository from "@/repositories/TipoProductoRepository";
import Pagination from "v-pagination-3";

import { NumberSpinner } from "vue3-number-spinner";

// select2
import Multiselect from "@suadelabs/vue3-multiselect";
import "@suadelabs/vue3-multiselect/dist/vue3-multiselect.css";
// loading
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";

import "@/assets/sass/forms/file-upload-with-preview.min.css";

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

import axios from "axios";

useMeta({ title: "EGURROLA" });

const store = useAuthStore();
const obtener_productos = ref([]);
const token = ref(null);

const urls = ref(process.env.MIX_URL);

const formatter = new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
});

//formulario crear y eliminar
let registerModal = ref(false);
let registerModalDetalle = ref(false);
const page = ref(1);
const isLoading = ref(true);
const order = ref({
    name: "nombre",
    order: "DESC",
});
const search = ref("");
const searchMarca = ref("");
const searchTipo = ref("");
const searchTratamiento = ref("");
const options_select2 = ref([6, 12, 24, 48, 100]);
const pageSize = ref(6);
const totalPages = ref(0);
const is_entrada = ref(false);
const editedIndex = ref(-1);
const formComponent = ref(null);
const errors = ref({});
const form = ref({
    user_id: store.current_user.id,
    producto_id: null,
    cantidad: 1,
});

const dataPreview = ref({
    id: "",
    nombre: "",
    descricion: "",
    marca: "",
    tipo_producto: "",
    tipo_tratamiento: "",
    precio: "",
    total: "",
    path: "",
});

//select2
const marca_id = ref({
    id: null,
    marca: "",
});
const optionsMarca = ref([]);

const changeMarca = (data) => {
    if (data == null) {
        marca_id.value = {
            id: "",
            marca: "",
        };
        searchMarca.value = "";
        getBuscar();
        return;
    }
    searchMarca.value = data.id;
    getBuscar();
};

const tipo_servicio_id = ref({
    id: null,
    descripcion: "",
});
const optionsTipoServicio = ref([]);

const changeTipoServicio = (data) => {
    if (data == null) {
        tipo_servicio_id.value = {
            id: "",
            descripcion: "",
        };
        searchTratamiento.value = "";
        getBuscar();
        return;
    }
    searchTratamiento.value = data.id;
    getBuscar();
};

const tipo_producto_id = ref({
    id: null,
    marca: "",
});
const optionsTipoProducto = ref([]);

const changeTipoProducto = (data) => {
    if (data == null) {
        tipo_producto_id.value = {
            id: "",
            descripcion: "",
        };
        searchTipo.value = "";
        getBuscar();
        return;
    }
    searchTipo.value = data.id;
    getBuscar();
};

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

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

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

const options_page = ref({
    texts: {
        count: "Mostrando {from} a {to} de {count}",
        filter: "",
        filterPlaceholder: "Buscar...",
        limit: "Resultados:",
    },
});

const createTienda = async () => {
    try {
        is_entrada.value = true;
        isLoading.value = true;
        const response = await TiendaRepository.createTienda(form.value);
        document.getElementById("evento_recargar_tienda").click();
        showMessage("Agregado correctamente");
        close();
        initializeCreate();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value = false;
    }
};

const getProductoId = async (data) => {
    try {
        form.value = {
            user_id: store.current_user.id,
            producto_id: data.id,
            cantidad: 1,
        };
        dataPreview.value = {
            id: data.id,
            nombre: data.nombre,
            descripcion: data.descripcion,
            marca: data.marca,
            tipo_producto: data.tipo_producto,
            tipo_tratamiento: data.tipo_tratamiento,
            precio: data.precio,
            total: data.total,
            path: data.path,
        };
        errors.value = {};
        editedIndex.value = data.id;
        registerModal.show();
    } catch (error) {
        console.log(error);
    }
};

const getProductoIdDetalle = async (data) => {
    try {
        dataPreview.value = {
            id: data.id,
            nombre: data.nombre,
            descripcion: data.descripcion,
            marca: data.marca,
            tipo_producto: data.tipo_producto,
            tipo_tratamiento: data.tipo_tratamiento,
            precio: data.precio,
            total: data.total,
            path: data.path,
        };
        errors.value = {};
        registerModalDetalle.show();
    } catch (error) {
        console.log(error);
    }
};

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

const initializeCreate = () => {
    form.value = {
        user_id: store.current_user.id,
        producto_id: null,
        cantidad: 1,
    };
    errors.value = {};
    editedIndex.value = -1;
};

const getBuscar = () => {
    getProductoAll("si");
};

const currency = (valor) => {
    return formatter.format(valor);
};

const getProductoAll = async (inicio = "no") => {
    try {
        isLoading.value = true;
        const params = {
            search: search.value,
            marca: searchMarca.value,
            tipo: searchTipo.value,
            tratamiento: searchTratamiento.value,
            order: order.value,
        };
        if (inicio == "si") {
            page.value = 1;
        }
        const response = await ProductoRepository.getPage(
            page.value,
            pageSize.value,
            params
        );
        obtener_productos.value = response.data.data;
        totalPages.value = response.data.total;
        pageSize.value = response.data.per_page;
        isLoading.value = false;
    } catch (error) {
        console.log(error);
    }
};

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

const initialize = async () => {
    search.value = "";
    searchMarca.value = "";
    searchTratamiento.value = "";
    searchTipo.value = "";
    isLoading.value = true;
    page.value = 1;
    pageSize.value = 6;
    totalPages.value = 0;
    is_entrada.value = false;
    order.value = {
        name: "nombre",
        order: "DESC",
    };
    await getProductoAll();
    const model_marca = await getMarcaAll();
    optionsMarca.value = model_marca;
    const model_servicio = await getTipoServicioAll();
    optionsTipoServicio.value = model_servicio;
    const model_producto = await getTipoProductoAll();
    optionsTipoProducto.value = model_producto;
};

const refrescar = () => {
    initialize();
};

const limpiar = () => {
    marca_id.value = {
        id: "",
        descripcion: "",
    };
    tipo_servicio_id.value = {
        id: "",
        descripcion: "",
    };
    tipo_producto_id.value = {
        id: "",
        descripcion: "",
    };
    initialize();
};

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 () => {
    isLoading.value = true;
    token.value = window.localStorage.getItem("token");
    if (token.value) {
        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")
    );
    registerModalDetalle = new window.bootstrap.Modal(
        document.getElementById("registerModalDetalle")
    );
    await initialize();
    isLoading.value = false;
});
</script>
