<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 { useState } from 'src/composables/useState';
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 state = useState();
const entryDescriptorRef = ref(null);
const url = ref();

const entryFilter = {
    include: [
        {
            relation: 'travel',
            scope: {
                fields: ['id', 'landed', 'shipped', 'agencyModeFk', 'warehouseOutFk'],
                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 currentEntry = computed(() => state.get('entry'));

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>
            <QCardActions class="q-gutter-x-md">
                <QIcon
                    v-if="currentEntry?.isExcludedFromAvailable"
                    name="vn:inventory"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Inventory entry') }}</QTooltip>
                </QIcon>
                <QIcon
                    v-if="currentEntry?.isRaid"
                    name="vn:net"
                    color="primary"
                    size="xs"
                >
                    <QTooltip>{{ t('Virtual entry') }}</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>
