<template>
    <div>
        <div
            class="overlay-setting"
            :class="{ show: isOpen }"
            @click="isOpen = !isOpen"
        ></div>

        <div class="app-settings" :class="{ active: isOpen }">
            <a
                v-if="!isUserType('cliente_linea')"
                href="javascript:;"
                id="settingbutton"
                class="setting"
                @click="isOpen = !isOpen"
            >
                <h5 class="mb-0">
                    <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="22"
                        height="22"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        class=""
                    >
                        <circle cx="12" cy="12" r="3"></circle>
                        <path
                            d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"
                        ></path>
                    </svg>
                </h5>
            </a>
            <perfect-scrollbar class="sidbarchat p-3" tag="div">
                <a
                    class="btn-close"
                    href="javascript:;"
                    @click="isOpen = !isOpen"
                >
                </a>
                <div class="text-center">
                    <img
                        src="@/assets/images/logo.png"
                        alt="..."
                        class="img-fluid"
                    />
                </div>
                <h3 class="mb-0 text-center">Control de la app</h3>

                <h6 class="mb-1">sucursales</h6>
                <p class="small text-muted mb-3">Seleccionar la sucursales</p>
                <div class="btn-group-toggle row mx-0">
                    <div
                        class="text-color radio-primary col-6 ps-0 mb-3 custom-control custom-radio"
                    >
                        <input
                            type="radio"
                            id="matriz_mode"
                            v-model="store.current_state.sucursal_mode"
                            class="custom-control-input"
                            value="1"
                            @change="setTemplateStyle"
                        />
                        <label class="custom-control-label" for="matriz_mode">
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                height="1em"
                                viewBox="0 0 384 512"
                            >
                                <path
                                    d="M48 0C21.5 0 0 21.5 0 48V464c0 26.5 21.5 48 48 48h96V432c0-26.5 21.5-48 48-48s48 21.5 48 48v80h96c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48H48zM64 240c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V240zm112-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V240c0-8.8 7.2-16 16-16zm80 16c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H272c-8.8 0-16-7.2-16-16V240zM80 96h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V112c0-8.8 7.2-16 16-16zm80 16c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V112zM272 96h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H272c-8.8 0-16-7.2-16-16V112c0-8.8 7.2-16 16-16z"
                                />
                            </svg>
                            MATRIZ
                        </label>
                    </div>
                    <div
                        class="text-color radio-primary col-6 ps-0 mb-3 custom-control custom-radio"
                    >
                        <input
                            type="radio"
                            id="deport_mode"
                            v-model="store.current_state.sucursal_mode"
                            class="custom-control-input"
                            value="3"
                            @change="setTemplateStyle"
                        />
                        <label class="custom-control-label" for="deport_mode">
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                height="1em"
                                viewBox="0 0 384 512"
                            >
                                <path
                                    d="M48 0C21.5 0 0 21.5 0 48V464c0 26.5 21.5 48 48 48h96V432c0-26.5 21.5-48 48-48s48 21.5 48 48v80h96c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48H48zM64 240c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V240zm112-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V240c0-8.8 7.2-16 16-16zm80 16c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H272c-8.8 0-16-7.2-16-16V240zM80 96h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V112c0-8.8 7.2-16 16-16zm80 16c0-8.8 7.2-16 16-16h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V112zM272 96h32c8.8 0 16 7.2 16 16v32c0 8.8-7.2 16-16 16H272c-8.8 0-16-7.2-16-16V112c0-8.8 7.2-16 16-16z"
                                />
                            </svg>
                            PLAZA DEPORTIVA
                        </label>
                    </div>
                    <div
                        class="text-color radio-primary col-12 ps-0 mb-3 custom-control custom-radio"
                    >
                        <input
                            type="radio"
                            id="ninguna_mode"
                            v-model="store.current_state.sucursal_mode"
                            class="custom-control-input"
                            value="0"
                            @change="setTemplateStyle"
                        />
                        <label class="custom-control-label" for="ninguna_mode">
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                height="2em"
                                viewBox="0 0 512 512"
                            >
                                <path
                                    d="M64 32C28.7 32 0 60.7 0 96V416c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V96c0-35.3-28.7-64-64-64H64zM175 175c9.4-9.4 24.6-9.4 33.9 0l47 47 47-47c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9l-47 47 47 47c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0l-47-47-47 47c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l47-47-47-47c-9.4-9.4-9.4-24.6 0-33.9z"
                                />
                            </svg>
                            No Sucursal
                        </label>
                    </div>
                </div>
                <div class="btn-group-toggle row mb-4 mx-0" v-if="!is('Cliente')">
                    <div class="col-md-12">
                        <h6 class="mb-1">Eventos Crear</h6>
                        <div class="row">
                            <div class="col-md-6 col-6">
                                <button
                                    type="button"
                                    class="btn btn-black"
                                    @click="opencliente"
                                >Cliente</button>
                            </div>
                            <div class="col-md-6 col-6">
                                <button
                                    type="button"
                                    class="btn btn-black"
                                    @click="open_cliente_search"
                                >Cita</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="btn-group-toggle row mb-4 mx-0" v-if="(condiciones_filtro(route.path)=='filtro_sesiones' || condiciones_filtro(route.path)=='filtro_sesiones_cliente')">
                    <div class="col-md-12">
                        <h6 class="mb-1">Filtros</h6>
                        <div class="row mb-1">
                            <div class="col-12" v-if="!is('Cliente')">
                                <label>Cliente</label>
                                <input
                                    v-model="filtro_cliente"
                                    class="form-control w-100 product-search"
                                    placeholder="Buscar..."
                                />
                            </div>
                            <div class="col-12" v-if="condiciones_filtro(route.path)=='filtro_sesiones'">
                                <div class="form-group">
                                    <label>Terapista</label>
                                    <multiselect
                                        v-model="terapista_id"
                                        mode="tags"
                                        :close-on-select="true"
                                        :searchable="true"
                                        :options="optionsTerapista"
                                        selected-label=""
                                        select-label=""
                                        deselect-label=""
                                        placeholder="Seleccione..."
                                        @update:model-value="changeTerapista"
                                        label="name"
                                        track-by="name"
                                    >
                                    </multiselect>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 col-6">
                                <button
                                type="button"
                                    class="btn btn-black"
                                    @click="aplicar_filtros"
                                >
                                    Aplicar filtros
                                </button>
                            </div>
                            <div class="col-md-6 col-6">
                                <button
                                    type="button"
                                    class="btn btn-danger"
                                    @click="limpiar_filtros"
                                >
                                    Limpiar
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </perfect-scrollbar>
        </div>
        <loading
            v-model:active="isLoading"
            :can-cancel="false"
            :is-full-page="true"
        />
        <!-- Register Modal crear cliente -->
        <div
            class="modal fade"
            id="registerModalExpressCliente"
            tabindex="-1"
            role="dialog"
            aria-labelledby="registerModalLabelCliente"
            aria-hidden="true"
            v-show="true"
        >
            <div class="modal-dialog modal-md" role="document">
                <div class="modal-content">
                    <div class="modal-header titulo-dorado" id="registerModalLabelCliente">
                        <h4 class="modal-title">{{
                            "Crear Cliente"
                        }}</h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <form class="mt-0" ref="formComponentCliente" @submit.stop.prevent="">
                            <div class="form-group">
                                <label>Nombre</label>
                                <input
                                    v-model="formCliente.razonSocial"
                                    type="text"
                                    class="form-control mb-2"
                                    placeholder="Nombre"
                                    :class="[is_entrada_cliente ? (!errorsCliente.razonSocial ? 'is-valid' : 'is-invalid') : '']"
                                />
                                <div class="valid-feedback"></div>
                                <div class="invalid-feedback">
                                    <li v-for="item in errorsCliente.razonSocial">
                                        {{ item }}
                                    </li>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>RFC</label>
                                <input
                                    v-model="formCliente.rfc"
                                    placeholder="RFC"
                                    type="text"
                                    class="form-control mb-2"
                                />
                            </div>
                            <div class="form-group">
                                <label>Email</label>
                                <input
                                    v-model="formCliente.email"
                                    type="email"
                                    class="form-control mb-2"
                                    placeholder="Email"
                                    :class="[is_entrada_cliente ? (!errorsCliente.email ? 'is-valid' : 'is-invalid') : '']"
                                />
                                <div class="valid-feedback"></div>
                                <div class="invalid-feedback">
                                    <li v-for="item in errorsCliente.email">
                                        {{ item }}
                                    </li>
                                </div>
                            </div>
                            <div class="form-group">
                                <label>Celular</label>
                                <input
                                    v-model="formCliente.celular"
                                    type="text"
                                    class="form-control mb-4"
                                    placeholder="Celular"
                                />
                            </div>
                            <div class="form-group">
                                <label class="">Observación:</label>
                                <textarea
                                    v-model="formCliente.observacion"
                                    class="form-control mb-4"
                                    placeholder="Agregar observación"
                                    rows="3"
                                ></textarea>
                            </div>
                            <div class="form-group">
                                <button
                                    type="button"
                                    class="btn btn-black w-100"
                                    @click="createCliente"
                                >
                                    Guardar
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- Modal cliente -->
        <div
            id="modal_index_cliente_express"
            class="modal fade"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
        >
            <div class="modal-dialog modal-lg">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title">Buscar cliente</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="w-100">
                            <button
                                class="btn btn-black pull-right m-1"
                                @click="abrirVale(true)"
                            >
                                Escanear Vale
                            </button>
                            <input
                                v-model="search.search"
                                class="form-control w-100 product-search"
                                placeholder="Buscar..."
                                @keyup.enter="getClienteAll"
                            />
                        </div>
                        <div class="custom-table">
                            <v-client-table
                                :data="obtener_clientes"
                                :columns="columns_cliente"
                                :options="table_option_cliente"
                                ref="table_cliente"
                            >
                                <template #id="props">
                                    <button class="btn btn-black" @click="openCreateCita(props.row.id,props.row.celular,props.row.razonSocial)">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-log-out"
                                        >
                                            <path
                                                d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"
                                            ></path>
                                            <polyline
                                                points="16 17 21 12 16 7"
                                            ></polyline>
                                            <line
                                                x1="21"
                                                y1="12"
                                                x2="9"
                                                y2="12"
                                            ></line>
                                        </svg>
                                        &nbsp{{ props.row.id }}
                                    </button>
                                </template>
                            </v-client-table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- The Modal crear cita-->
        <div
            id="addEventsModalExpress"
            class="modal fade"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
        >
            <div class="modal-dialog modal-lg">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            {{ "Nueva Cita" }}
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <form class="mt-0" ref="formComponentCita" @submit.stop.prevent="">
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-12">
                                    <h3>{{ titulo_sesion }}</h3>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <button
                                        v-if="formCita.vale == 'NO'"
                                        type="button"
                                        class="btn btn-success"
                                        @click="abrirTratamientos"
                                    >
                                        Elegir tratamientos
                                    </button>
                                    <div class="form-group mb-4">
                                        <label>
                                            Tratamientos
                                        </label>
                                        <input
                                        type="hidden"
                                        :class="[
                                            cantidad_tratamientos!=0? 'is-valid': 'is-invalid',
                                        ]"
                                        v-model="cantidad_tratamientos">
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            No puede estar vacio
                                        </div>
                                        <ul v-for="item in tratamientos_vistas">
                                            <li>
                                                <a
                                                    v-if="formCita.vale == 'NO'"
                                                    href="javascript:void(0);"
                                                    title="Eliminar"
                                                    data-bs-toggle="tooltip"
                                                    data-bs-placement="top"
                                                    @click="removerTratamiento(item.id)"
                                                >
                                                    <svg
                                                        xmlns="http://www.w3.org/2000/svg"
                                                        width="24"
                                                        height="24"
                                                        viewBox="0 0 24 24"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        stroke-width="1.5"
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                        class="feather feather-trash"
                                                    >
                                                        <polyline
                                                            points="3 6 5 6 21 6"
                                                        ></polyline>
                                                        <path
                                                            d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"
                                                        ></path>
                                                    </svg>
                                                </a>
                                                &nbsp{{ item.tratamiento }}
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                        <label v-show="formCita.vale == 'SI'">Vale</label>
                                        <p v-show="formCita.vale_id">Folio del vale:{{ formCita.vale_id }}</p><br v-show="!formCita.vale_id">
                                        <button
                                            type="button"
                                            class="btn btn-success"
                                            v-show="formCita.vale == 'SI'"
                                            @click="abrirVale(false)"
                                        >
                                            Elegir
                                        </button>
                                        <button
                                            type="button"
                                            class="btn btn-danger m-1"
                                            v-show="formCita.vale == 'SI' && formCita.vale_id"
                                            @click="removeVale"
                                        >
                                            Remover
                                        </button>
                                        <input
                                        type="hidden"
                                        :class="[
                                            is_entrada_cita
                                                ? !errorsCita.vale_id
                                                    ? 'is-valid'
                                                    : 'is-invalid'
                                                : '',
                                        ]"
                                        v-model="formCita.vale_id">
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            Vale no puede estar vacio
                                        </div>
                                    </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Celular</label>
                                        <input type="text" v-model="formCita.celular" class="form-control" placeholder="Celular" />
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Vale</label>
                                        <multiselect
                                            v-model="vale_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsVale"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.vale
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeVale"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.vale">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Duración</label>
                                        <flat-pickr v-model="formCita.duracion" :config="{ noCalendar: true, enableTime: true, dateFormat: 'H:i', minTime:'01:00:00', maxTime:'10:00:00', minuteIncrement:30 }" class="form-control flatpickr active"></flat-pickr>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Terapista</label>
                                        <multiselect
                                            v-model="terapista_id_express"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsTerapistaExpress"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.terapista_id
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeTerapistaExpress"
                                            label="name"
                                            track-by="name"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.terapista_id">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Sucursal</label>
                                        <multiselect
                                            v-model="sucursal_id_express"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsSucursales"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.sucursal_id
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeSucursal"
                                            label="nombre"
                                            track-by="nombre"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.sucursal_id">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Fecha</label>
                                        <flat-pickr
                                            v-model="formCita.fecha_asignada"
                                            :config="optionsFecha"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.fecha_asignada
                                                        ? 'form-control flatpickr active is-valid'
                                                        : 'form-control flatpickr active is-invalid'
                                                    : 'form-control flatpickr active',
                                            ]"
                                        ></flat-pickr>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.fecha_asignada">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Asistencia</label>
                                        <multiselect
                                            v-model="asistencia_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsAsistencia"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.asistencia
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeAsistencia"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.asistencia">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Confirmación</label>
                                        <multiselect
                                            v-model="asistencia_cumplida_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsAsistenciaCumplida"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.asistencia_cumplida
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeAsistenciaCumplida"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.asistencia_cumplida">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Solicitada por Cliente</label>
                                        <multiselect
                                            v-model="preferencia_terepista_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsPreferenciaTerepista"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.preferencia_terepista
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changePreferenciaTerepista"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.preferencia_terepista">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-6 col-12">
                                    <div class="form-group">
                                        <label>Usa expediente</label>
                                        <multiselect
                                            v-model="usa_expediente_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsUsaExpediente"
                                            :class="[
                                                is_entrada_cita
                                                    ? !errorsCita.usa_expediente
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            @update:model-value="changeUsaExpediente"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errorsCita.usa_expediente">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group mb-4">
                                        <label class="">Observaciones:</label>
                                        <textarea
                                            v-model="formCita.observaciones"
                                            class="form-control"
                                            placeholder="Agregar observación"
                                            rows="3"
                                        ></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button
                                type="button"
                                class="btn btn-black w-100"
                                @click="createCita"
                            >
                                Guardar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- Modal tratamientos -->
        <div
            id="modal_index_tratamientos_express"
            class="modal fade"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
            style="z-index: 1100 !important"
        >
            <div class="modal-dialog modal-lg">
                <div class="modal-content mailbox-popup">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            Tratamientos
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <button
                            class="btn btn-black pull-left m-1"
                            @click="agregarIdsTratamiento"
                        >
                            Agregar
                        </button>
                        <div class="custom-table">
                            <v-client-table
                                :data="obtener_tratamientos"
                                :columns="columns_tratamientos"
                                :options="table_option_tratamientos"
                                ref="table_tratamientos"
                            >
                                <template #check_id_tratamiento="props">
                                    <div class="checkbox-outline-primary custom-control custom-checkbox">
                                        <input
                                        v-model="check_id_tratamiento"
                                        variant="primary"
                                        type="checkbox"
                                        class="custom-control-input"
                                        :id="props.row.id"
                                        :value="props.row.id+'||'+props.row.tratamiento+'||'+props.row.duracion" />
                                        <label class="custom-control-label" :for="props.row.id"></label>
                                    </div>
                                </template>
                                <template #id="props">
                                    <button class="btn btn-sm btn-black"
                                    @click="agregarTratamiento(props.row.id,props.row.tratamiento,props.row.duracion)"
                                    >
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-log-out"
                                        >
                                            <path
                                                d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"
                                            ></path>
                                            <polyline
                                                points="16 17 21 12 16 7"
                                            ></polyline>
                                            <line
                                                x1="21"
                                                y1="12"
                                                x2="9"
                                                y2="12"
                                            ></line>
                                        </svg>
                                        &nbsp{{ props.row.id }}
                                    </button>
                                </template>
                            </v-client-table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- escanner vale Modal -->
        <div class="modal fade" id="valeModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" style="z-index: 1100 !important">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Examinar vale</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-12">
                                <h4><b>UUID o ID/Folio:</b></h4>
                                <input type="text" class="form-control" v-model="decodedString" placeholder="Escribe el UUID o ID/Folio del vale">
                            </div>
                            <div class="col-12">
                                <ul style="color: red;" v-if="errors2.uuid">
                                    <li v-for="item in errors2.uuid">
                                        {{ item }}
                                    </li>
                                </ul>
                            </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="examinarVale()">Verificar</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, inject } from "vue";
import { useStateStore } from '@/store/StateStore';
import * as SucursalRepository from '@/repositories/SucursalRepository';
import * as UserRepository from '@/repositories/UserRepository';
import * as ClienteRepository from "@/repositories/ClienteRepository";
import * as TratamientoRepository from "@/repositories/TratamientoRepository";
import * as SesionRepository from "@/repositories/SesionRepository";
import { useRoute } from "vue-router";
import axios from "axios";

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

//select2
import Multiselect from "@suadelabs/vue3-multiselect";
import "@suadelabs/vue3-multiselect/dist/vue3-multiselect.css";

// qr
import { QrcodeStream } from 'qrcode-reader-vue3';

// loading
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";
const isLoading = ref(false);

const store = useStateStore();
const route = useRoute();

//qr
const decodedString =ref('');
const errors2 =ref({});
const camera= ref('off');
const is_vale_directo = ref(false);
const id_cliente_publico = ref(null);
const name_cliente_publico = ref(null);

const isUserType = inject('$isUserType');

//modales
let registerModalExpressCliente = ref(false);
let addEventsModalExpress = ref(null);
let modal_index_cliente_express = ref(null);
let modal_index_tratamientos_express = ref(null);
let valeModal2 = ref(null);

// tratamientos
const columns_tratamientos = ref(['check_id_tratamiento','id','tratamiento']);
const table_option_tratamientos = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio tratamiento";
        },
        check_id_tratamiento: (h, row, index) => {
            return "#";
        }
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: { count_exp: "count_exp text-center" },
    sortable: ['id','tratamiento'],
    sortIcon: {
        base: "sort-icon-none",
        up: "sort-icon-asc",
        down: "sort-icon-desc",
    },
    pagination: { nav: "scroll", chunk: 5 },
    texts: {
        count: "Mostrando {from} a {to} de {count}",
        filter: "",
        filterPlaceholder: "Buscar...",
        limit: "Resultados:",
        noResults:"No hay registros"
    },
    resizableColumns: true,
});
const obtener_tratamientos = ref([]);
const check_id_tratamiento= ref([]);
const cantidad_tratamientos=ref(0);

//formulario citas
const titulo_sesion =ref('');
const fecha_asignada =ref('');
const is_entrada_cita = ref(false);
const formComponentCita = ref(null);
const errorsCita = ref({});
const formCita = ref({
    celular: null,
    sucursal_id: null,
    cliente_id: null,
    terapista_id: null,
    duracion: '01:00',
    fecha_asignada: moment(new Date()).format("YYYY-MM-D H:mm"),
    observaciones: null,
    asistencia: 'NO',
    preferencia_terepista: 'NO',
    vale: 'NO',
    vale_id: null,
    asistencia_cumplida: 'NO',
    usa_expediente: 'NO',
});

// tratamientos
const tratamientos_vistas= ref([]);

// crear cliente
const formComponentCliente = ref(null);
const is_entrada_cliente = ref(false);
const errorsCliente = ref({});
const formCliente = ref({
    rfc: "",
    razonSocial: null,
    email: null,
    celular: null,
    observacion:''
});


const filtros = ref({
    terapista_id:0,
    terapista:"",
});
//select terapista
const optionsTerapista = ref([]);
const changeTerapista = (data) => {
    filtros.value.terapista_id=0;
    filtros.value.terapista="";
    if(data !=null){
        filtros.value.terapista_id=data.id;
        filtros.value.terapista=data.name;
    }
};
const terapista_id = ref({});

//filtro cliente
const filtro_cliente = ref('');


//table clientes
const search = ref({
    search: "",
});
const columns_cliente = ref(["id", "razonSocial"]);
const table_option_cliente = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        razonSocial: (h, row, index) => {
            return "Cliente";
        },
        count_exp: (h, row, index) => {
            return "Entrar";
        },
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: { count_exp: "count_exp text-center" },
    sortable: ["id", "razonSocial", "rfc", "celular", "email"],
    sortIcon: {
        base: "sort-icon-none",
        up: "sort-icon-asc",
        down: "sort-icon-desc",
    },
    pagination: { nav: "scroll", chunk: 5 },
    texts: {
        count: "Mostrando {from} a {to} de {count}",
        filter: "",
        filterPlaceholder: "Buscar...",
        limit: "Resultados:",
        noResults:"No hay registros"
    },
    resizableColumns: true,
    filterable: false,
});

//clientes index
const obtener_clientes = ref([]);

// eventos de consulta

const getClienteAll = async () => {
    try {
        isLoading.value = true;
        const response = await ClienteRepository.getAllSearch(search.value);
        obtener_clientes.value = response.data;
        isLoading.value = false;
    } catch (error) {
        console.log(error);
    }
};

const obtener_sucursal = async (sucursal_id)=>{
    try {
        const response = await SucursalRepository.getSucursalId(sucursal_id);
        return response;
    } catch (error) {
        console.log(error);
    }
}

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

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

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

const isOpen = ref(null);
const setTemplateStyle = async (primera_entrada=false) => {
    isLoading.value=true;
    if(store.current_state.sucursal_mode!=0){
        const response= await obtener_sucursal(store.current_state.sucursal_mode);
        store.current_state.sucursal_name_mode=response.data.nombre;
        store.current_state.sucursal_mode=response.data.id;
        UserRepository.setConfigSucursal(store.current_state.sucursal_mode);
    } else {
        store.current_state.sucursal_name_mode='Sin sucursal';
        store.current_state.sucursal_mode=0;
        UserRepository.setConfigSucursal(0);
    }
    isLoading.value=false;
    if((condiciones_filtro(route.path)=='filtro_sucursal' || condiciones_filtro(route.path)=='filtro_sesiones' || condiciones_filtro(route.path)=='filtro_sesiones_cliente' || condiciones_filtro_name(route.name)=='filtro_sesiones_expediente') && primera_entrada !== true){
        aplicar_filtros();
    }
};
const aplicar_filtros =()=>{
    store.current_state.terapista_id=filtros.value.terapista_id;
    store.current_state.terapista_name=filtros.value.terapista;
    store.current_state.filtro_cliente=filtro_cliente.value;
    document.getElementById("evento_recargar_reservar").click();
    isOpen.value=false;
}
const limpiar_filtros =()=>{
    store.current_state.terapista_id="0";
    store.current_state.terapista_name="";
    store.current_state.filtro_cliente=null;
    filtros.value = {
        terapista_id:0,
        terapista:"",
    };
    filtro_cliente.value = "";
    document.getElementById("evento_recargar_reservar").click();
    isOpen.value=false;
}
const condiciones_filtro = (path) => {
    switch (path) {
        case "/":
        case "/monitor":
        case "/citas/reservar":
            return 'filtro_sesiones';
            break;
        case "/citas/revision":
            return 'filtro_sesiones_cliente';
            break;
        case "/inventarios/lista":
        case "/inventarios/lista":
        case "/entradas/lista":
        case "/ventas/vender":
        case "/ventas/lista":
        case "/ventas/mis-compras":
        case "/cortes-cajas/lista":
            return 'filtro_sucursal';
            break;
    }
    return "";
};


const condiciones_filtro_name = (name) => {
    switch (name) {
        case "expedientes-clienteid-router":
            return 'filtro_sesiones_expediente';
            break;
    }
    return "";
};


//eventos tratamiento
const removerTratamiento=(id)=>{
    isLoading.value = true;
    tratamientos_vistas.value=tratamientos_vistas.value.filter(function(val, i) {
        if(val.id==id){
            const [h1, m1] = formCita.value.duracion.split(":").map(Number);
            const [h2, m2] = val.duracion.split(":").map(Number);

            let totalMinutes = m1 - m2;
            let carry = Math.floor(totalMinutes / 60);
            totalMinutes = totalMinutes % 60;

            let totalHours = h1 - h2 - carry;
            totalHours = totalHours % 24;

            const formatTime = num => (num < 10 ? "0" : "") + num;
            if(totalHours>1){
                formCita.value.duracion = `${formatTime(totalHours)}:${formatTime(totalMinutes)}`;
            } else {
                formCita.value.duracion = '01:00';
            }
        }
        return val.id != id;
    });
    cantidad_tratamientos.value=tratamientos_vistas.value.length;
    isLoading.value = false;
};

const agregarTratamiento=(id,tratamiento,duracion)=>{
    isLoading.value = true;
    tratamientos_vistas.value.push({id:id,tratamiento:tratamiento,duracion:duracion});
    modal_index_tratamientos_express.hide();
    cantidad_tratamientos.value=tratamientos_vistas.value.length;
    if(tratamientos_vistas.value.length > 1){
        const [h1, m1] = formCita.value.duracion.split(":").map(Number);
        const [h2, m2] = duracion.split(":").map(Number);

        let totalMinutes = m1 + m2;
        let carry = Math.floor(totalMinutes / 60);
        totalMinutes = totalMinutes % 60;

        let totalHours = h1 + h2 + carry;
        totalHours = totalHours % 24;

        const formatTime = num => (num < 10 ? "0" : "") + num;

        formCita.value.duracion = `${formatTime(totalHours)}:${formatTime(totalMinutes)}`;
    } else {
        formCita.value.duracion = duracion;
    }
    isLoading.value = false;
};

const agregarIdsTratamiento= async()=>{
    isLoading.value = true;
    if(tratamientos_vistas.value.length == 0){
        formCita.value.duracion = '00:00:00';
    }
    await check_id_tratamiento.value.forEach((element) => {
        const filtro= element.split("||");

        const [h1, m1] = formCita.value.duracion.split(":").map(Number);
        const [h2, m2] = filtro[2].split(":").map(Number);

        let totalMinutes = m1 + m2;
        let carry = Math.floor(totalMinutes / 60);
        totalMinutes = totalMinutes % 60;

        let totalHours = h1 + h2 + carry;
        totalHours = totalHours % 24;

        const formatTime = num => (num < 10 ? "0" : "") + num;

        formCita.value.duracion = `${formatTime(totalHours)}:${formatTime(totalMinutes)}`;

        tratamientos_vistas.value.push({id:filtro[0],tratamiento:filtro[1],duracion:filtro[2]});
    });
    cantidad_tratamientos.value=tratamientos_vistas.value.length;
    modal_index_tratamientos_express.hide();
    isLoading.value = false;
};

const abrirTratamientos = async()=>{
    isLoading.value = true;
    check_id_tratamiento.value=[];
    const response = await TratamientoRepository.getAll({tratamientos:tratamientos_vistas.value});
    obtener_tratamientos.value=response.data;
    modal_index_tratamientos_express.show();
    isLoading.value = false;
};

// eventos crear cliente
const opencliente = () => {
    initializeCreateCliente();
    registerModalExpressCliente.show();
    isOpen.value=false;
};

const createCliente = async () => {
  try {
    isLoading.value = true;
    is_entrada_cliente.value = true;
    const response = await ClienteRepository.createCliente(formCliente.value);
    showMessage('Guardado correctamente');
    initializeCreateCliente();
    registerModalExpressCliente.hide();
    isLoading.value = false;
  } catch (error) {
    isLoading.value = false;
    if (axios.isAxiosError(error)) errorsCliente.value = error.response.data.errors;
  }
};

//eventos crear cita
const open_cliente_search = () => {
    search.value = {
        search:""
    };
    obtener_clientes.value=[];
    modal_index_cliente_express.show();
    isOpen.value=false;
};

const initializeCreateCliente = () => {
    formCliente.value = {
        rfc: "",
        razonSocial: null,
        email: null,
        celular: null,
        observacion: '',
    };
    errorsCliente.value = {};
    is_entrada_cliente.value = false;
};

// eventos de crear citas
const openCreateCita = (cliente_id,celular,razonSocial) => {
    initializeCreateCita();
    titulo_sesion.value=razonSocial;
    fecha_asignada.value=formCita.value.fecha_asignada;
    formCita.value.cliente_id=cliente_id;
    formCita.value.celular=celular;
    is_entrada_cita.value = true;
    modal_index_cliente_express.hide();
    addEventsModalExpress.show();
};

const initializeCreateCita = () => {
    decodedString.value='';
    errors2.value={};
    titulo_sesion.value='';
    fecha_asignada.value='';
    sucursal_id_express.value = {
        id: store.current_state.sucursal_mode,
        nombre: store.current_state.sucursal_name_mode,
    };
    terapista_id_express.value = {
        id: 36,
        name: 'no asignada',
    };
    if(store.current_state.terapista_id != 0){
        terapista_id_express.value = {
            id: store.current_state.terapista_id,
            name: store.current_state.terapista_name,
        };
    }
    preferencia_terepista_id.value = 'NO';
    vale_id.value = 'NO';
    asistencia_id.value = 'NO';
    usa_expediente_id.value = 'NO';
    asistencia_cumplida_id.value = 'NO';
    cantidad_tratamientos.value=0;
    tratamientos_vistas.value = [];
    formCita.value = {
        celular:null,
        sucursal_id: store.current_state.sucursal_mode,
        cliente_id: null,
        terapista_id: 36,
        duracion: '01:00',
        fecha_asignada: moment(new Date()).format("YYYY-MM-D H:mm"),
        observaciones: null,
        asistencia: 'NO',
        asistencia_cumplida: 'NO',
        usa_expediente: 'NO',
        preferencia_terepista: 'NO',
        vale: 'NO',
        vale_id: null,
    };
    errorsCita.value = {};
    is_entrada_cita.value = false;
};

const optionsFecha = ref({
    enableTime: true,
    dateFormat: 'Y-m-d H:i',
    time_24hr: false,
    minTime: '08:00:00',
    maxTime: '19:00:00',
    minuteIncrement:60,
    minDate: moment(new Date()).format("YYYY-MM-D H:mm"),
});

//select sucursal
const sucursal_id_express = ref({
    id: store.current_state.sucursal_mode,
    nombre: store.current_state.sucursal_name_mode,
});
const optionsSucursales = ref([]);
const changeSucursal = (data) => {
    formCita.value.sucursal_id_express = data.id;
    formCita.value.sucursal_id = data.id;
};


// select terapista
const terapista_id_express = ref({
    id: 36,
    name: 'no asignada',
});
const optionsTerapistaExpress= ref([]);
const changeTerapistaExpress = (data) => {
    formCita.value.terapista_id = data.id;
};

const cargar_terapista = async () =>{
    const response =  await obtener_terapista();
    optionsTerapista.value = response.data;
    optionsTerapistaExpress.value = response.data;
};

// select solicitado por cliente
const preferencia_terepista_id = ref('NO');
const optionsPreferenciaTerepista = ref(['NO','SI']);
const changePreferenciaTerepista = (data) => {
    formCita.value.preferencia_terepista = data;
};

// select asistencia
const asistencia_id = ref('NO');
const optionsAsistencia= ref(['NO','SI']);
const changeAsistencia = (data) => {
    formCita.value.asistencia = data;
};

// select vale
const vale_id = ref('NO');
const optionsVale = ref(['NO','SI']);
const changeVale = (data) => {
    formCita.value.vale = data;
};

// select usa_expediente
const usa_expediente_id = ref('NO');
const optionsUsaExpediente = ref(['NO','SI']);
const changeUsaExpediente = (data) => {
    formCita.value.usa_expediente = data;
};

// select asistencia_cumplida
const asistencia_cumplida_id = ref('NO');
const optionsAsistenciaCumplida = ref(['NO','SI']);
const changeAsistenciaCumplida = (data) => {
    formCita.value.asistencia_cumplida = data;
};

const createCita = async () => {
    if(cantidad_tratamientos.value>0){
        try {
            isLoading.value = true;
            is_entrada_cita.value = true;
            formCita.value.tratamientos_vistas = tratamientos_vistas.value;
            formCita.value.cantidad_tratamientos = cantidad_tratamientos.value;
            const response = await SesionRepository.createSesion(formCita.value);
            showMessage('Guardado correctamente');
            initializeCreateCita();
            addEventsModalExpress.hide();
            const refrescar_externo = condiciones_filtro(route.path);
            isLoading.value = false;
            if(refrescar_externo=='filtro_sesiones' || refrescar_externo=='filtro_sesiones_cliente'){
                aplicar_filtros();
            }
        } catch (error) {
            isLoading.value = false;
            if (axios.isAxiosError(error)) errorsCita.value = error.response.data.errors;
        }
    }
};

const removeVale = () => {
    decodedString.value='';
    formCita.value.vale_id=null;
    errors2.value={};
}

const abrirVale = (temp=false) => {
    decodedString.value='';
    errors2.value={};
    valeModal2.show();
    is_vale_directo.value = temp;
    if(temp){
        form.value.cliente_id = id_cliente_publico.value;
        form.value.celular = "";
        is_vale_directo.value = true;
        titulo_sesion.value= 'Cliente: '+name_cliente_publico.value;

    }
}

function paintOutline(detectedCodes, ctx) {
  for (const detectedCode of detectedCodes) {
    const [firstPoint, ...otherPoints] = detectedCode.cornerPoints

    ctx.strokeStyle = 'red'

    ctx.beginPath()
    ctx.moveTo(firstPoint.x, firstPoint.y)
    for (const { x, y } of otherPoints) {
        ctx.lineTo(x, y)
    }
    ctx.lineTo(firstPoint.x, firstPoint.y)
    ctx.closePath()
    ctx.stroke()
  }
}

const trackFunctionSelected = ref({ text: 'outline', value: paintOutline });

function onDetect(detectedCodes) {
    detectedCodes.then(
        function(value) {
            decodedString.value=value.content;
        },
        function(error) { console.log(error,"error") }
    );
}

const examinarVale = async () => {
    try {
        isLoading.value = true;
        // Determinar si es UUID o ID/folio basado en el formato
        const isNumeric = /^\d+$/.test(decodedString.value);
        const params = isNumeric
            ? { id: decodedString.value }
            : { uuid: decodedString.value };

        const response = await SesionRepository.getVerificarVale(params);
        showMessage('Vale valido, se agrego correctamente');
        errors2.value={};
        valeModal2.hide();
        if(is_vale_directo.value){
            openCreateCita(id_cliente_publico.value,'','Cliente: '+name_cliente_publico.value);
        }
        formCita.value.vale='SI';
        vale_id.value = 'SI';
        formCita.value.vale_id=response.data.id;
        tratamientos_vistas.value=[];
        cantidad_tratamientos.value=0;
        agregarTratamiento(response.data.tratamiento_id, response.data.tratamiento, response.data.duracion_tratamiento);
        isLoading.value = false;
    } catch (error) {
        if (axios.isAxiosError(error)) errors2.value = error.response.data.errors;
        isLoading.value = false;
        showMessage('Error al verificar vale','error');
    }
}

const activarCamara = () => {
    const activar= valeModal2._isShown;
    camera.value='off';
    if(activar){
        camera.value='auto';
    }
}

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

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 token = window.localStorage.getItem("token");
    if(token){
        cargar_terapista();
        obtener_sucursales();
        const response= await obtener_config_sucursal();
        store.current_state.sucursal_name_mode=response.data.nombre;
        store.current_state.sucursal_mode=response.data.id;
        const cliente_publico = await obtener_cliente_publico();
        if(cliente_publico.id){
            id_cliente_publico.value = cliente_publico.id;
            name_cliente_publico.value = cliente_publico.razonSocial;
        }
        setTemplateStyle(true);
        modal_index_cliente_express = new window.bootstrap.Modal(
            document.getElementById("modal_index_cliente_express")
        );
        addEventsModalExpress = new window.bootstrap.Modal(
            document.getElementById("addEventsModalExpress")
        );
        modal_index_tratamientos_express = new window.bootstrap.Modal(
            document.getElementById("modal_index_tratamientos_express")
        );
        registerModalExpressCliente = new window.bootstrap.Modal(
            document.getElementById('registerModalExpressCliente')
        );
        valeModal2 = new window.bootstrap.Modal(
            document.getElementById("valeModal2")
        );
    }
});
</script>
