<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">
                            <h1 class="pull-left">Cliente: {{ titulo_mo }}</h1>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xl-12 col-lg-12 col-sm-12">
                            <div class="text-center titulo-dorado">
                                <h1 class="pull-left">Direcciones de entrega</h1>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    @click="refrescar"
                                >
                                    Refrescar
                                </button>
                                <button
                                    class="btn btn-black pull-right m-1"
                                    data-bs-toggle="modal"
                                    data-bs-target="#registerModal"
                                    @click="initializeCreate"
                                >
                                    Nuevo
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="custom-table">
                        <v-client-table
                            :data="obtener_direcciones"
                            :columns="columns1"
                            :options="table_option1"
                        >
                            <template #actions="item">
                                <a
                                    href="javascript:void(0);"
                                    title="Edit"
                                    data-bs-toggle="tooltip"
                                    data-bs-placement="top"
                                    @click="getDireccionId(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>
        <!-- Register Modal -->
        <div
            class="modal fade"
            id="registerModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="registerModalLabel"
            aria-hidden="true"
            v-show="true"
        >
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div
                        class="modal-header titulo-dorado"
                        id="registerModalLabel"
                    >
                        <h4 class="modal-title">
                            {{ editedIndex === -1 ? "Nuevo " : "Editar " }}
                        </h4>
                        <button
                            type="button"
                            data-dismiss="modal"
                            data-bs-dismiss="modal"
                            aria-label="Close"
                            class="btn-close"
                        ></button>
                    </div>
                    <div class="modal-body">
                        <form
                            class="mt-0"
                            ref="formComponent"
                            @submit.stop.prevent=""
                        >
                            <div class="row">
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Calle</label>
                                        <textarea
                                            class="form-control mb-2"
                                            placeholder="Calle"
                                            v-model="form.calle"
                                            :class="[
                                                is_entrada
                                                    ? !errors.calle
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                        >
                                        </textarea>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.calle" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Número exterior</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Número exterior"
                                            v-model="form.numero_exterior"
                                            :class="[is_entrada ? !errors.numero_exterior ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.numero_exterior" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Número interior</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Número interior"
                                            v-model="form.numero_interior"
                                            :class="[is_entrada ? !errors.numero_interior ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.numero_interior" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Colonia</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Colonia"
                                            v-model="form.colonia"
                                            :class="[is_entrada ? !errors.colonia ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.colonia" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Código postal</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Código postal"
                                            v-model="form.codigo_postal"
                                            :class="[is_entrada ? !errors.codigo_postal ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.codigo_postal" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Ciudad</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Ciudad"
                                            v-model="form.ciudad"
                                            :class="[is_entrada ? !errors.ciudad ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.ciudad" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Estado</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="Estado"
                                            v-model="form.estado"
                                            :class="[is_entrada ? !errors.estado ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.estado" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>País</label>
                                        <input
                                            type="text"
                                            class="form-control mb-2"
                                            placeholder="País"
                                            v-model="form.pais"
                                            :class="[is_entrada ? !errors.pais ? 'is-valid' : 'is-invalid' : '',]"
                                        />
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.pais" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Principal</label>
                                        <multiselect
                                            v-model="form.es_principal"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsEsPrincipal"
                                            :class="[
                                                is_entrada
                                                    ? !errors.es_principal
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.es_principal" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 col-sm-12 col-6">
                                    <div class="form-group">
                                        <label>Estatus</label>
                                        <multiselect
                                            v-model="form.estatus"
                                            mode="tags"
                                            :close-on-select="true"
                                            :searchable="true"
                                            :options="optionsEstatus"
                                            :class="[
                                                is_entrada
                                                    ? !errors.estatus
                                                        ? 'is-valid'
                                                        : 'is-invalid'
                                                    : '',
                                            ]"
                                            selected-label=""
                                            select-label=""
                                            deselect-label=""
                                            placeholder="Seleccione..."
                                            :showNoOptions="false"
                                            :showNoResults="false"
                                        >
                                        </multiselect>
                                        <div class="valid-feedback"></div>
                                        <div class="invalid-feedback">
                                            <li v-for="item in errors.estatus" :key="item">
                                                {{ item }}
                                            </li>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-12 col-sm-12 col-12">
                                <div class="form-group">
                                    <label>Referencia</label>
                                    <textarea
                                        class="form-control mb-2"
                                        placeholder="Referencia"
                                        v-model="form.referencia"
                                        :class="[
                                            is_entrada
                                                ? !errors.referencia
                                                    ? 'is-valid'
                                                    : 'is-invalid'
                                                : '',
                                        ]"
                                    >
                                    </textarea>
                                    <div class="valid-feedback"></div>
                                    <div class="invalid-feedback">
                                        <li v-for="item in errors.referencia" :key="item">
                                            {{ item }}
                                        </li>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 m-1">
                                    <div class="form-group">
                                        <button
                                            type="button"
                                            class="btn btn-black w-100"
                                            v-show="editedIndex === -1"
                                            @click="createDireccion"
                                        >
                                            Guardar
                                        </button>

                                        <button
                                            type="button"
                                            class="btn btn-black w-100"
                                            v-show="editedIndex !== -1"
                                            @click="updateDireccion"
                                        >
                                            Actualizar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <!-- Eliminar Modal -->
        <div
            class="modal fade"
            id="deleteModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
        >
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">
                            ¿Estás seguro de eliminar este registro?
                        </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="deleteDireccion()"
                        >
                            Aceptar
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <loading
        v-model:active="isLoading"
        :can-cancel="false"
        :is-full-page="true"/>
    </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 * as UserRepository from "@/repositories/UserRepository";
import * as DireccionEntregaRepository from "@/repositories/DireccionEntregaRepositoriy";
import * as ClienteRepository from "@/repositories/ClienteRepository";
import axios from "axios";
import Multiselect from "@suadelabs/vue3-multiselect";
import "@suadelabs/vue3-multiselect/dist/vue3-multiselect.css";
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';

useMeta({ title: "EGURROLA" });

const store = useAuthStore();
const obtener_direcciones = ref([]);

const titulo_mo = ref("");
const route = useRoute();

//formulario crear y eliminar
let registerModal = ref(false);
let deleteModal = ref(false);
const is_entrada = ref(false);
const editedIndex = ref(-1);
const formComponent = ref(null);
const errors = ref({});
const form = ref({
    cliente_id: route.params.clienteId,
    calle:'',
    numero_exterior:'',
    numero_interior:'',
    colonia:'',
    codigo_postal:'',
    ciudad:'',
    estado:'',
    pais:'México',
    referencia:'',
    estatus:'activo',
    es_principal:'no',
});

const isLoading = ref(true);

// estatus
const optionsEstatus = ref(['activo','inactivo']);
const optionsEsPrincipal = ref(['si','no']);
//table 2
const columns1 = ref([
    'id',
    'calle',
    'numero_exterior',
    'numero_interior',
    'colonia',
    'codigo_postal',
    'ciudad',
    'estado',
    'pais',
    'es_principal',
    'estatus',
    'actions'
]);
const table_option1 = ref({
    headings: {
        id: (h, row, index) => {
            return "Folio";
        },
        actions: (h, row, index) => {
            return "";
        },
        razon_social: (h, row, index) => {
            return "Razón social";
        },
        numero_exterior: (h, row, index) => {
            return "Número exterior";
        },
        numero_interior: (h, row, index) => {
            return "Número interior";
        },
        pais: (h, row, index) => {
            return "País";
        },
        codigo_postal: (h, row, index) => {
            return "Código postal";
        },
    },
    perPage: 20,
    perPageValues: [20, 50, 100],
    skin: "table table-hover",
    columnsClasses: { actions: "actions text-center" },
    sortable: [
        "id",
        "calle",
        "numero_exterior",
        "numero_interior",
        "colonia",
        "codigo_postal",
        "ciudad",
        "estado",
        "pais",
        "es_principal",
        "estatus"
    ],
    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 createDireccion = async () => {
    try {
        isLoading.value=true;
        is_entrada.value = true;
        const response = await DireccionEntregaRepository.createDireccion(
            form.value
        );
        showMessage("Guardado correctamente");
        initializeCreate();
        close();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
};

const updateDireccion = async () => {
    try {
        isLoading.value=true;
        is_entrada.value = true;
        const response = await DireccionEntregaRepository.updateDireccion(
            form.value,
            editedIndex.value
        );
        showMessage("Actualizado correctamente");
        close();
        initializeCreate();
        initialize();
    } catch (error) {
        if (axios.isAxiosError(error))
            errors.value = error.response.data.errors;
        isLoading.value=false;
    }
};

const getDireccionId = async (id) => {
    try {
        const response = await DireccionEntregaRepository.getDireccionId(id);
        form.value = {
            cliente_id: route.params.clienteId,
            calle: response.data.calle,
            numero_exterior: response.data.numero_exterior,
            numero_interior: response.data.numero_interior,
            colonia: response.data.colonia,
            codigo_postal: response.data.codigo_postal,
            ciudad: response.data.ciudad,
            estado: response.data.estado,
            pais: response.data.pais,
            referencia: response.data.referencia,
            estatus: response.data.estatus,
            es_principal: response.data.es_principal,
        };
        errors.value = {};
        editedIndex.value = id;
        registerModal.show();
    } catch (error) {
        console.log(error);
    }
};

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

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

const deleteDireccion = async () => {
    try {
        isLoading.value=true;
        const response = await DireccionEntregaRepository.deleteDireccion(
            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 = () => {
    form.value = {
        cliente_id: route.params.clienteId,
        calle:'',
        numero_exterior:'',
        numero_interior:'',
        colonia:'',
        codigo_postal:'',
        ciudad:'',
        estado:'',
        pais:'México',
        referencia:'',
        estatus:'activo',
        es_principal:'no',
    };
    errors.value = {};
    editedIndex.value = -1;
};

const getPage = async () => {
    try {
        const response = await DireccionEntregaRepository.getPage(route.params.clienteId);
        return response.data;
    } catch (error) {
        console.log(error);
    }
};

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

const initialize = async () => {
    isLoading.value=true;
    const resp = await getPage();
    obtener_direcciones.value = resp;
    table_option1.value = {
        headings: {
            id: (h, row, index) => {
                return "Folio";
            },
            actions: (h, row, index) => {
                return "";
            },
            razon_social: (h, row, index) => {
                return "Razón social";
            },
            numero_exterior: (h, row, index) => {
                return "Número exterior";
            },
            numero_interior: (h, row, index) => {
                return "Número interior";
            },
            pais: (h, row, index) => {
                return "País";
            },
            codigo_postal: (h, row, index) => {
                return "Código postal";
            },
        },
        perPage: 100,
        perPageValues: [20, 50, 100],
        skin: "table table-hover",
        columnsClasses: { actions: "actions text-center" },
        sortable: [
            'calle',
            'numero_exterior',
            'numero_interior',
            'colonia',
            'codigo_postal',
            'ciudad',
            'estado',
            'pais',
            'es_principal',
            'estatus'
        ],
        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,
    };
    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",
    });
};

const getClienteIdPrin = async (id) => {
    try {
        const response = await ClienteRepository.getClienteId(id);
        titulo_mo.value = response.data.razonSocial;
    } catch (error) {
        console.log(error);
    }
};

onMounted(async () => {
    getClienteIdPrin(route.params.clienteId);
    const response = await obtener_user();
    store.current_user.id = response.id;
    store.current_user.name = response.name;
    store.current_user.email = response.email;
    registerModal = new window.bootstrap.Modal(
        document.getElementById("registerModal")
    );
    deleteModal = new window.bootstrap.Modal(
        document.getElementById("deleteModal")
    );

    initialize();
});
</script>
