<script setup>
import { ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import axios from 'axios';
import { toCurrency, toDate } from 'src/filters';
import { useRole } from 'src/composables/useRole';
import useCardDescription from 'src/composables/useCardDescription';
import { downloadFile } from 'src/composables/downloadFile';
import { useArrayData } from 'src/composables/useArrayData';
import { usePrintService } from 'composables/usePrintService';
import VnLv from 'src/components/ui/VnLv.vue';
import CardDescriptor from 'components/ui/CardDescriptor.vue';
import FetchData from 'src/components/FetchData.vue';
import SendEmailDialog from 'components/common/SendEmailDialog.vue';
import VnConfirm from 'src/components/ui/VnConfirm.vue';

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

const route = useRoute();
const router = useRouter();
const quasar = useQuasar();
const { hasAny } = useRole();
const { t } = useI18n();
const { openReport, sendEmail } = usePrintService();
const arrayData = useArrayData('InvoiceIn');

const invoiceIn = computed(() => arrayData.store.data);
const cardDescriptorRef = ref();
const entityId = computed(() => $props.id || route.params.id);
const totalAmount = ref();
const currentAction = ref();
const config = ref();

const actions = {
    book: {
        title: 'Are you sure you want to book this invoice?',
        cb: checkToBook,
        action: toBook,
    },
    delete: {
        title: 'Are you sure you want to delete this invoice?',
        action: deleteInvoice,
    },
    clone: {
        title: 'Are you sure you want to clone this invoice?',
        action: cloneInvoice,
    },
    showPdf: {
        cb: showPdfInvoice,
    },
    sendPdf: {
        cb: sendPdfInvoiceConfirmation,
    },
};
const filter = {
    include: [
        {
            relation: 'supplier',
            scope: {
                include: {
                    relation: 'contacts',
                    scope: {
                        where: {
                            email: { neq: null },
                        },
                    },
                },
            },
        },
        {
            relation: 'invoiceInDueDay',
        },
        {
            relation: 'company',
        },
        {
            relation: 'currency',
        },
    ],
};

const data = ref(useCardDescription());

async function setData(entity) {
    data.value = useCardDescription(entity.supplierRef, entity.id);
    const { totalDueDay } = await getTotals();
    totalAmount.value = totalDueDay;
}

async function getTotals() {
    const { data } = await axios.get(`InvoiceIns/${entityId.value}/getTotals`);
    return data;
}

function openDialog() {
    quasar.dialog({
        component: VnConfirm,
        componentProps: {
            title: currentAction.value.title,
            promise: currentAction.value.action,
        },
    });
}

async function checkToBook() {
    let directBooking = true;

    const totals = await 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: entityId.value,
            dueDated: { gte: Date.vnNew() },
        },
    });

    if (dueDaysCount) directBooking = false;

    if (!directBooking) openDialog();
    else toBook();
}

async function toBook() {
    await axios.post(`InvoiceIns/${entityId.value}/toBook`);

    // Pendiente de sincronizar todo con arrayData
    quasar.notify({
        type: 'positive',
        message: t('globals.dataSaved'),
    });

    await cardDescriptorRef.value.getData();
    setTimeout(() => location.reload(), 500);
}

async function deleteInvoice() {
    await axios.delete(`InvoiceIns/${entityId.value}`);
    quasar.notify({
        type: 'positive',
        message: t('Invoice deleted'),
    });
    router.push({ path: '/invoice-in' });
}

async function cloneInvoice() {
    const { data } = await axios.post(`InvoiceIns/${entityId.value}/clone`);
    quasar.notify({
        type: 'positive',
        message: t('Invoice cloned'),
    });
    router.push({ path: `/invoice-in/${data.id}/summary` });
}

const isAdministrative = () => hasAny(['administrative']);

const isAgricultural = () =>
    invoiceIn.value.supplier.sageWithholdingFk == config.value[0].sageWithholdingFk;

function showPdfInvoice() {
    if (isAgricultural()) openReport(`InvoiceIns/${entityId.value}/invoice-in-pdf`);
}

function sendPdfInvoiceConfirmation() {
    quasar.dialog({
        component: SendEmailDialog,
        componentProps: {
            data: {
                address: invoiceIn.value.supplier.contacts[0].email,
            },
            promise: sendPdfInvoice,
        },
    });
}

function sendPdfInvoice({ address }) {
    if (!address)
        quasar.notify({
            type: 'negative',
            message: t(`The email can't be empty`),
        });
    else
        return sendEmail(`InvoiceIns/${entityId.value}/invoice-in-email`, {
            recipientId: invoiceIn.value.supplier.id,
            recipient: address,
        });
}

function triggerMenu(type) {
    currentAction.value = actions[type];
    if (currentAction.value.cb) currentAction.value.cb();
    else openDialog(type);
}
</script>

<template>
    <FetchData
        url="InvoiceInConfigs"
        :where="{ fields: ['sageWithholdingFk'] }"
        auto-load
        @on-fetch="(data) => (config = data)"
    />
    <!--Refactor para añadir en el arrayData-->
    <CardDescriptor
        ref="cardDescriptorRef"
        module="InvoiceIn"
        :url="`InvoiceIns/${entityId}`"
        :filter="filter"
        :title="data.title"
        :subtitle="data.subtitle"
        @on-fetch="setData"
        data-key="invoiceInData"
    >
        <template #menu="{ entity }">
            <QItem
                v-if="!entity.isBooked && isAdministrative()"
                v-ripple
                clickable
                @click="triggerMenu('book')"
            >
                <QItemSection>{{ t('To book') }}</QItemSection>
            </QItem>
            <QItem
                v-if="isAdministrative()"
                v-ripple
                clickable
                @click="triggerMenu('delete')"
            >
                <QItemSection>{{ t('Delete invoice') }}</QItemSection>
            </QItem>
            <QItem
                v-if="isAdministrative()"
                v-ripple
                clickable
                @click="triggerMenu('clone')"
            >
                <QItemSection>{{ t('Clone invoice') }}</QItemSection>
            </QItem>
            <QItem
                v-if="isAgricultural()"
                v-ripple
                clickable
                @click="triggerMenu('showPdf')"
            >
                <QItemSection>{{ t('Show agricultural receipt as PDF') }}</QItemSection>
            </QItem>
            <QItem
                v-if="isAgricultural()"
                v-ripple
                clickable
                @click="triggerMenu('sendPdf')"
            >
                <QItemSection
                    >{{ t('Send agricultural receipt as PDF') }}...</QItemSection
                >
            </QItem>
            <QItem
                v-if="entity.dmsFk"
                v-ripple
                clickable
                @click="downloadFile(entity.dmsFk)"
            >
                <QItemSection>{{ t('components.smartCard.downloadFile') }}</QItemSection>
            </QItem>
        </template>
        <template #body="{ entity }">
            <VnLv :label="t('invoiceIn.card.issued')" :value="toDate(entity.issued)" />
            <VnLv :label="t('invoiceIn.summary.booked')" :value="toDate(entity.booked)" />
            <VnLv :label="t('invoiceIn.card.amount')" :value="toCurrency(totalAmount)" />
            <VnLv
                :label="t('invoiceIn.summary.supplier')"
                :value="entity.supplier?.nickname"
            />
        </template>
        <template #actions="{ entity }">
            <QCardActions>
                <!--Sección proveedores no disponible-->
                <!--Sección entradas no disponible-->
                <QBtn
                    size="md"
                    icon="vn:ticket"
                    color="primary"
                    :to="{
                        name: 'InvoiceInList',
                        query: {
                            params: JSON.stringify({ supplierFk: entity.supplierFk }),
                        },
                    }"
                >
                    <QTooltip>{{ t('invoiceOut.card.ticketList') }}</QTooltip>
                </QBtn>
            </QCardActions>
        </template>
    </CardDescriptor>
</template>
<style lang="scss" scoped>
.q-dialog {
    .q-card {
        width: 35em;
    }
}
</style>
<i18n>
es:
    To book: Contabilizar
    Are you sure you want to book this invoice?: Estas seguro de querer asentar esta factura?
    Delete invoice: Eliminar factura
    Are you sure you want to delete this invoice?:  Estas seguro de querer eliminar esta factura?
    Invoice deleted: Factura eliminada
    Clone invoice: Clonar factura
    Invoice cloned: Factura clonada
    Show agricultural receipt as PDF: Ver recibo agrícola como PDF
    Send agricultural receipt as PDF: Enviar recibo agrícola como PDF
    Are you sure you want to send it?: Estás seguro que quieres enviarlo?
    Send PDF invoice: Enviar factura a PDF
</i18n>
