<script setup>
    import { onMounted, ref } from 'vue';
    import { useCompanyStore } from '../stores/company';
    import Spiner from './ui/Spiner.vue';
    import { useVehiclesStore } from '../stores/vehicles';
    import Swal from 'sweetalert2';

    const props = defineProps({
        vehicle: {
            type: Object,
            required: true
        }
    });

    defineEmits(['reset-vehicle']);

    const companyStore = useCompanyStore();
    const vehicleStore = useVehiclesStore();

    const driverSelected = ref(null);
    const drivers = ref([]);
    const error = ref(null)
    const loading = ref(false);

    onMounted(() => {   
        drivers.value = companyStore.users?.filter((u) => u.job_role == 'driver');
        if(props?.vehicle?.driver) {
            const index = drivers.value.findIndex((d) => d._id === props.vehicle.driver?._id);
            driverSelected.value = drivers.value[index];
        }
    });

    const handleSetDriver = async() => {
        if(driverSelected.value === null) {
            error.value = 'Seleccione un conductor';
            return 
        }

        let vehicle_id = props.vehicle._id;
        let driver_id = driverSelected.value._id;

        let vehicleData ={
            driver : driverSelected.value
        }
        let localData ={
            driver : driverSelected.value,
            categories: props.vehicle.categories
        }
        loading.value = true;
        const result = await vehicleStore.updateVehicleCompany(vehicle_id, vehicleData, localData);
        
        if( result === 'success' ) {
            //Actualizamos el vehiculo
            let userData = {
                vehicle : vehicle_id
            }

            let localUser = {
                categories: driverSelected.value.categories,
            }
            
            const result2 = await companyStore.updateUserCompany(driver_id, userData, localUser);
            if(result2 === 'success' ){
                document.getElementById('btnCloseeditDriverVehicle').click();
                Swal.fire({
                    title: `<strong>Driver asignado con éxito!</strong>`,
                    icon: 'success'
                });
            } else {
                Swal.fire({
                    title: result2,
                    icon: 'error'
                })
            }
        } else {
            Swal.fire({
                title: result,
                icon: 'error'
            })
        }
        
        loading.value = false;

        //Continua en la lina 568 web_main

    }


</script>

<template>
    <div class="modal fade" id="editDriverVehicle" tabindex="-1" role="dialog" aria-labelledby="editDriverVehicle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="title mt-2 mb-3">Cambiar conductor</h2>
                    <button 
                        id="btnCloseeditDriverVehicle" 
                        type="button" 
                        class="close bg-white" 
                        data-dismiss="modal" 
                        aria-label="Close"
                        @click="$emit('reset-vehicle')"
                    >
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body view-proposals">
                    <div class="custom-selected-field">
                        <label class="custom-label my-2" for="driver">Conductor asignado:</label>
                        <select 
                            class="custom-input-light"
                            name="driver" 
                            id="driver" 
                            v-model="driverSelected"
                        >
                            <option disabled value="">-- Seleccionar conductor --</option>
                            <option v-for="driver in drivers" :value="driver">{{driver.name}}</option>
                        </select>
                        <span class="error-msg" v-if="error">{{ error }}</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <Spiner v-if="loading"/>
                    <div v-else class="btns-footer">
                        <button 
                            type="button" 
                            class="btn btn-dark radius-sm" 
                            data-dismiss="modal"
                            @click="$emit('reset-vehicle')"
                        >Cancelar</button>
                        <button 
                            class="btn-primary-sm radius-sm"
                            @click="handleSetDriver"
                        >
                            <span class="clear-xsm">Guardar</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
    .custom-selected-field {
        display: flex;
        flex-direction: column;
        margin-bottom: 16px;
    }

    .btns-footer {
        display: flex;
        gap: 1rem;
    }
</style>