<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">Entradas de productos</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="w-100">
                        <div class="row">
                            <div class="col-lg-10 mt-4">
                                <input v-model="search" class="form-control w-100 product-search" placeholder="Buscar..." @keyup.enter="getBuscar" />
                            </div>
                            <div class="col-lg-2">
                                <div class="form-group form-inline pull-right VueTables__limit">
                                    <div class="VueTables__limit-field">
                                        <label>Resultados</label>
                                        <multiselect
                                            v-model="pageSize"
                                            :options="options_select2"
                                            :searchable="true"
                                            :preselect-first="true"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccionar..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="getBuscar"
                                        >
                                        </multiselect>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="custom-table">
                        <v-client-table
                            :data="obtener_entradas"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #actions="item">
                                <div
                                    class="me-2 custom-dropdown dropdown btn-group"
                                >
                                    <a
                                        class="btn dropdown-toggle btn-icon-only"
                                        href="#"
                                        role="button"
                                        id="pendingTask"
                                        data-bs-toggle="dropdown"
                                        aria-haspopup="true"
                                        aria-expanded="false"
                                    >
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            style="width: 24px; height: 24px"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-more-horizontal"
                                        >
                                            <circle
                                                cx="12"
                                                cy="12"
                                                r="1"
                                            ></circle>
                                            <circle
                                                cx="19"
                                                cy="12"
                                                r="1"
                                            ></circle>
                                            <circle
                                                cx="5"
                                                cy="12"
                                                r="1"
                                            ></circle>
                                        </svg>
                                    </a>

                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <li>
                                            <a
                                                href="javascript:void(0);"
                                                class="dropdown-item"
                                                @click="getIngresoMercanciaId(item.row)"
                                            >
                                                Ver
                                            </a>
                                        </li>
                                        <li>
                                            <a
                                                href="javascript:void(0);"
                                                class="dropdown-item"
                                                @click="deleteItem(item.row.id)"
                                            >
                                                Eliminar
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </template>
                        </v-client-table>
                        <div class="VueTables VueTables--client">
                            <div class="text-center">
                                <pagination v-model="page" :records="totalPages" :per-page="pageSize" @paginate="getIngresoMercanciaAll" :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-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">
                                    <button
                                        type="button"
                                        class="btn btn-success"
                                        @click="abrirProductos"
                                    >
                                        Elegir producto
                                    </button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group mb-4">
                                        <label>
                                            Producto
                                        </label>
                                        <input
                                        type="hidden"
                                        :class="[is_entrada ? (!errors.producto_id ? 'is-valid' : 'is-invalid') : '']"
                                        v-model="form.producto_id">
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            No puede estar vacio
                                        </div>
                                        <h4>{{ nombre_producto }}</h4>
                                    </div>
                                </div>
                                <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="Seleccione..."
                                            :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>Cantidad</label>
                                        <input
                                            type="number"
                                            class="form-control mb-2"
                                            placeholder="Cantidad"
                                            v-model="form.cantidad"
                                            :class="[is_entrada ? (!errors.cantidad ? 'is-valid' : 'is-invalid') : '']"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.cantidad">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Costo</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Costo"
                                            v-model="form.costo"
                                            :class="[is_entrada ? (!errors.costo ? 'is-valid' : 'is-invalid') : '']"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.costo">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-group">
                                        <label>Observación</label>
                                        <textarea
                                            v-model="form.observacion"
                                            :class="[is_entrada ? (!errors.observacion ? 'form-control is-valid' : 'form-control is-invalid') : 'form-control']"
                                            class="form-control"
                                            placeholder="Agregar observación"
                                            rows="3"
                                        ></textarea>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.observacion">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group mt-2">
                                <button
                                    type="button"
                                    class="btn btn-black w-100"
                                    v-show="editedIndex === -1"
                                    @click="createIngresoMercancia"
                                >
                                    Guardar
                                </button>
                            </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 ingreso?</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="deleteIngresoMercancia()">Eliminar</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Modal productos -->
        <div
            id="modal_index_productos"
            class="modal fade"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
            style="z-index: 1100 !important"
        >
            <div class="modal-dialog modal-lg">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            Lista de Productos
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <div class="custom-table">
                            <v-client-table
                                :data="obtener_productos"
                                :columns="columns_productos"
                                :options="table_option_tratamientos"
                                ref="table_tratamientos"
                            >
                                <template #id="props">
                                    <button class="btn btn-sm btn-black"
                                    @click="agregarProducto(props.row.id,props.row.nombre)"
                                    >
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-log-out"
                                        >
                                            <path
                                                d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"
                                            ></path>
                                            <polyline
                                                points="16 17 21 12 16 7"
                                            ></polyline>
                                            <line
                                                x1="21"
                                                y1="12"
                                                x2="9"
                                                y2="12"
                                            ></line>
                                        </svg>
                                        &nbsp{{ props.row.id }}
                                    </button>
                                </template>
                            </v-client-table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register Modal -->
        <div
            class="modal fade"
            id="registerModalInfo"
            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</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.producto }}</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">

                                    <form class="mt-0" ref="formComponent" @submit.stop.prevent="">
                                        <table class="table mt-3">
                                            <tbody>
                                                <tr>
                                                    <td>
                                                        <h5>
                                                            <b>Sucursal: </b>
                                                        </h5>
                                                    </td>
                                                    <td>
                                                        <h5>
                                                            {{ dataPreview.sucursal }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <h5>
                                                            <b>Cantidades: </b>
                                                        </h5>
                                                    </td>
                                                    <td>
                                                        <h5>
                                                            {{ dataPreview.cantidad }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <h5>
                                                            <b>Costo: </b>
                                                        </h5>
                                                    </td>
                                                    <td>
                                                        <h5>
                                                            {{ currency(dataPreview.costo) }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2">
                                                        <h5>
                                                            <b>Fecha y hora de registro: </b>
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" style="text-align: center;">
                                                        <h5>
                                                            {{ dataPreview.fecha_hora }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2">
                                                        <h5>
                                                            <b>Observación: </b>
                                                        </h5>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" style="text-align: center;">
                                                        <h5>
                                                            {{ dataPreview.observacion }}
                                                        </h5>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </form>
                                </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"/>
        <button
            id="evento_recargar_reservar"
            type="button"
            v-show="false"
            class="btn btn-black"
            @click="getIngresoMercanciaAll"
        ></button>
    </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 { useStateStore } from '@/store/StateStore';
import * as UserRepository from "@/repositories/UserRepository";
import * as IngresoMercanciaRepository from "@/repositories/IngresoMercanciaRepository";
import * as ProductoRepository from "@/repositories/ProductoRepository";
import * as SucursalRepository from "@/repositories/SucursalRepository";
import Pagination from 'v-pagination-3';

// 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 axios from "axios";

useMeta({ title: "EGURROLA" });

const store = useAuthStore();
const storeState = useStateStore();
const obtener_entradas = ref([]);
const formatter = new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'});

//formulario crear y eliminar
let registerModal = ref(false);
let modal_index_productos = ref(null);
let deleteModal = ref(false);
let registerModalInfo = ref(false);
const page = ref(1);
const isLoading = ref(true);
const order = ref({
    name:'id',
    order:'DESC',
});
const search = ref("");
const options_select2 = ref([20, 50, 100]);
const pageSize = ref(20);
const totalPages = ref(0);
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,
    producto_id: null,
    costo: 0,
    cantidad: 1,
    observacion: "",
});
const dataPreview=ref({
    producto:'',
    descripcion:'',
    costo:'',
    sucursal:'',
    cantidad:'',
    path:'',
});
const nombre_producto = ref("");

// productos
const columns_productos = ref(['id','nombre','marca']);
const table_option_tratamientos = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        nombre: (h, row, index) => {
            return "Producto";
        },
        marca: (h, row, index) => {
            return "Marca";
        },
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: {  },
    sortable: ['id','nombre', 'marca'],
    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 obtener_productos = ref([]);

//table 2
const columns1 = ref([
    "id",
    "fecha_hora",
    "sucursal",
    "producto",
    "cantidad",
    "costo",
    "actions"
]);
const table_option1 = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        sucursal: (h, row, index) => {
            return "Sucursal";
        },
        producto: (h, row, index) => {
            return "Producto";
        },
        cantidad: (h, row, index) => {
            return "Cantidad";
        },
        costo: (h, row, index) => {
            return "Costo";
        },
        actions: (h, row, index) => {
            return "";
        },
    },
    perPage: 100,
    perPageValues: [],
    skin: "table table-hover",
    columnsClasses: { actions: "actions text-center" },
    sortable: [],
    sortIcon: {
        base: "sort-icon-none",
        up: "sort-icon-asc",
        down: "sort-icon-desc",
    },
    pagination: { nav: "scroll", chunk: 5, show: false, dropdown: false },
    resizableColumns: true,
    filterable: false,
    texts: {
        noResults:"No hay registros"
    },
});

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


//select sucursal
const sucursal_id = ref({
    id: storeState.current_state.sucursal_mode,
    nombre: storeState.current_state.sucursal_name_mode,
});
const optionsSucursales = ref([]);
const changeSucursal = (data) => {
    form.value.sucursal_id = data.id;
};
const urls = ref(process.env.MIX_URL);

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

const getIngresoMercanciaId = async (data) => {
  try {
    dataPreview.value = {
        sucursal:data.sucursal,
        producto:data.producto,
        descripcion:data.descripcion,
        cantidad:data.cantidad,
        costo:data.costo,
        path:data.path,
        observacion:data.observacion,
        fecha_hora:data.fecha_hora
    };
    errors.value = {};
    registerModalInfo.show();
  } catch (error) {
    console.log(error);
  }
};

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

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

const deleteIngresoMercancia = async () => {
  try {
    const response = await IngresoMercanciaRepository.deleteIngresoMercancia(editedIndex.value);
    showMessage('Eliminado correctamente');
    closeDelete();
    initialize();
    await getIngresoMercanciaAll('si');
  } catch (error) {
    if (axios.isAxiosError(error)) errors.value = error.response.data.errors;
    console.log(error);
  }
};

const agregarProducto = (id,nombre) => {
    form.value.producto_id=id;
    nombre_producto.value=nombre;
    modal_index_productos.hide();
}

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

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

const initializeCreate = () => {
    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,
        producto_id: null,
        costo: 0,
        cantidad: 1,
        observacion: "",
    };
    errors.value = {};
    editedIndex.value = -1;
};

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

const getIngresoMercanciaAll = async (inicio="no") => {
    try {
        isLoading.value=true;
        const params={
            search:search.value,
            order:order.value,
            sucursal_id:null,
        }
        if(inicio=="si"){
            page.value=1;
        }
        if(storeState.current_state.sucursal_mode != 0){
            params.sucursal_id=storeState.current_state.sucursal_mode;
        }
        const response = await IngresoMercanciaRepository.getPage(page.value,pageSize.value,params);
        obtener_entradas.value = response.data.data;
        totalPages.value= response.data.total;
        pageSize.value= response.data.per_page;
        isLoading.value=false;
    } catch (error) {
        console.log(error);
    }
};

const abrirProductos = async()=>{
    isLoading.value = true;
    const response = await ProductoRepository.getAll();
    obtener_productos.value=response.data;
    modal_index_productos.show();
    isLoading.value = false;
};

const getSucursalAll = async () => {
    try {
        const response = await SucursalRepository.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 initialize = async () => {
    search.value = "";
    isLoading.value = true;
    page.value = 1;
    pageSize.value = 20;
    totalPages.value = 0;
    is_entrada.value = false;
    order.value={
        name:'razonSocial',
        order:'DESC',
    };
    isLoading.value = false;
};

const refrescar = () => {
    initialize();
    getIngresoMercanciaAll('si');
}

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;
    const model_sucursal = await getSucursalAll();
    optionsSucursales.value = model_sucursal;
    registerModal = new window.bootstrap.Modal(document.getElementById('registerModal'));
    deleteModal = new window.bootstrap.Modal(document.getElementById('deleteModal'));
    modal_index_productos = new window.bootstrap.Modal(
        document.getElementById("modal_index_productos")
    );
    registerModalInfo = new window.bootstrap.Modal(
        document.getElementById("registerModalInfo")
    );
    initialize();
    await getIngresoMercanciaAll('si');
});
</script>
