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

import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import useCardDescription from 'src/composables/useCardDescription';

import { toDate } from 'src/filters';
import { usePrintService } from 'composables/usePrintService';
import { getUrl } from 'src/composables/getUrl';

const $props = defineProps({
    id: {
        type: Number,
        required: false,
        default: null,
    },
});

const route = useRoute();
const { t } = useI18n();
const { openReport } = usePrintService();
const entryDescriptorRef = ref(null);
const url = ref();

const entryFilter = {
    include: [
        {
            relation: 'travel',
            scope: {
                fields: [
                    'id',
                    'landed',
                    'shipped',
                    'agencyModeFk',
                    'warehouseOutFk',
                    'daysInForward',
                ],
                include: [
                    {
                        relation: 'agency',
                        scope: {
                            fields: ['name'],
                        },
                    },
                    {
                        relation: 'warehouseOut',
                        scope: {
                            fields: ['name'],
                        },
                    },
                    {
                        relation: 'warehouseIn',
                        scope: {
                            fields: ['name'],
                        },
                    },
                ],
            },
        },
        {
            relation: 'supplier',
            scope: {
                fields: ['id', 'nickname'],
            },
        },
    ],
};

const entityId = computed(() => {
    return $props.id || route.params.id;
});
onMounted(async () => {
    url.value = await getUrl('');
});

const data = ref(useCardDescription());
const setData = (entity) =>
    (data.value = useCardDescription(entity.supplier?.nickname, entity.id));

const getEntryRedirectionFilter = (entry) => {
    let entryTravel = entry && entry.travel;

    if (!entryTravel || !entryTravel.landed) return null;

    const date = new Date(entryTravel.landed);
    date.setHours(0, 0, 0, 0);

    const from = new Date(date.getTime());
    from.setDate(from.getDate() - 10);

    const to = new Date(date.getTime());
    to.setDate(to.getDate() + 10);

    return JSON.stringify({
        supplierFk: entry.supplierFk,
        from,
        to,
    });
};

const showEntryReport = () => {
    openReport(`Entries/${route.params.id}/entry-order-pdf`);
};

watch;
</script>

<template>
    <CardDescriptor
        ref="entryDescriptorRef"
        module="Entry"
        :url="`Entries/${entityId}`"
        :filter="entryFilter"
        :title="data.title"
        :subtitle="data.subtitle"
        @on-fetch="setData"
        data-key="entry"
    >
        <template #menu="{ entity }">
            <QItem v-ripple clickable @click="showEntryReport(entity)">
                <QItemSection>{{ t('Show entry report') }}</QItemSection>
            </QItem>
        </template>
        <template #body="{ entity }">
            <VnLv
                :label="t('entry.descriptor.agency')"
                :value="entity.travel?.agency?.name"
            />
            <VnLv :label="t('shipped')" :value="toDate(entity.travel?.shipped)" />
            <VnLv :label="t('landed')" :value="toDate(entity.travel?.landed)" />
            <VnLv
                :label="t('entry.descriptor.warehouseOut')"
                :value="entity.travel?.warehouseOut?.name"
            />
        </template>
        <template #icons="{ entity }">
            <QCardActions class="q-gutter-x-md">
                <QIcon
                    v-if="entity?.isExcludedFromAvailable"
                    name="vn:inventory"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Inventory entry') }}</QTooltip>
                </QIcon>
                <QIcon
                    v-if="entity?.travel?.daysInForward"
                    name="vn:net"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>
                        {{
                            t('globals.raid', {
                                daysInForward: entity?.travel?.daysInForward,
                            })
                        }}</QTooltip
                    >
                </QIcon>
            </QCardActions>
        </template>
        <template #actions="{ entity }">
            <QCardActions>
                <QBtn
                    :to="`/supplier/${entity.supplier.id}`"
                    size="md"
                    icon="vn:supplier"
                    color="primary"
                >
                    <QTooltip>{{ t('Supplier card') }}</QTooltip>
                </QBtn>
                <QBtn
                    :to="{
                        name: 'TravelMain',
                        query: {
                            params: JSON.stringify({
                                agencyModeFk: entity.travel?.agencyModeFk,
                            }),
                        },
                    }"
                    size="md"
                    icon="local_airport"
                    color="primary"
                >
                    <QTooltip>{{ t('All travels with current agency') }}</QTooltip>
                </QBtn>
                <QBtn
                    :to="{
                        name: 'EntryMain',
                        query: {
                            params: getEntryRedirectionFilter(entity),
                        },
                    }"
                    size="md"
                    icon="vn:entry"
                    color="primary"
                >
                    <QTooltip>{{ t('All entries with current supplier') }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </CardDescriptor>
</template>
<i18n>
es:
    Supplier card: Ficha del proveedor
    All travels with current agency: Todos los envíos con la agencia actual
    All entries with current supplier: Todas las entradas con el proveedor actual
    Show entry report: Ver informe del pedido
    Go to module index: Ir al índice del modulo
    Inventory entry: Es inventario
    Virtual entry: Es una redada
</i18n>
