<script setup>
import { onMounted, inject, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';

import TicketDetails from 'src/pages/Ecomerce/TicketDetails.vue';

import { useUserStore } from 'stores/user';
import { useAppStore } from 'stores/app';
import { storeToRefs } from 'pinia';

const { t } = useI18n();
const jApi = inject('jApi');
const route = useRoute();
const userStore = useUserStore();
const appStore = useAppStore();
const { isHeaderMounted } = storeToRefs(appStore);

const ticket = ref({});
const rows = ref([]);
const services = ref(null);
const packages = ref(null);

onMounted(async () => {
    const params = {
        ticket: parseInt(route.params.id)
    };
    ticket.value = await jApi.getObject('CALL myTicket_get(#ticket)', params);
    rows.value = await jApi.query('CALL myTicket_getRows(#ticket)', params);
    services.value = await jApi.query(
        'CALL myTicket_getServices(#ticket)',
        params
    );
    packages.value = await jApi.query(
        'CALL myTicket_getPackages(#ticket)',
        params
    );
});

const onPrintClick = () => {
    const params = new URLSearchParams({
        access_token: userStore.token,
        recipientId: userStore.id,
        type: 'deliveryNote'
    });
    window.open(
        `/api/Tickets/${ticket.value.id}/delivery-note-pdf?${params.toString()}`
    );
};
</script>

<template>
    <Teleport v-if="isHeaderMounted" to="#actions">
        <QBtn
            icon="print"
            :label="t('printDeliveryNote')"
            @click="onPrintClick()"
            rounded
            no-caps
        />
    </Teleport>
    <QPage>
        <TicketDetails :rows="rows" :ticket="ticket" />
    </QPage>
</template>

<i18n lang="yaml">
en-US:
    printDeliveryNote: Print delivery note
es-ES:
    printDeliveryNote: Imprimir albarán
ca-ES:
    printDeliveryNote: Imprimir albarà
fr-FR:
    printDeliveryNote: Imprimer bulletin de livraison
pt-PT:
    printDeliveryNote: Imprimir nota de entrega
</i18n>
