<script setup>
import axios from 'axios';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
import { useArrayData } from 'src/composables/useArrayData';
const { notify, dialog } = useQuasar();
const { t } = useI18n();

defineExpose({ checkToBook });

const { store } = useArrayData();

async function checkToBook(id) {
    let directBooking = true;

    const { data: totals } = await axios.get(`InvoiceIns/${id}/getTotals`);
    const taxableBaseNotEqualDueDay = totals.totalDueDay != totals.totalTaxableBase;
    const vatNotEqualDueDay = totals.totalDueDay != totals.totalVat;

    if (taxableBaseNotEqualDueDay && vatNotEqualDueDay) directBooking = false;

    const { data: dueDaysCount } = await axios.get('InvoiceInDueDays/count', {
        where: {
            invoiceInFk: id,
            dueDated: { gte: Date.vnNew() },
        },
    });

    if (dueDaysCount) directBooking = false;

    if (directBooking) return toBook(id);

    dialog({
        component: VnConfirm,
        componentProps: { title: t('Are you sure you want to book this invoice?') },
    }).onOk(async () => await toBook(id));
}

async function toBook(id) {
    let type = 'positive';
    let message = t('globals.dataSaved');

    try {
        await axios.post(`InvoiceIns/${id}/toBook`);
        store.data.isBooked = true;
    } catch (e) {
        type = 'negative';
        message = t('It was not able to book the invoice');
    } finally {
        notify({ type, message });
    }
}
</script>
<template>
    <slot name="content" :book="checkToBook" />
</template>
<i18n>
es:
    Are you sure you want to book this invoice?: ¿Estás seguro de querer asentar esta factura?
    It was not able to book the invoice: No se pudo contabilizar la factura
</i18n>
