<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">Cortes Cajas</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"
                                >
                                    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_cortes"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #total="item">
                                {{ currency(item.row.total) }}
                            </template>
                            <template #ver="item">
                                <button class="btn btn-success" @click="getCorteId(item.row.id)">
                                    Ver&nbsp
                                    <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-eye" data-v-5522efca=""><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                                </button>
                            </template>
                        </v-client-table>
                        <div class="VueTables VueTables--client">
                            <div class="text-center">
                                <pagination v-model="page" :records="totalPages" :per-page="pageSize" @paginate="getCorteCajaAll" :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">Realizar corte</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 justify-content-md-center">
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Fecha inicio</label>
                                        <flat-pickr
                                            v-model="form.fecha_inicio"
                                            :config="optionsFecha"
                                            :class="[
                                                is_entrada
                                                    ? !errors.fecha_inicio
                                                        ? 'form-control flatpickr active is-valid'
                                                        : 'form-control flatpickr active is-invalid'
                                                    : 'form-control flatpickr active',
                                            ]"
                                        ></flat-pickr>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.fecha_inicio">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Fecha fin</label>
                                        <flat-pickr
                                            v-model="form.fecha_fin"
                                            :config="optionsFecha"
                                            :class="[
                                                is_entrada
                                                    ? !errors.fecha_fin
                                                        ? 'form-control flatpickr active is-valid'
                                                        : 'form-control flatpickr active is-invalid'
                                                    : 'form-control flatpickr active',
                                            ]"
                                        ></flat-pickr>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.fecha_fin">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </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">
                                        <button
                                            type="button"
                                            class="btn btn-black m-4"
                                            @click="calcularCorteCaja"
                                        >
                                            Calcular
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group mt-2" v-if="form.total > 0">
                                <button
                                    type="button"
                                    class="btn btn-black w-100"
                                    @click="createCorteCaja"
                                >
                                    Aplicar corte
                                </button>
                            </div>
                            <div class="form-group mt-2">
                                <table class="table table-hover table-bordered mt-3">
                                    <thead>
                                        <tr>
                                            <td colspan="5" style="text-align: center;">
                                                <b>Información de las ventas</b>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td><b>Iva:</b></td>
                                            <td colspan="2"><b>Subtotal:</b></td>
                                            <td colspan="2"><b>Total:</b></td>
                                        </tr>
                                        <tr>
                                            <td>{{ currency(form.subtotal) }}</td>
                                            <td colspan="2">{{ currency(form.subtotal) }}</td>
                                            <td colspan="2">{{ currency(form.total) }}</td>
                                        </tr>
                                        <tr>
                                            <td><b>Efectivo:</b></td>
                                            <td><b>Tarjeta D.:</b></td>
                                            <td><b>Tarjeta C.:</b></td>
                                            <td><b>Credito.:</b></td>
                                        </tr>
                                        <tr>
                                            <td>{{ currency(form.total_efectivo) }}</td>
                                            <td>{{ currency(form.total_tarjeta_debito) }}</td>
                                            <td>{{ currency(form.total_tarjeta_credito) }}</td>
                                            <td>{{ currency(form.total_credito) }}</td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" style="text-align: center;"><b>Lista de ventas</b></td>
                                        </tr>
                                        <tr>
                                            <td><b>Fecha</b></td>
                                            <td><b>Folio</b></td>
                                            <td><b>Iva</b></td>
                                            <td><b>Subtotal</b></td>
                                            <td><b>total</b></td>
                                        </tr>
                                    </thead>
                                    <tbody v-for="(item, i) in dataPreviewVentas">
                                        <tr>
                                            <td>
                                                {{ item.fecha_asignada_custom }}
                                            </td>
                                            <td>
                                                {{ item.id }}
                                            </td>
                                            <td>
                                                {{ currency(item.iva) }}
                                            </td>
                                            <td>
                                                {{ currency(item.subtotal) }}
                                            </td>
                                            <td>
                                                {{ currency(item.total) }}
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="form-group mt-2" v-if="form.total > 0">
                                <button
                                    type="button"
                                    class="btn btn-black w-100"
                                    @click="createCorteCaja"
                                >
                                    Aplicar corte
                                </button>
                            </div>
                        </form>
                    </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">
                                <table class="table table-hover table-bordered">
                                    <thead>
                                        <tr>
                                            <td colspan="5" style="text-align: center;">
                                                <b>Información de las ventas</b>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td colspan="3"><b>Fecha inicio:</b></td>
                                            <td colspan="2"><b>Fecha fin:</b></td>
                                        </tr>
                                        <tr>
                                            <td colspan="3">{{ dataPreview.fecha_inicio_custom}}</td>
                                            <td colspan="2">{{ dataPreview.fecha_fin_custom}}</td>
                                        </tr>
                                        <tr>
                                            <td><b>Iva:</b></td>
                                            <td colspan="2"><b>Subtotal:</b></td>
                                            <td colspan="2"><b>Total:</b></td>
                                        </tr>
                                        <tr>
                                            <td>{{ currency(dataPreview.subtotal) }}</td>
                                            <td colspan="2">{{ currency(dataPreview.subtotal) }}</td>
                                            <td colspan="2">{{ currency(dataPreview.total) }}</td>
                                        </tr>
                                        <tr>
                                            <td><b>Efectivo:</b></td>
                                            <td><b>Tarjeta D.:</b></td>
                                            <td><b>Tarjeta C.:</b></td>
                                            <td><b>Credito.:</b></td>
                                        </tr>
                                        <tr>
                                            <td>{{ currency(dataPreview.total_efectivo) }}</td>
                                            <td>{{ currency(dataPreview.total_tarjeta_debito) }}</td>
                                            <td>{{ currency(dataPreview.total_tarjeta_credito) }}</td>
                                            <td>{{ currency(dataPreview.total_credito) }}</td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" style="text-align: center;"><b>Lista de ventas</b></td>
                                        </tr>
                                        <tr>
                                            <td><b>Fecha</b></td>
                                            <td><b>Folio</b></td>
                                            <td><b>Iva</b></td>
                                            <td><b>Subtotal</b></td>
                                            <td><b>total</b></td>
                                        </tr>
                                    </thead>
                                    <tbody v-for="(item, i) in dataPreview.venta">
                                        <tr>
                                            <td>
                                                {{ item.venta.fecha_asignada_custom }}
                                            </td>
                                            <td>
                                                {{ item.venta.id }}
                                            </td>
                                            <td>
                                                {{ currency(item.venta.iva) }}
                                            </td>
                                            <td>
                                                {{ currency(item.venta.subtotal) }}
                                            </td>
                                            <td>
                                                {{ currency(item.venta.total) }}
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </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="getCorteCajaAll"
        ></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 CorteCajaRepository from "@/repositories/CorteCajaRepository";
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';

//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);
import moment from "moment";

import axios from "axios";

useMeta({ title: "EGURROLA" });

const optionsFecha = ref({
    enableTime: true,
    dateFormat: 'Y-m-d H:i',
    time_24hr: false,
    minTime: '08:00:00',
    maxTime: '19:00:00',
    minuteIncrement:60,
});

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

//formulario crear y eliminar
let registerModal = 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,
    venta_id_temp: [],
    total: 0,
    subtotal: 0,
    iva: 0,
    ieps: 0,
    total_efectivo: 0,
    total_tarjeta_debito: 0,
    total_tarjeta_credito: 0,
    total_tranferencia: 0,
    total_credito: 0,
    fecha_inicio: moment(new Date()).format("YYYY-MM-D")+' 00:00',
    fecha_fin: moment(new Date()).format("YYYY-MM-D")+' 23:00',
});

const dataPreview=ref({});
const dataPreviewVentas=ref([]);

//table 2
const columns1 = ref([
    "id",
    "fecha_inicio_custom",
    "fecha_fin_custom",
    "sucursal",
    "total",
    "ver"
]);
const table_option1 = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        sucursal: (h, row, index) => {
            return "Sucursal";
        },
        fecha_inicio_custom: (h, row, index) => {
            return "Fecha inicio";
        },
        fecha_fin_custom: (h, row, index) => {
            return "Fecha fin";
        },
        ver: (h, row, index) => {
            return "ver";
        }
    },
    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=null) => {
    form.value.sucursal_id = null;
    if(data){
        form.value.sucursal_id = data.id;
    }
};

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

const calcularCorteCaja = async () => {
  try {
    is_entrada.value = true;
    isLoading.value = true;
    const response = await CorteCajaRepository.calcularCorteCaja(form.value);
    form.value.total=response.data.cortes.total;
    form.value.subtotal=response.data.cortes.subtotal;
    form.value.iva=response.data.cortes.iva;
    form.value.total_efectivo=response.data.cortes.total_efectivo;
    form.value.total_tarjeta_debito=response.data.cortes.total_tarjeta_debito;
    form.value.total_tarjeta_credito=response.data.cortes.total_tarjeta_credito;
    form.value.total_credito=response.data.cortes.total_credito;
    form.value.venta_id_temp=response.data.venta_id_temp;
    dataPreviewVentas.value=response.data.ventas;
    showMessage('Calculado correctamente');
    isLoading.value = false;
} catch (error) {
    if (axios.isAxiosError(error)) errors.value = error.response.data.errors;
    isLoading.value = false;
  }
};

const getCorteId = async (id) => {
    try {
        isLoading.value = true;
        const response = await CorteCajaRepository.getCorteCajaId(id);
        dataPreview.value = response.data;
        editedIndex.value = id;
        registerModalInfo.show();
        isLoading.value = false;
    } catch (error) {
        console.log(error);S
        isLoading.value = false;
    }
};

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

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

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,
        venta_id_temp: [],
        total: 0,
        subtotal: 0,
        iva: 0,
        ieps: 0,
        total_efectivo: 0,
        total_tarjeta_debito: 0,
        total_tarjeta_credito: 0,
        total_tranferencia: 0,
        total_credito: 0,
        fecha_inicio: moment(new Date()).format("YYYY-MM-D")+' 00:00',
        fecha_fin: moment(new Date()).format("YYYY-MM-D")+' 23:00',
    };
    dataPreview.value={};
    dataPreviewVentas.value=[];
    errors.value = {};
    editedIndex.value = -1;
};

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

const getCorteCajaAll = 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 CorteCajaRepository.getPage(page.value,pageSize.value,params);
        obtener_cortes.value = response.data.data;
        totalPages.value= response.data.total;
        pageSize.value= response.data.per_page;
        isLoading.value=false;
    } catch (error) {
        console.log(error);
        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:'id',
        order:'DESC',
    };
    isLoading.value = false;
};

const refrescar = () => {
    initialize();
    initializeCreate();
    getCorteCajaAll('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'));
    registerModalInfo = new window.bootstrap.Modal(
        document.getElementById("registerModalInfo")
    );
    initialize();
    initializeCreate();
    await getCorteCajaAll('si');
});
</script>
