<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">Ventas en línea por confirmar</h1>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    @click="refrescar"
                                >
                                    Refrescar
                                </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_ventas"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #total="item">
                                {{ currency(item.row.total) }}
                            </template>
                            <template #ver="item">
                                <button class="btn btn-success btn-sm mt-1" @click="getVentaId(item.row.id)">
                                    Ver Compra&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>
                            <template #comprobante_pago="item">
                                <button 
                                    v-if="!item.row.comprobante_pago && item.row.opcion_pago_transferencia_id"
                                    class="btn btn-danger btn-sm mt-1"
                                >
                                    Sin comprobante pago&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>
                                <a 
                                    :href="item.row.comprobante_pago_path" 
                                    target="_blank" 
                                    v-if="item.row.comprobante_pago" 
                                    class="btn btn-primary btn-sm mt-1">
                                    Comprobante pago
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="ms-1">
                                        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                        <polyline points="7 10 12 15 17 10"/>
                                        <line x1="12" y1="15" x2="12" y2="3"/>
                                    </svg>
                                </a>
                            </template>
                            <template #cancelar="item">
                                <button class="btn btn-black btn-sm" @click="getVentaCanId(item.row.id)" v-show="item.row.puede_cancelar == 'si'">
                                    Cancelar&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-x" data-v-5522efca=""><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                                </button>
                                <button class="btn btn-danger" v-show="item.row.cancelado == 'si'">
                                    Cancelado&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-x" data-v-5522efca=""><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                                </button>
                                <br
                                v-if="item.row.comprobante_pago && item.row.cancelado != 'si'"
                                >
                                <button 
                                    v-if="item.row.comprobante_pago && item.row.cancelado != 'si'"
                                    class="btn btn-primary btn-sm mt-1" 
                                    @click="getVentaIdAutorizar(item.row.id)"
                                >
                                    Autorizar&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-check">
                                        <path d="M20 6L9 17l-5-5"></path>
                                    </svg>
                                </button>
                            </template>
                            <template #envios="item">
                                <button 
                                    v-if="item.row.comprobante_pago && item.row.cancelado != 'si'"
                                    class="btn btn-primary btn-sm mt-1" 
                                    @click="getVentaIdRellenarEnvio(item.row.id)"
                                >
                                    Rellenar envio&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-truck">
                                        <rect x="1" y="3" width="15" height="13"></rect>
                                        <polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon>
                                        <circle cx="5.5" cy="18.5" r="2.5"></circle>
                                        <circle cx="18.5" cy="18.5" r="2.5"></circle>
                                    </svg>
                                </button>
                            </template>
                            <template #actions="item">
                                <button
                                    class="btn btn-dark btn-sm mt-1" 
                                    @click="abrir_ticket(item.row.id)"
                                >
                                    Ticket&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-ticket">
                                        <rect x="2" y="4" width="20" height="16" rx="2" ry="2"></rect>
                                        <line x1="8" y1="4" x2="8" y2="20" stroke-dasharray="4 4"></line>
                                        <circle cx="8" cy="8" r="1.5" fill="currentColor" stroke="none"></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="getVentasAll" :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">Ver detalle de compra</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <!-- Header con información principal -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <div>
                                        <h4 class="mb-1">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-primary me-2">
                                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                                <polyline points="14,2 14,8 20,8"/>
                                                <line x1="16" y1="13" x2="8" y2="13"/>
                                                <line x1="16" y1="17" x2="8" y2="17"/>
                                                <polyline points="10,9 9,9 8,9"/>
                                            </svg>
                                            Venta #{{ dataPreview.id }}
                                        </h4>
                                        <p class="text-muted mb-0">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-1">
                                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                                                <line x1="16" y1="2" x2="16" y2="6"/>
                                                <line x1="8" y1="2" x2="8" y2="6"/>
                                                <line x1="3" y1="10" x2="21" y2="10"/>
                                            </svg>
                                            {{ dataPreview.fecha_asignada_custom }}
                                        </p>
                                    </div>
                                    <div v-if="dataPreview.cancelado=='si'" class="text-end">
                                        <span class="badge bg-danger fs-6">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-1">
                                                <circle cx="12" cy="12" r="10"/>
                                                <line x1="15" y1="9" x2="9" y2="15"/>
                                                <line x1="9" y1="9" x2="15" y2="15"/>
                                            </svg>
                                            Cancelada
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Información del cliente y sucursal -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="card border-0 bg-light">
                                    <div class="card-body p-3">
                                        <h6 class="card-title text-primary mb-2">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                                                <circle cx="12" cy="7" r="4"/>
                                            </svg>Cliente
                                        </h6>
                                        <p class="card-text mb-0" v-if="dataPreview.cliente">
                                            {{ dataPreview.cliente.razonSocial }}
                                        </p>
                                        <p class="card-text text-muted mb-0" v-else>
                                            Cliente general
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card border-0 bg-light">
                                    <div class="card-body p-3">
                                        <h6 class="card-title text-primary mb-2">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                                                <polyline points="9,22 9,12 15,12 15,22"/>
                                            </svg>Sucursal
                                        </h6>
                                        <p class="card-text mb-0">
                                            {{ dataPreview.sucursal.nombre }}
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Detalles de productos -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-header bg-primary text-white">
                                        <h6 class="mb-0">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <circle cx="9" cy="21" r="1"/>
                                                <circle cx="20" cy="21" r="1"/>
                                                <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>
                                            </svg>Productos
                                        </h6>
                                    </div>
                                    <div class="card-body p-0">
                                        <div class="table-responsive">
                                            <table class="table table-hover mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th class="border-0">Producto</th>
                                                        <th class="border-0 text-center" width="120">Cantidad</th>
                                                        <th class="border-0 text-end" width="120">Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr v-for="(item, i) in dataPreview.venta_detalle" :key="i">
                                                        <td class="border-0">
                                                            <div class="d-flex align-items-center">
                                                                <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                                        <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
                                                                        <polyline points="3.27,6.96 12,12.01 20.73,6.96"/>
                                                                        <line x1="12" y1="22.08" x2="12" y2="12"/>
                                                                    </svg>
                                                                </div>
                                                                <div>
                                                                    <h6 class="mb-0">{{ item.descripcion }}</h6>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td class="border-0 text-center">
                                                            <span class="badge bg-secondary fs-6">{{ item.cantidad }}</span>
                                                        </td>
                                                        <td class="border-0 text-end">
                                                            <strong class="text-success">{{ currency(item.total) }}</strong>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                                <tfoot class="table-light">
                                                    <tr>
                                                        <td class="border-0 text-end">
                                                            <strong>Subtotal:</strong>
                                                        </td>
                                                        <td class="border-0 text-end">
                                                            <strong>{{ currency(dataPreview.subtotal) }}</strong>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="border-0 text-end">
                                                            <strong>IVA:</strong>
                                                        </td>
                                                        <td class="border-0 text-end">
                                                            <strong>{{ currency(dataPreview.iva) }}</strong>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="2" class="border-0 text-end">
                                                            <h5 class="mb-0">Total:</h5>
                                                        </td>
                                                        <td class="border-0 text-end">
                                                            <h4 class="mb-0 text-success">{{ currency(dataPreview.total) }}</h4>
                                                        </td>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Mensaje de cancelación -->
                        <div v-if="dataPreview.cancelado=='si'" class="row mb-4">
                            <div class="col-12">
                                <div class="alert alert-danger border-0 shadow-sm">
                                    <div class="d-flex align-items-center">
                                        <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="me-3">
                                            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                                            <line x1="12" y1="9" x2="12" y2="13"/>
                                            <line x1="12" y1="17" x2="12.01" y2="17"/>
                                        </svg>
                                        <div>
                                            <h6 class="alert-heading mb-1">Venta Cancelada</h6>
                                            <p class="mb-0">{{ dataPreview.observacion_cancelado }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Información de envío -->
                        <div v-if="dataPreview.id && dataPreview.envio" class="row mb-4">
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-header bg-info text-white">
                                        <h6 class="mb-0">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <rect x="1" y="3" width="15" height="13"/>
                                                <polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/>
                                                <circle cx="5.5" cy="18.5" r="2.5"/>
                                                <circle cx="18.5" cy="18.5" r="2.5"/>
                                            </svg>Información de Envío
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-3 mb-3">
                                                <div class="text-center">
                                                    <div class="bg-info rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2" style="width: 35px; height: 35px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <rect x="1" y="3" width="15" height="13"/>
                                                            <polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/>
                                                            <circle cx="5.5" cy="18.5" r="2.5"/>
                                                            <circle cx="18.5" cy="18.5" r="2.5"/>
                                                        </svg>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Paquetería</h6>
                                                    <p class="mb-0 fw-bold">{{ dataPreview.envio.paqueteria }}</p>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <div class="text-center">
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2" style="width: 35px; height: 35px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <path d="M3 5v14"/>
                                                            <path d="M8 5v14"/>
                                                            <path d="M13 5v14"/>
                                                            <path d="M18 5v14"/>
                                                            <path d="M21 5v14"/>
                                                        </svg>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Número de Guía</h6>
                                                    <p class="mb-0 fw-bold">{{ dataPreview.envio.numero_guia }}</p>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <div class="text-center">
                                                    <div class="bg-success rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2" style="width: 35px; height: 35px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                                                            <line x1="16" y1="2" x2="16" y2="6"/>
                                                            <line x1="8" y1="2" x2="8" y2="6"/>
                                                            <line x1="3" y1="10" x2="21" y2="10"/>
                                                            <path d="M9 16l2 2 4-4"/>
                                                        </svg>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Fecha de Envío</h6>
                                                    <p class="mb-0 fw-bold">{{ dataPreview.envio.fecha_envio_custom }}</p>
                                                </div>
                                            </div>
                                            <div class="col-md-3 mb-3">
                                                <div class="text-center">
                                                    <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center mx-auto mb-2" style="width: 35px; height: 35px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <circle cx="12" cy="12" r="10"/>
                                                            <polyline points="12,6 12,12 16,14"/>
                                                        </svg>
                                                    </div>
                                                    <h6 class="text-muted mb-1">Entrega Estimada</h6>
                                                    <p class="mb-0 fw-bold">{{ dataPreview.envio.fecha_entrega_estimada_custom }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Dirección de entrega -->
                        <div v-if="dataPreview.id && dataPreview.direccion" class="row mb-4">
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-header bg-warning text-dark">
                                        <h6 class="mb-0">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
                                                <circle cx="12" cy="10" r="3"/>
                                            </svg>Dirección de Entrega
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <path d="M3 3h18v18H3zM7 7h10v10H7z"/>
                                                            <path d="M9 9h6v6H9z"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Dirección</h6>
                                                        <p class="mb-0 fw-bold">
                                                            {{ dataPreview.direccion.calle }} 
                                                            #{{ dataPreview.direccion.numero_exterior }}
                                                            <span v-if="dataPreview.direccion.numero_interior">Int. {{ dataPreview.direccion.numero_interior }}</span>
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                                                            <polyline points="9,22 9,12 15,12 15,22"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Colonia</h6>
                                                        <p class="mb-0 fw-bold">{{ dataPreview.direccion.colonia }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
                                                            <line x1="8" y1="21" x2="16" y2="21"/>
                                                            <line x1="12" y1="17" x2="12" y2="21"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Código Postal</h6>
                                                        <p class="mb-0 fw-bold">{{ dataPreview.direccion.codigo_postal }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6" v-if="dataPreview.direccion.referencia">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <circle cx="12" cy="12" r="10"/>
                                                            <path d="M12 16v-4"/>
                                                            <path d="M12 8h.01"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Referencia</h6>
                                                        <p class="mb-0 fw-bold">{{ dataPreview.direccion.referencia }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Datos fiscales -->
                        <div v-if="dataPreview.id && dataPreview.datos_fiscales" class="row mb-4">
                            <div class="col-12">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-header bg-success text-white">
                                        <h6 class="mb-0">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-2">
                                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                                <polyline points="14,2 14,8 20,8"/>
                                                <line x1="16" y1="13" x2="8" y2="13"/>
                                                <line x1="16" y1="17" x2="8" y2="17"/>
                                                <polyline points="10,9 9,9 8,9"/>
                                            </svg>Datos Fiscales
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-success rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
                                                            <line x1="8" y1="21" x2="16" y2="21"/>
                                                            <line x1="12" y1="17" x2="12" y2="21"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">RFC</h6>
                                                        <p class="mb-0 fw-bold">{{ dataPreview.datos_fiscales.rfc }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-success rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
                                                            <polyline points="9,22 9,12 15,12 15,22"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Razón Social</h6>
                                                        <p class="mb-0 fw-bold">{{ dataPreview.datos_fiscales.razon_social }}</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="d-flex align-items-start mb-3">
                                                    <div class="bg-success rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 30px; height: 30px;">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-white">
                                                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                                                            <polyline points="14,2 14,8 20,8"/>
                                                            <line x1="16" y1="13" x2="8" y2="13"/>
                                                            <line x1="16" y1="17" x2="8" y2="17"/>
                                                            <polyline points="10,9 9,9 8,9"/>
                                                        </svg>
                                                    </div>
                                                    <div>
                                                        <h6 class="text-muted mb-1">Constancia</h6>
                                                        <a 
                                                            :href="dataPreview.datos_fiscales.documento_fiscal_path" 
                                                            target="_blank" 
                                                            v-if="dataPreview.datos_fiscales.documento_fiscal" 
                                                            class="btn btn-success btn-sm">
                                                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="me-1">
                                                                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                                                                <polyline points="7 10 12 15 17 10"/>
                                                                <line x1="12" y1="15" x2="12" y2="3"/>
                                                            </svg>
                                                            Descargar
                                                        </a>
                                                        <span v-else class="text-muted">No disponible</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register pago ticket -->
        <div
            class="modal fade"
            id="registerticket"
            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">Ticket</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <div ref="ticketRef" style="background: white;">
                            <div class="row justify-content-md-center">
                                <div class="col-xl-5 col-lg-5 col-sm-5">
                                    <div id="printable-content-ticket">
                                        <table style="padding-right: 20px !important;">
                                            <tbody style="font-size: 12px;">
                                                <tr>
                                                    <th colspan="3" class="empresa-nombre">
                                                        <img
                                                            src="@/assets/images/default/logo_negro.png"
                                                            class="navbar-logo"
                                                            alt="logo"
                                                        />
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="3" class="empresa-direccion" v-if="dataPreview.sucursal" style="text-align: center; margin: 0 0 0 0 !important; padding: 0 0 0 0 !important;">
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">{{ dataPreview.sucursal.direccion }}</p>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="3" class="folio-fecha" style="text-align: center; margin: 0 0 0 0 !important; padding: 0 0 0 0 !important;">
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">F-{{ dataPreview.id }} - {{ dataPreview.fecha_asignada_custom }}</p>
                                                    </th>
                                                </tr>
                                                <tr style="border-bottom: 1px dashed; border-top: 1px dashed;">
                                                    <td width="50%">
                                                        Producto
                                                    </td>
                                                    <td>
                                                        Cant.
                                                    </td>
                                                    <td style="text-align: right;">
                                                        precio
                                                    </td>
                                                </tr>
                                            </tbody>
                                            <tbody v-for="(item, i) in dataPreview.venta_detalle" style="font-size: 12px;">
                                                <tr>
                                                    <td colspan="3" width="100%" class="descripcion-producto">
                                                        {{ item.descripcion }}
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td>

                                                    </td>
                                                    <td width="10%" style="text-align: center;">
                                                        {{ item.cantidad }}
                                                    </td>
                                                    <td width="30%" style="text-align: right;">
                                                        {{ currency(item.total) }}
                                                    </td>
                                                </tr>
                                            </tbody>
                                            <tfoot style="font-size: 12px;">
                                                <tr>
                                                    <td colspan="3" style="border-bottom: 1px dashed;"></td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2" class="total" style="text-align: left;">
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">Total</p>
                                                    </td>
                                                    <td colspan="1" class="total" style="text-align: right;">
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">{{ currency(dataPreview.total) }}</p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" style="border-bottom: 1px dashed;"></td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" style="border-bottom: 1px dashed;"></td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" class="footer" style="text-align: center;">
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">¡GRACIAS POR SU VISITA!</p>
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">ESTE COMPROBANTE NO TIENE</p>
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">VALIDEZ FISCAL</p>
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">POR FAVOR REVISE SUS PRODUCTOS</p>
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">YA QUE NO SE ACEPTAN</p>
                                                        <p style="margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; font-size: 12px;">RECLAMACIONES NI DEVOLUCIONES</p>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" style="border-bottom: 1px dashed;"></td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" style="border-bottom: 1px dashed;"></td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group mt-2">
                            <button
                                type="button"
                                class="btn btn-black w-100"
                                @click="printContent('printable-content-ticket')"
                            >
                                Imprimir
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Register pago vale -->
        <div
            class="modal fade"
            id="registervale"
            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">Vale</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <div v-for="(item, i) in dataPreview.venta_detalle">
                            <div v-if="item.vale_id">
                                <div :id="'printable-content-vale-'+item.vale_id">
                                    <div class="row justify-content-md-center">
                                        <div class="col-xl-6 col-lg-6 col-sm-6">
                                            <table style="padding-right: 20px !important;">
                                                <tr>
                                                    <th colspan="3" style="text-align: center;">
                                                        <img
                                                            src="@/assets/images/default/logo_negro.png"
                                                            class="navbar-logo"
                                                            alt="logo"
                                                        />
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th style="text-align: left; padding-right: 10px;">
                                                        <b>Vigencia: </b>{{ moment(new Date(item.vale.vigencia)).format("D-MM-YYYY") }}
                                                    </th>
                                                    <th></th>
                                                    <th style="text-align: right; padding-right: 10px;">
                                                        <b>Folio:</b>{{ item.vale_id }}
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="3" style="text-align: center;">
                                                        <b><h3>Vale</h3></b>
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <th colspan="3" style="text-align: center;">
                                                        <QRCodeVue3
                                                                :key="item.vale.token"
                                                                :width="200"
                                                                :height="200"
                                                                :value="item.vale.token"
                                                                :qrOptions="{ typeNumber: 0, mode: 'Byte', errorCorrectionLevel: 'H' }"
                                                                :imageOptions="{ hideBackgroundDots: true, imageSize: 0.4, margin: 0 }"
                                                                :dotsOptions="{
                                                                    type: 'square',
                                                                    color: '#000000',
                                                                    gradient: {
                                                                    type: 'linear',
                                                                    rotation: 0,
                                                                    colorStops: [
                                                                        { offset: 0, color: '#000000' },
                                                                        { offset: 1, color: '#000000' },
                                                                    ],
                                                                    },
                                                                }"
                                                                :backgroundOptions="{ color: '#ffffff' }"
                                                                :cornersSquareOptions="{ type: 'dot', color: '#000000' }"
                                                                :cornersDotOptions="{ type: undefined, color: '#000000' }"
                                                                fileExt="png"
                                                                :download="false"
                                                                myclass="my-qur"
                                                                imgclass="img-qr"
                                                                downloadButton="my-button"
                                                                :downloadOptions="{ name: 'vqr', extension: 'png' }"
                                                        />
                                                    </th>
                                                </tr>
                                                <tr>
                                                    <td colspan="3">&nbsp;</td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" style="text-align: center; margin-top: 100px; font-size: 9px !important;">
                                                        <p>El Vale no es reembolsable ni canjeable por dinero en efectivo en todo o en
                                                        parte, y no se emiten reembolsos por cualquier saldo no utilizado. Es de un
                                                        solo uso y queda invalidado.</p>
                                                        <p>El Vale no puede ser combinado con otras promociones, descuentos u ofertas
                                                        especiales y está prohibida su reventa.</p>
                                                        <p>La reserva de citas para utilizar el Vale está sujeta a disponibilidad y se
                                                        recomienda hacer la reserva con anticipación.</p>
                                                        <p>En caso de pérdida o uso del vale sin consentimiento, no se proporcionará
                                                        sustitución.</p>
                                                        <p>Válido por un mes al día de su compra.</p>
                                                        <p>Clínica Egurrola se reserva el derecho de modificar estos términos y
                                                        condiciones en cualquier momento sin previo aviso.</p>
                                                    </td>
                                                </tr>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group mt-2">
                                    <button
                                        type="button"
                                        class="btn btn-black w-100"
                                        @click="printContent('printable-content-vale-'+item.vale_id, 'vale')"
                                    >
                                        Imprimir
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Cancelar Modal -->
        <div
            class="modal fade"
            id="cancelarModal"
            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 Cancelar esta venta?
                        </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="row">
                            <div class="col-md-12">
                                <div class="form-group mb-4">
                                    <label class="">Observación:</label>
                                    <textarea
                                        v-model="form.observacion_cancelado"
                                        :class="[
                                            is_entrada
                                                ? !errors.observacion_cancelado
                                                    ? 'form-control flatpickr active is-valid'
                                                    : 'form-control flatpickr active is-invalid'
                                                : 'form-control flatpickr active',
                                        ]"
                                        placeholder="Agregar observación"
                                        rows="3"
                                    ></textarea>
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.observacion_cancelado">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </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="canceladoVenta()"
                        >
                            Aceptar
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <!-- The Modal autorizar -->
        <div
            id="autorizarModal"
            class="modal fade"
            aria-labelledby="exampleModalLabelAutorizar"
            aria-hidden="true"
        >
            <div class="modal-dialog modal-md">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabelAutorizar">
                            Autorizar venta
                        </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="row">
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Autorizar</label>
                                    <multiselect
                                        v-model="formAutorizar.es_pago_tienda"
                                        mode="tags"
                                        :close-on-select="true"
                                        :searchable="true"
                                        :options="optionsAutorizar"
                                        :class="[
                                            is_entrada
                                                ? !errors.es_pago_tienda
                                                    ? 'is-valid'
                                                    : 'is-invalid'
                                                : '',
                                        ]"
                                        selected-label=""
                                        select-label=""
                                        deselect-label=""
                                        placeholder="Seleccione..."
                                        :showNoOptions="false"
                                        :showNoResults="false"
                                    >
                                    </multiselect>
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.es_pago_tienda">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button
                            class="btn btn-black w-100"
                            v-show="editedIndex  !== -1"
                            @click="autorizarVenta()"
                        >
                            Actualizar
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <!-- The Modal rellenar envio -->
        <div
            id="rellenarEnvioModal"
            class="modal fade"
            aria-labelledby="exampleModalLabelRellenarEnvio"
            aria-hidden="true"
        >
            <div class="modal-dialog modal-md">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabelRellenarEnvio">
                            Rellenar envio
                        </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="row">
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Paqueteria</label>
                                    <input
                                        type="text"
                                        class="form-control mb-2"
                                        placeholder="Paqueteria"
                                        v-model="formRellenarEnvio.paqueteria"
                                        :class="[is_entrada ? (!errors.paqueteria ? 'is-valid' : 'is-invalid') : '']"
                                    />
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.paqueteria">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Numero de guia</label>
                                    <input
                                        type="text"
                                        class="form-control mb-2"
                                        placeholder="Numero de guia"
                                        v-model="formRellenarEnvio.numero_guia"
                                        :class="[is_entrada ? (!errors.numero_guia ? 'is-valid' : 'is-invalid') : '']"
                                    />
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.numero_guia">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Fecha de envio</label>
                                    <flat-pickr
                                        v-model="formRellenarEnvio.fecha_envio"
                                        :config="{
                                            dateFormat: 'Y-m-d',
                                        }"
                                        class="form-control flatpickr active"
                                    ></flat-pickr>
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.fecha_envio">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Fecha de entrega estimada</label>
                                    <flat-pickr
                                        v-model="formRellenarEnvio.fecha_entrega_estimada"
                                        :config="{
                                            dateFormat: 'Y-m-d',
                                        }"
                                        class="form-control flatpickr active"
                                    ></flat-pickr>
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.fecha_entrega_estimada">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button
                            class="btn btn-black w-100"
                            @click="rellenarEnvio()"
                        >
                            Guardar
                        </button>
                    </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="getVentasAll('si')"
        ></button>
    </div>
</template>
<style>
.table3 .actions svg {
    padding: 2px;
}
#printable-content-ticket,
[id^="printable-content-vale-"] {
    width: 80mm;
    font-family: Arial, sans-serif;
    font-size: 20px;
    line-height: 1.5;
    font-weight: bold;
    color: rgb(0, 0, 0) !important;
    -webkit-text-fill-color: rgb(0, 0, 0) !important;
}

@media print {
    @page {
        size: 80mm auto;
        margin: 0;
    }

    body * {
        visibility: hidden;
    }

    #printable-content-ticket,
    #printable-content-ticket * {
        visibility: visible;
        font-family: Arial, sans-serif !important;
        color: rgb(0, 0, 0) !important;
        -webkit-text-fill-color: rgb(0, 0, 0) !important;
        text-shadow: none !important;
        font-weight: bold !important;
        filter: none !important;
    }

    #printable-content-ticket {
        position: absolute;
        left: 0;
        top: 0;
        width: 72mm !important;
        max-width: none !important;
        padding: 0;
        margin: 0;
        transform: scale(1);
    }

    #printable-content-ticket table {
        width: 100% !important;
        table-layout: fixed !important;
        border-collapse: collapse;
        margin: 0;
        padding: 0;
    }

    #printable-content-ticket td,
    #printable-content-ticket th,
    #printable-content-ticket p,
    #printable-content-ticket span,
    #printable-content-ticket div,
    #printable-content-ticket h1,
    #printable-content-ticket h2,
    #printable-content-ticket h3,
    #printable-content-ticket h4,
    #printable-content-ticket h5,
    #printable-content-ticket h6 {
        padding: 2mm 1mm;
        font-size: 22px !important;
        line-height: 1.5 !important;
        font-weight: bold !important;
        white-space: normal;
        word-wrap: break-word;
        color: rgb(0, 0, 0) !important;
        -webkit-text-fill-color: rgb(0, 0, 0) !important;
    }

    #printable-content-ticket h1 {
        font-size: 28px !important;
    }
    #printable-content-ticket h2 {
        font-size: 26px !important;
    }
    #printable-content-ticket h3 {
        font-size: 24px !important;
    }
}
</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 VentaRepository from "@/repositories/VentaRepository";
import Pagination from 'v-pagination-3';
import QRCodeVue3 from "qrcode-vue3";

import { useStateStore } from '@/store/StateStore';

import qr_presentacion from "@/assets/images/default/qr_presentacion.png";
// 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";
import moment from "moment";
import { imprimirConConfiguracion, imprimirTicketDirecto, imprimirValeDirecto } from "@/repositories/ImpresionRepository";

// 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);

useMeta({ title: "EGURROLA" });

const urls = ref(process.env.MIX_URL);
const store = useAuthStore();
const storeState = useStateStore();
const obtener_ventas = ref([]);

//formulario crear y eliminar
let registerModal = ref(false);
let registerticket = ref(null);
let registervale = ref(null);
let cancelarModal = ref(null);
let autorizarModal = ref(null);
let rellenarEnvioModal = ref(null);
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 errors = ref({});
const dataPreview = ref({
    nombre:'',
    descripcion:'',
    precio:'',
    sucursal:'',
    iva:'',
    ieps:'',
    cantidad_existente:'',
    cantidad_vendido:'',
    path:'',
});
const form = ref({
    observacion_cancelado:''
});
const error = ref({
    observacion_cancelado:''
});
const formatter = new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'});

const formRellenarEnvio = ref({
    paqueteria:'',
    numero_guia:'',
    fecha_envio:'',
    fecha_entrega_estimada:'',
});

//table 2
const columns1 = ref([
    "id",
    "fecha_asignada_custom",
    "sucursal",
    "cliente",
    "total",
    "ver",
    "comprobante_pago",
    "cancelar",
    "envios",
    "actions",
]);
const table_option1 = ref({
    headings: {
        fecha_asignada_custom: (h, row, index) => {
            return "Fecha registro";
        },
        id: (h, row, index) => {
            return "Folio";
        },
        comprobante_pago: (h, row, index) => {
            return "Comprobante de pago";
        },
        actions: (h, row, index) => {
            return "Imprimir";
        },
        cancelar: (h, row, index) => {
            return "Acciones";
        },
        ver: (h, row, index) => {
            return "Ver";
        },
        envios: (h, row, index) => {
            return "Envios";
        },
    },
    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:",
    }
});

const optionsAutorizar = ref(['si','no']);
const formAutorizar = ref({
    es_pago_tienda:'si'
});

const getVentaId = async (id) => {
    try {
        isLoading.value = true;
        const response = await VentaRepository.getVentaId(id);
        dataPreview.value = response.data;
        editedIndex.value = id;
        registerModal.show();
        isLoading.value = false;
    } catch (error) {
        console.log(error);S
        isLoading.value = false;
    }
};

const getVentaIdAutorizar = async (id) => {
    try {
        isLoading.value = true;
        const response = await VentaRepository.getVentaId(id);
        dataPreview.value = response.data;
        editedIndex.value = id;
        autorizarModal.show();
        isLoading.value = false;
    } catch (error) {
        console.log(error);S
        isLoading.value = false;
    }
};

const getVentaIdRellenarEnvio = async (id) => {
    try {
        isLoading.value = true;
        const response = await VentaRepository.getVentaId(id);
        dataPreview.value = response.data;
        if(dataPreview.value.envio){
            formRellenarEnvio.value.paqueteria = dataPreview.value.envio.paqueteria;
            formRellenarEnvio.value.numero_guia = dataPreview.value.envio.numero_guia;
            formRellenarEnvio.value.fecha_envio = dataPreview.value.envio.fecha_envio;
            formRellenarEnvio.value.fecha_entrega_estimada = dataPreview.value.envio.fecha_entrega_estimada;
            editedIndex.value = dataPreview.value.envio.id;
        } else {
            formRellenarEnvio.value.paqueteria = '';
            formRellenarEnvio.value.numero_guia = '';
            formRellenarEnvio.value.fecha_envio = '';
            formRellenarEnvio.value.fecha_entrega_estimada = '';
        }
        rellenarEnvioModal.show();
        isLoading.value = false;
    } catch (error) {
        console.log(error);
        isLoading.value = false;
    }
};

const abrir_vale = async (id) => {
    isLoading.value = true;
    const response = await VentaRepository.getVentaId(id);
    dataPreview.value = response.data;
    editedIndex.value = id;
    isLoading.value = false;
    registervale.show();
}

const abrir_ticket = async (id) => {
    isLoading.value = true;
    const response = await VentaRepository.getVentaId(id);
    dataPreview.value = response.data;
    editedIndex.value = id;
    isLoading.value = false;
    registerticket.show();
}

// Función de impresión que verifica primero impresora directa, luego configuración por defecto
const printContent = async (content, tipoImpresion = null) => {
    if (!tipoImpresion) {
        if (content.includes('printable-content-vale-')) {
            tipoImpresion = 'vale';
        } else if (content.includes('printable-content-ticket')) {
            tipoImpresion = 'ticket';
        } else {
            tipoImpresion = 'ticket';
        }
    }

    isLoading.value = true;

    try {
        if (tipoImpresion === 'ticket' && dataPreview.value && dataPreview.value.id) {
            try {
                const response = await imprimirTicketDirecto(dataPreview.value.id);
                isLoading.value = false;
                if (response.success) {
                    showMessage('Se pudo enviar la impresión correctamente', 'success');
                    return;
                }
                if (response.fallback) {
                    console.log('No se encontró impresora directa, usando impresión normal');
                } else {
                    showMessage(response.message || 'Error al imprimir', 'error');
                    return;
                }
            } catch (error) {
                console.error('Error al imprimir con impresora directa:', error);
                isLoading.value = false;
            }
        }

        if (tipoImpresion === 'vale') {
            let valeId = null;
            let valeToken = null;

            if (content.includes('printable-content-vale-')) {
                const match = content.match(/printable-content-vale-(\d+)/);
                if (match && match[1]) {
                    valeId = parseInt(match[1]);
                    if (dataPreview.value && dataPreview.value.venta_detalle) {
                        const detalleConVale = dataPreview.value.venta_detalle.find(d => d.vale_id === valeId);
                        if (detalleConVale && detalleConVale.vale && detalleConVale.vale.token) {
                            valeToken = detalleConVale.vale.token;
                        }
                    }
                }
            } else if (dataPreview.value && dataPreview.value.venta_detalle) {
                const detalleConVale = dataPreview.value.venta_detalle.find(d => d.vale_id);
                if (detalleConVale && detalleConVale.vale_id) {
                    valeId = detalleConVale.vale_id;
                    if (detalleConVale.vale && detalleConVale.vale.token) {
                        valeToken = detalleConVale.vale.token;
                    }
                }
            }

            if (valeId) {
                try {
                    const response = await imprimirValeDirecto(valeId, valeToken);
                    isLoading.value = false;
                    if (response.success) {
                        showMessage('Se pudo enviar la impresión correctamente', 'success');
                        return;
                    }
                    if (response.fallback) {
                        console.log('No se encontró impresora directa, usando impresión normal');
                    } else {
                        showMessage(response.message || 'Error al imprimir', 'error');
                        return;
                    }
                } catch (error) {
                    console.error('Error al imprimir con impresora directa:', error);
                    isLoading.value = false;
                }
            }
        }

        await imprimirConConfiguracion(content, tipoImpresion, storeState.current_state.sucursal_mode);
        isLoading.value = false;
    } catch (error) {
        console.error('Error al imprimir con configuración:', error);
        isLoading.value = false;
        printContentOriginal(content);
    }
};

// Función de impresión original como fallback (ventana de impresión del navegador)
const printContentOriginal = (content) => {
    const printableContent = document.getElementById(content);
    const printWindow = window.open('', '_blank', 'height=600,width=800');

    const htmlContent = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Ticket</title>
                <style>
                    @page {
                        size: 80mm auto;
                        margin: 0;
                    }

                    * {
                        color: rgb(0, 0, 0) !important;
                        -webkit-text-fill-color: rgb(0, 0, 0) !important;
                        -webkit-print-color-adjust: exact !important;
                        print-color-adjust: exact !important;
                    }

                    body {
                        margin: 0;
                        padding: 0;
                        width: 88%;
                        font-family: Arial, sans-serif;
                        font-weight: bold;
                    }

                    #${content} {
                        width: 100%;
                        margin: 0;
                        padding: 0;
                    }

                    #${content} table {
                        width: 100%;
                        table-layout: fixed;
                        border-collapse: collapse;
                        margin: 0;
                        padding: 0;
                    }

                    #${content} td,
                    #${content} th,
                    #${content} p,
                    #${content} span,
                    #${content} div,
                    #${content} h1,
                    #${content} h2,
                    #${content} h3,
                    #${content} h4,
                    #${content} h5,
                    #${content} h6 {
                        padding: 2mm 1mm;
                        font-size: 22px;
                        line-height: 1.5;
                        font-weight: bold;
                        white-space: normal;
                        word-wrap: break-word;
                        color: rgb(0, 0, 0) !important;
                        -webkit-text-fill-color: rgb(0, 0, 0) !important;
                    }

                    #${content} h1 {
                        font-size: 28px !important;
                    }
                    #${content} h2 {
                        font-size: 26px !important;
                    }
                    #${content} h3 {
                        font-size: 24px !important;
                    }

                    #${content} img {
                        width: 100%;
                        max-width: none;
                        height: auto;
                        margin: 0 auto;
                        display: block;
                    }

                    @media print {
                        * {
                            color: rgb(0, 0, 0) !important;
                            -webkit-text-fill-color: rgb(0, 0, 0) !important;
                            -webkit-print-color-adjust: exact !important;
                            print-color-adjust: exact !important;
                        }
                        body {
                            width: 88%;
                        }
                    }
                </style>
            </head>
            <body>
                ${printableContent.innerHTML}
                <script>
                    window.onload = function() {
                        window.print();
                        setTimeout(function() {
                            window.close();
                        }, 500);
                    }<\/script>
            </body>
        </html>
    `.trim();

    printWindow.document.write(htmlContent);
    printWindow.document.close();
};

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

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

const getVentasAll = 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 VentaRepository.paginacionTiendaVerificar(page.value,pageSize.value,params);
        obtener_ventas.value = response.data.data;
        totalPages.value= response.data.total;
        pageSize.value= response.data.per_page;
        isLoading.value=false;
    } catch (error) {
        console.log(error);
    }
};

const canceladoVenta = async () => {
    try {
        isLoading.value=true;
        is_entrada.value = true;
        await VentaRepository.canledadoVenta(form.value,editedIndex.value);
        initialize();
        await getVentasAll('si');
        cancelarModal.hide();
        showMessage('Cancelado correctamente');
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
};

const getVentaCanId = (id) => {
    form.value.observacion_cancelado='';
    editedIndex.value = id;
    cancelarModal.show();
};

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',
    };
    form.value.observacion_cancelado='';
    isLoading.value = false;
};

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

const autorizarVenta = async () => {
    try {
        isLoading.value = true;
        await VentaRepository.autorizarVenta(formAutorizar.value, editedIndex.value);
        formAutorizar.value.es_pago_tienda = 'si';
        autorizarModal.hide();
        showMessage('Autorizado correctamente');
        isLoading.value = false;
        await getVentasAll('si');
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
}

const rellenarEnvio = async () => {
    try {
        isLoading.value = true;
        formRellenarEnvio.value.venta_id = dataPreview.value.id;
        if(dataPreview.value.envio){
            await VentaRepository.rellenarEnvioActualizar(formRellenarEnvio.value, editedIndex.value);
        }else{
            await VentaRepository.rellenarEnvioCrear(formRellenarEnvio.value);
        }
        rellenarEnvioModal.hide();
        showMessage('Guardado correctamente');
        isLoading.value = false;
        await getVentasAll('si');
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
}

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

onMounted(async () => {
    const response = await obtener_user();
    store.current_user.id = response.id;
    store.current_user.name = response.name;
    store.current_user.email = response.email;
    registerModal = new window.bootstrap.Modal(document.getElementById('registerModal'));
    registerticket = new window.bootstrap.Modal(
        document.getElementById("registerticket")
    );
    registervale = new window.bootstrap.Modal(
        document.getElementById("registervale")
    );
    cancelarModal = new window.bootstrap.Modal(
        document.getElementById("cancelarModal")
    );
    autorizarModal = new window.bootstrap.Modal(
        document.getElementById("autorizarModal")
    );
    rellenarEnvioModal = new window.bootstrap.Modal(
        document.getElementById("rellenarEnvioModal")
    );
    initialize();
    await getVentasAll('si');
});

</script>
