<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 messages = [];

    const hasProblemWithTax = (
        await axios.get('InvoiceInTaxes/count', {
            params: {
                where: JSON.stringify({
                    invoiceInFk: id,
                    or: [{ taxTypeSageFk: null }, { transactionTypeSageFk: null }],
                }),
            },
        })
    ).data?.count;

    if (hasProblemWithTax)
        messages.push(t('The VAT and Transaction fields have not been informed'));

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

    if (taxableBaseNotEqualDueDay && vatNotEqualDueDay)
        messages.push(t('The sum of the taxable bases does not match the due dates'));

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

    if (dueDaysCount) messages.push(t('Some due dates are less than or equal to today'));

    if (!messages.length) toBook(id);
    else
        dialog({
            component: VnConfirm,
            componentProps: {
                title: t('Are you sure you want to book this invoice?'),
                message: messages.reduce((acc, msg) => `${acc}<p>${msg}</p>`, ''),
                promise: () => toBook(id),
            },
        });
}

async function toBook(id) {
    let err = false;
    try {
        await axios.post(`InvoiceIns/${id}/toBook`);
        store.data.isBooked = true;
    } catch (e) {
        err = true;
        throw e;
    } finally {
        if (!err) notify({ type: 'positive', message: t('globals.dataSaved') });
    }
}
</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
    Some due dates are less than or equal to today: Algún vencimiento tiene una fecha menor o igual que hoy
    The sum of the taxable bases does not match the due dates: La suma de las bases imponibles no coincide con la de los vencimientos
    The VAT and Transaction fields have not been informed: No se han informado los campos de iva y/o transacción
</i18n>
