<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">Nuevas citas en línea</h1>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    @click="refrescar"
                                >
                                    Refrescar
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="custom-table">
                        <v-client-table
                            :data="obtener_citas"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #actions="item">
                                <a
                                    href="javascript:void(0);"
                                    title="Edit"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="getCitaId(item.row.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-edit-2"
                                    >
                                        <path
                                            d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"
                                        ></path>
                                    </svg>
                                </a>
                                <a
                                    href="javascript:void(0);"
                                    title="Delete"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="deleteItem(item.row.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>
                            </template>
                        </v-client-table>
                    </div>
                </div>
            </div>
        </div>
        <!-- Modal tratamientos -->
        <div
            id="modal_index_tratamientos_principal"
            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>

        <!-- The Modal -->
        <div
            id="addEventsModalPrincipal"
            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">
                            {{ editedIndex === -1 ? "Nuevo " : "Editar " }}
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <form class="mt-0" ref="formComponentPrincipal" @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
                                        type="button"
                                        class="btn btn-success"
                                        @click="abrirTratamientos"
                                    >
                                        Elegir tratamientos
                                    </button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <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
                                                    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 col-sm-12 col-6">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Celular</label>
                                        <input type="text" v-model="form.celular" class="form-control" placeholder="Celular" />
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group end-date mb-4">
                                        <label for="end-date" class="">Duración</label>
                                        <flat-pickr v-model="form.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-12 col-6">
                                    <div class="form-group">
                                        <label>Terapista</label>
                                        <multiselect
                                            v-model="terapista_id"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsTerapista"
                                            :class="[
                                                is_entrada
                                                    ? !errors.terapista_id
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeTerapista"
                                            label="name"
                                            track-by="name"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.terapista_id">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Sucursal</label>
                                        <multiselect
                                            v-model="sucursal_id"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsSucursales"
                                            :class="[
                                                is_entrada
                                                    ? !errors.sucursal_id
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeSucursal"
                                            label="nombre"
                                            track-by="nombre"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.sucursal_id">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Fecha</label>
                                        <flat-pickr
                                            v-model="form.fecha_asignada"
                                            :config="optionsFechaCitas"
                                            :class="[
                                                is_entrada
                                                    ? !errors.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 errors.fecha_asignada">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Asistencia</label>
                                        <multiselect
                                            v-model="asistencia_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsAsistencia"
                                            :class="[
                                                is_entrada
                                                    ? !errors.asistencia
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeAsistencia"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.asistencia">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <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
                                                    ? !errors.asistencia_cumplida
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeAsistenciaCumplida"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.asistencia_cumplida">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <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
                                                    ? !errors.preferencia_terepista
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changePreferenciaTerepista"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.preferencia_terepista">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <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
                                                    ? !errors.usa_expediente
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeUsaExpediente"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.usa_expediente">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <!-- <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Vale</label>
                                        <multiselect
                                            v-model="vale_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsVale"
                                            :class="[
                                                is_entrada
                                                    ? !errors.vale
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeVale"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.vale">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div> -->
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Aprobado</label>
                                        <multiselect
                                            v-model="aprobado_id"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsAprobado"
                                            :class="[
                                                is_entrada
                                                    ? !errors.aprobado
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                            @update:model-value="changeAprobado"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.aprobado">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group mb-4">
                                        <label class="">Observaciones del cliente:</label>
                                        <textarea
                                            v-model="form.observacion_cliente"
                                            class="form-control"
                                            placeholder="Agregar observación"
                                            rows="3"
                                        ></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button
                                class="btn btn-black w-100"
                                v-show="editedIndex  !== -1"
                                @click="updateCitaPrincipal"
                            >
                                Actualizar
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- Eliminar Modal -->
        <div
            class="modal fade"
            id="deleteModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
        >
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">
                            ¿Estás seguro de eliminar esta cita?
                        </h5>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-footer">
                        <button
                            type="button"
                            class="btn"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                        >
                            <i class="flaticon-cancel-12"></i> Cancelar
                        </button>
                        <button
                            type="button"
                            class="btn btn-black"
                            @click="deleteSesion()"
                        >
                            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="aplicar_flitro"
        ></button>
    </div>
</template>
<style>
.table3 .actions svg {
    padding: 2px;
}
</style>
<script setup>
import { onMounted, ref } from "vue";
import "@/assets/sass/elements/tooltip.scss";
import { useMeta } from "@/composables/use-meta";
import { useAuthStore } from "@/store/AuthStore";
import { useStateStore } from "@/store/StateStore";
import * as UserRepository from "@/repositories/UserRepository";
import * as SucursalRepository from "@/repositories/SucursalRepository";
import * as SesionRepository from "@/repositories/SesionRepository";
import * as TratamientoRepository from "@/repositories/TratamientoRepository";
import axios from "axios";
import { useRoute } from "vue-router";
import "@/assets/sass/scrollspyNav.scss";

// loading
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";

//icono
import '@/assets/sass/font-icons/fontawesome/css/regular.css';
import '@/assets/sass/font-icons/fontawesome/css/fontawesome.css';
import feather from 'feather-icons';

//tabs
import '@/assets/sass/scrollspyNav.scss';
import '@/assets/sass/components/tabs-accordian/custom-tabs.scss';

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

useMeta({ title: "EGURROLA" });

const store = useAuthStore();
const storeState = useStateStore();
const obtener_citas = ref([]);
const route = useRoute();

const isLoading = ref(true);

// filtros
const filtro = ref({
    sucursal_id: null,
    cliente: null
});

//formulario crear y eliminar
let addEventsModalPrincipal = ref(false);
let modal_index_tratamientos_principal = ref(null);
let deleteModal = ref(false);

//table 2
const columns1 = ref([
    "id",
    "fecha",
    "hora",
    "sucursal",
    "cliente",
    "actions",
]);

const table_option1 = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        actions: (h, row, index) => {
            return "";
        },
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: { actions: "actions text-center" },
    sortable: ["id", "fecha", "hora",  "sucursal",  "cliente"],
    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,
});

// 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 = ref(false);
const editedIndex = ref(-1);
const formComponentPrincipal = ref(null);
const errors = ref({});
const form = ref({
    celular: null,
    sucursal_id: storeState.current_state.sucursal_mode,
    cliente_id: null,
    terapista_id: null,
    duracion: '01:00',
    fecha_asignada: moment(new Date()).format("YYYY-MM-DD H:mm"),
    observaciones: null,
    asistencia: 'NO',
    preferencia_terepista: 'NO',
    vale: 'NO',
    asistencia_cumplida: 'NO',
    usa_expediente: 'NO',
    aprobado: 'NO',
    observacion_cliente: null,
});

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

//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] = form.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){
                form.value.duracion = `${formatTime(totalHours)}:${formatTime(totalMinutes)}`;
            } else {
                form.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_principal.hide();
    cantidad_tratamientos.value=tratamientos_vistas.value.length;
    if(tratamientos_vistas.value.length > 1){
        const [h1, m1] = form.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;

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

const agregarIdsTratamiento= async()=>{
    isLoading.value = true;
    if(tratamientos_vistas.value.length == 0){
        form.value.duracion = '00:00:00';
    }
    await check_id_tratamiento.value.forEach((element) => {
        const filtro= element.split("||");
        const [h1, m1] = form.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;

        form.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_principal.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_principal.show();
    isLoading.value = false;
};

const optionsFechaCitas = 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 = ref({
    id: storeState.current_state.sucursal_mode,
    nombre: storeState.current_state.sucursal_name_mode,
});
const optionsSucursales = ref([]);
const changeSucursal = (data) => {
    form.value.sucursal_id = data.id;
};


// select terapista
const terapista_id = ref({
    id: 36,
    name: 'no asignada',
});
const optionsTerapista = ref([]);
const changeTerapista = (data) => {
    form.value.terapista_id = data.id;
};
const obtener_terapista = async ()=>{
    try {
        const response = await UserRepository.getTerapistas();
        return response;
    } catch (error) {
        console.log(error);
    }
}
const cargar_terapista = async () =>{
    const response =  await obtener_terapista();
    optionsTerapista.value = response.data;
};

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

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

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

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

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

// select aprobado
const aprobado_id = ref('NO');
const optionsAprobado = ref(['NO','SI']);
const changeAprobado = (data) => {
    form.value.aprobado = data;
};

const getCitaId = async (id,vista="") => {
  try {
        isLoading.value = true;
        const response = await SesionRepository.getSesionId(id);
        titulo_sesion.value=response.data.cliente.razonSocial;
        fecha_asignada.value=response.data.sesion.fecha_asignada;
        sucursal_id.value = {
            id: response.data.sucursal.id,
            nombre: response.data.sucursal.nombre,
        };
        terapista_id.value = {
            id: response.data.terapista.id,
            name: response.data.terapista.name,
        };
        asistencia_id.value = response.data.sesion.asistencia;
        usa_expediente_id.value = response.data.sesion.usa_expediente;
        asistencia_cumplida_id.value = response.data.sesion.asistencia_cumplida;
        preferencia_terepista_id.value = response.data.sesion.preferencia_terepista;
        vale_id.value = response.data.sesion.vale;
        aprobado_id.value = response.data.sesion.aprobado;
        cantidad_tratamientos.value=response.data.tratamientos.length;
        tratamientos_vistas.value = response.data.tratamientos;
        form.value = {
            celular:response.data.cliente.celular,
            sucursal_id: response.data.sucursal.id,
            cliente_id: response.data.cliente.id,
            terapista_id: response.data.terapista.id,
            duracion: response.data.sesion.duracion,
            fecha_asignada: response.data.sesion.fecha_asignada,
            observaciones: response.data.sesion.observaciones,
            asistencia: response.data.sesion.asistencia,
            asistencia_cumplida: response.data.sesion.asistencia_cumplida,
            usa_expediente: response.data.sesion.usa_expediente,
            preferencia_terepista: response.data.sesion.preferencia_terepista,
            vale: response.data.sesion.vale,
            aprobado: response.data.sesion.aprobado,
            observacion_cliente: response.data.sesion.observacion_cliente,
        };
        errors.value = {};
        editedIndex.value = id;
        addEventsModalPrincipal.show();
        isLoading.value = false;
  } catch (error) {
        console.log(error);
  }
};

const updateCitaPrincipal = async () => {
    try {
        isLoading.value = true;
        is_entrada.value = true;
        form.value.tratamientos_vistas = tratamientos_vistas.value;
        form.value.cantidad_tratamientos = cantidad_tratamientos.value;
        const response = await SesionRepository.updateSesion(
            form.value,
            editedIndex.value
        );
        showMessage('Guardado correctamente');
        addEventsModalPrincipal.hide();
        initializeCreate();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error)) errors.value = error.response.data.errors;
        isLoading.value = false;
    }
};

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

const deleteSesion = async () => {
    try {
        isLoading.value=true;
        const response = await SesionRepository.deleteSesion(
            editedIndex.value
        );
        showMessage("Eliminado correctamente");
        closeDelete();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
        console.log(error);
    }
};

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

const initializeCreate = async() => {
    sucursal_id.value = {
        id: storeState.current_state.sucursal_mode,
        nombre: storeState.current_state.sucursal_name_mode,
    };
    form.value = {
        sucursal_id:storeState.current_state.sucursal_mode,
        celular: null,
        cliente_id: null,
        terapista_id: null,
        duracion: '01:00',
        fecha_asignada: moment(new Date()).format("YYYY-MM-DD H:mm"),
        observaciones: null,
        asistencia: 'NO',
        preferencia_terepista: 'NO',
        vale: 'NO',
        asistencia_cumplida: 'NO',
        usa_expediente: 'NO',
        aprobado: 'NO',
        observacion_cliente: null,
    };
    errors.value = {};
    editedIndex.value = -1;
};

const getSesionAll = async () => {
    try {
        isLoading.value=true;
        filtro.value.sucursal_id=null;
        if(storeState.current_state.sucursal_mode != 0){
            filtro.value.sucursal_id=storeState.current_state.sucursal_mode;
        }
        filtro.value.cliente=null;
        if(storeState.current_state.filtro_cliente != null){
            filtro.value.cliente=storeState.current_state.filtro_cliente;
        }
        const response = await SesionRepository.getRevision(filtro.value);
        return response.data;
    } catch (error) {
        console.log(error);
    }
};

const aplicar_flitro = async () => {
    const resp = await getSesionAll();
    obtener_citas.value = resp;
    isLoading.value=false;
}

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

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

const initialize = async () => {
    isLoading.value=true;
    const resp = await getSesionAll();
    obtener_citas.value = resp;
    table_option1.value = {
        headings: {
            id: (h, row, index) => {
                return "Folio";
            },
            actions: (h, row, index) => {
                return "";
            },
        },
        perPage: 100,
        perPageValues: [20, 50, 100],
        skin: "table table-hover",
        columnsClasses: { actions: "actions text-center" },
        sortable: ["id", "fecha", "hora",  "sucursal",  "cliente"],
        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 model_sucursal = await getSucursalAll();
    optionsSucursales.value = model_sucursal;
    is_entrada.value = false;
    isLoading.value=false;
};

const refrescar = () => {
    initialize();
    showMessage("Completado correctamente");
};

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;
    cargar_terapista();
    addEventsModalPrincipal = new window.bootstrap.Modal(
        document.getElementById("addEventsModalPrincipal")
    );
    modal_index_tratamientos_principal = new window.bootstrap.Modal(
        document.getElementById("modal_index_tratamientos_principal")
    );
    deleteModal = new window.bootstrap.Modal(
        document.getElementById("deleteModal")
    );
    initialize();
});
</script>
