<script setup>
import { reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import VnInput from 'src/components/common/VnInput.vue';
import VnRow from 'components/ui/VnRow.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const $props = defineProps({
    ticket: {
        type: Boolean,
        default: false,
    },
    withRoute: {
        type: Boolean,
        default: false,
    },
    selectedExpeditions: {
        type: Array,
        default: () => [],
    },
});

const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();

const newTicketFormData = reactive({});
const date = new Date();

const createTicket = async () => {
    try {
        const expeditionIds = $props.selectedExpeditions.map(
            (expedition) => expedition.id
        );
        const params = {
            clientId: $props.ticket.clientFk,
            landed: newTicketFormData.landed,
            warehouseId: $props.ticket.warehouseFk,
            addressId: $props.ticket.addressFk,
            agencyModeId: $props.ticket.agencyModeFk,
            routeId: newTicketFormData.routeFk,
            expeditionIds: expeditionIds,
        };

        const { data } = await axios.post('Expeditions/moveExpeditions', params);
        notify(t('globals.dataSaved'), 'positive');
        router.push({ name: 'TicketSummary', params: { id: data.id } });
    } catch (error) {
        console.error(error);
    }
};
</script>

<template>
    <FormModelPopup
        model="expeditionNewTicket"
        :form-initial-data="newTicketFormData"
        :save-fn="createTicket"
    >
        <template #form-inputs="{ data }">
            <VnRow>
                <VnInputDate
                    :label="t('expedition.landed')"
                    v-model="data.landed"
                    :model-value="date"
                />
            </VnRow>
            <VnRow>
                <VnInput
                    v-if="withRoute"
                    :label="t('expedition.routeId')"
                    v-model="data.routeFk"
                />
            </VnRow>
        </template>
    </FormModelPopup>
</template>
