<script setup>
import { ref, reactive, computed, onBeforeMount } from 'vue';
import { useRouter, onBeforeRouteUpdate } from 'vue-router';
import { useI18n } from 'vue-i18n';
import axios from 'axios';
import { toCurrency, toDate } from 'src/filters';
import VnLv from 'src/components/ui/VnLv.vue';
import EntityDescriptor from 'components/ui/EntityDescriptor.vue';
import SupplierDescriptorProxy from 'src/pages/Supplier/Card/SupplierDescriptorProxy.vue';
import filter from './InvoiceInFilter.js';
import InvoiceInDescriptorMenu from './InvoiceInDescriptorMenu.vue';

const $props = defineProps({ id: { type: Number, default: null } });
const { currentRoute } = useRouter();
const { t } = useI18n();

const cardDescriptorRef = ref();
const entityId = computed(() => $props.id || +currentRoute.value.params.id);
const totalAmount = ref();
const invoiceInCorrection = reactive({ correcting: [], corrected: null });
const routes = reactive({
    getSupplier: (id) => {
        return { name: 'SupplierCard', params: { id } };
    },
    getInvoices: (id) => {
        return {
            name: 'InvoiceInList',
            query: {
                table: JSON.stringify({ supplierFk: id }),
            },
        };
    },
    getCorrection: (invoiceInCorrection) => {
        if (invoiceInCorrection.correcting.length > 1) {
            return {
                name: 'InvoiceInList',
                query: {
                    table: JSON.stringify({ correctedFk: entityId.value }),
                },
            };
        }

        return {
            name: 'InvoiceInCard',
            params: {
                id: invoiceInCorrection.corrected ?? invoiceInCorrection.correcting[0],
            },
        };
    },
    getEntry: (id) => {
        return { name: 'EntryCard', params: { id } };
    },
});

onBeforeMount(async () => {
    await setInvoiceCorrection(entityId.value);
    const { data } = await axios.get(`InvoiceIns/${entityId.value}/getTotals`);
    totalAmount.value = data.totalDueDay;
});

onBeforeRouteUpdate(async (to, from) => {
    if (to.params.id !== from.params.id) {
        await setInvoiceCorrection(to.params.id);
        const { data } = await axios.get(`InvoiceIns/${to.params.id}/getTotals`);
        totalAmount.value = data.totalDueDay;
    }
});

async function setInvoiceCorrection(id) {
    invoiceInCorrection.correcting.length = 0;
    invoiceInCorrection.corrected = null;
    const { data: correctingData } = await axios.get('InvoiceInCorrections', {
        params: { filter: { where: { correctingFk: id } } },
    });
    const { data: correctedData } = await axios.get('InvoiceInCorrections', {
        params: { filter: { where: { correctedFk: id } } },
    });

    if (correctingData[0]) invoiceInCorrection.corrected = correctingData[0].correctedFk;

    invoiceInCorrection.correcting = correctedData.map(
        (corrected) => corrected.correctingFk,
    );
}
</script>
<template>
    <EntityDescriptor
        ref="cardDescriptorRef"
        data-key="InvoiceIn"
        :url="`InvoiceIns/${entityId}`"
        :filter="filter"
        title="supplierRef"
        width="xlg-width"
    >
        <template #menu="{ entity }">
            <InvoiceInDescriptorMenu :invoice="entity" />
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('invoiceIn.list.issued')" :value="toDate(entity.issued)" />
            <VnLv
                :label="t('invoiceIn.summary.bookedDate')"
                :value="toDate(entity.booked)"
            />
            <VnLv :label="t('invoiceIn.list.amount')" :value="toCurrency(totalAmount)" />
            <VnLv :label="t('invoiceIn.list.supplier')">
                <template #value>
                    <span class="link" data-cy="invoiceInDescriptor_supplier">
                        {{ entity?.supplier?.nickname }}
                        <SupplierDescriptorProxy :id="entity?.supplierFk" />
                    </span>
                </template>
            </VnLv>
        </template>
        <template #actions="{ entity }">
            <QCardActions>
                <QBtn
                    size="md"
                    icon="vn:supplier"
                    color="primary"
                    :to="routes.getSupplier(entity.supplierFk)"
                >
                    <QTooltip>{{ t('globals.supplier') }}</QTooltip>
                </QBtn>
                <QBtn
                    size="md"
                    icon="vn:entry"
                    color="primary"
                    :to="routes.getEntry(entity.entryFk)"
                >
                    <QTooltip>{{ t('globals.entry') }}</QTooltip>
                </QBtn>
                <QBtn
                    size="md"
                    icon="vn:invoice-in"
                    color="primary"
                    :to="routes.getInvoices(entity.supplierFk)"
                >
                    <QTooltip>{{ t('invoiceIn.descriptor.invoices') }}</QTooltip>
                </QBtn>
                <QBtn
                    v-if="
                        invoiceInCorrection.corrected ||
                        invoiceInCorrection.correcting.length
                    "
                    size="md"
                    :icon="
                        invoiceInCorrection.corrected
                            ? 'vn:link-to-corrected'
                            : 'vn:link-to-correcting'
                    "
                    color="primary"
                    :to="routes.getCorrection(invoiceInCorrection)"
                >
                    <QTooltip>{{
                        invoiceInCorrection.corrected
                            ? t('Original invoice')
                            : t('Rectificative invoice')
                    }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </EntityDescriptor>
</template>
<style lang="scss" scoped>
.q-dialog {
    .q-card {
        max-width: 45em;
    }
    .q-field:nth-child(1) {
        padding-bottom: 20px;
    }
}

@media (max-width: $breakpoint-xs) {
    .q-dialog {
        .q-card__section:nth-child(2) {
            .q-item,
            .q-item__section {
                flex-direction: column;
            }
        }
    }
}
</style>
