<script setup>
import { useDialogPluginComponent } from 'quasar';
import { useI18n } from 'vue-i18n';
import { reactive, ref } from 'vue';
import axios from 'axios';
import FetchData from 'components/FetchData.vue';
import RoadmapAddStopForm from 'pages/Route/Roadmap/RoadmapAddStopForm.vue';

const emit = defineEmits([...useDialogPluginComponent.emits]);
const { dialogRef, onDialogHide } = useDialogPluginComponent();

const { t } = useI18n();
const props = defineProps({
    roadmapFk: {
        type: Number,
        required: true,
    },
});

const isLoading = ref(false);
const roadmapStopForm = reactive({
    roadmapFk: Number(props.roadmapFk) || 0,
    warehouseFk: null,
    eta: new Date().toISOString(),
    description: '',
});

const updateDefaultStop = (data) => {
    const eta = new Date(data.etd);
    eta.setDate(eta.getDate() + 1);
    roadmapStopForm.eta = eta.toISOString();
};

const onSave = async () => {
    isLoading.value = true;
    try {
        await axios.post('ExpeditionTrucks', { ...roadmapStopForm });
        emit('ok');
    } finally {
        isLoading.value = false;
        emit('hide');
    }
};
</script>
<template>
    <FetchData
        :url="`Roadmaps/${roadmapFk}`"
        auto-load
        :filter="{ fields: ['etd'] }"
        @on-fetch="updateDefaultStop"
    />
    <QDialog ref="dialogRef" @hide="onDialogHide">
        <QCard class="q-pa-lg">
            <QCardSection class="row absolute absolute-top z-fullscreen">
                <QSpace />
                <QBtn icon="close" flat round dense v-close-popup />
            </QCardSection>
            <RoadmapAddStopForm
                :roadmap-fk="roadmapFk"
                :form-data="roadmapStopForm"
                layout="dialog"
            />
            <QCardActions align="right">
                <QBtn :label="t('globals.cancel')" color="primary" flat v-close-popup />
                <QBtn
                    :label="t('globals.confirm')"
                    color="primary"
                    :loading="isLoading"
                    @click="onSave"
                    unelevated
                />
            </QCardActions>
        </QCard>
    </QDialog>
</template>
<style lang="scss" scoped>
.card-section {
    gap: 16px;
}
</style>

<i18n>
es:
    Warehouse: Almacén
    ETA date: Fecha ETA
    ETA time: Hora ETA
    Description: Descripción
</i18n>
