<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';
import VnConfirm from 'components/ui/VnConfirm.vue';
import VnRow from 'components/ui/VnRow.vue';
import FetchData from 'components/FetchData.vue';
import VnSelect from 'components/common/VnSelect.vue';
import FormPopup from './FormPopup.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const $props = defineProps({
    invoiceOutData: {
        type: Object,
        default: () => {},
    },
});

const quasar = useQuasar();
const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();
const checked = ref(true);
let skip = 0;

const transferInvoiceParams = reactive({
    id: $props.invoiceOutData?.id,
    refFk: $props.invoiceOutData?.ref,
});
const closeButton = ref(null);
const clientsOptions = ref([]);
const rectificativeTypeOptions = ref([]);
const siiTypeInvoiceOutsOptions = ref([]);
const invoiceCorrectionTypesOptions = ref([]);

const closeForm = () => {
    if (closeButton.value) closeButton.value.click();
};

onMounted(async () => {
    await fetchClients();
});

const fetchClients = async () => {
    try {
        const filter = {
            skip: skip,
            order: 'id DESC',
            limit: 10,
        };
        const { data } = await axios.get('http://localhost:9000/api/Clients/filter', {
            params: {
                filter: serializeFilter(filter),
            },
        });
        clientsOptions.value = [...clientsOptions.value, ...data];
        skip += 10;
    } catch (error) {
        console.error('Error fetching clients:', error);
    }
};

const serializeFilter = (filter) => {
    let serializedFilter = '{';
    for (const key in filter) {
        serializedFilter += `"${key}":${JSON.stringify(filter[key])},`;
    }
    serializedFilter = serializedFilter.slice(0, -1);
    serializedFilter += '}';
    return serializedFilter;
};

const handleScroll = async () => {
    const selectEl = document.querySelector('.vn-select');
    if (selectEl.scrollTop + selectEl.clientHeight >= selectEl.scrollHeight) {
        await fetchClients();
    }
};
const transferInvoice = async () => {
    const params = {
        id: transferInvoiceParams.id,
        cplusRectificationTypeFk: transferInvoiceParams.cplusRectificationTypeFk,
        invoiceCorrectionTypeFk: transferInvoiceParams.invoiceCorrectionTypeFk,
        newClientFk: transferInvoiceParams.newClientFk,
        refFk: transferInvoiceParams.refFk,
        siiTypeInvoiceOutFk: transferInvoiceParams.siiTypeInvoiceOutFk,
        checked: checked.value,
    };

    try {
        const clientDetails = await axios.get(
            `Clients/${transferInvoiceParams.newClientFk}`
        );

        if (checked.value && clientDetails.data.hasToInvoiceByAddress)
            quasar.dialog({
                component: VnConfirm,
                componentProps: {
                    title: t('Bill destination client'),
                    message: t('confirmationInfo'),
                },
            });

        const { data } = await axios.post('InvoiceOuts/transferInvoice', params);
        notify(t('Transferred invoice'), 'positive');
        closeForm();
        router.push('InvoiceOutSummary', { id: data.id });
    } catch (err) {
        console.error('Error transfering invoice', err);
    }
};
</script>

<template>
    <FetchData
        url="Clients"
        @on-fetch="(data) => (clientsOptions = data)"
        :filter="{ fields: ['id', 'name'], order: 'id', limit: 30 }"
        auto-load
    />
    <FetchData
        url="CplusRectificationTypes"
        :filter="{ order: 'description' }"
        @on-fetch="
            (data) => (
                (rectificativeTypeOptions = data),
                (transferInvoiceParams.cplusRectificationTypeFk = data[1].id)
            )
        "
        auto-load
    />
    <FetchData
        url="SiiTypeInvoiceOuts"
        :filter="{ where: { code: { like: 'R%' } } }"
        @on-fetch="
            (data) => (
                (siiTypeInvoiceOutsOptions = data),
                (transferInvoiceParams.siiTypeInvoiceOutFk = data[3].id)
            )
        "
        auto-load
    />
    <FetchData
        url="InvoiceCorrectionTypes"
        @on-fetch="(data) => (invoiceCorrectionTypesOptions = data)"
        auto-load
    />
    <FormPopup
        @on-submit="transferInvoice()"
        :title="t('Transfer invoice')"
        :custom-submit-button-label="t('Transfer client')"
        :default-cancel-button="false"
    >
        <template #form-inputs>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelect
                        :label="t('Client')"
                        :options="clientsOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="transferInvoiceParams.newClientFk"
                        :required="true"
                        @scroll="handleScroll"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>
                                        #{{ scope.opt?.id }} -
                                        {{ scope.opt?.name }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                </div>
                <div class="col">
                    <VnSelect
                        :label="t('Rectificative type')"
                        :options="rectificativeTypeOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="transferInvoiceParams.cplusRectificationTypeFk"
                        :required="true"
                    />
                </div>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <div class="col">
                    <VnSelect
                        :label="t('Class')"
                        :options="siiTypeInvoiceOutsOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="transferInvoiceParams.siiTypeInvoiceOutFk"
                        :required="true"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>
                                        {{ scope.opt?.code }} -
                                        {{ scope.opt?.description }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                </div>
                <div class="col">
                    <VnSelect
                        :label="t('Type')"
                        :options="invoiceCorrectionTypesOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="transferInvoiceParams.invoiceCorrectionTypeFk"
                        :required="true"
                    />
                </div>
            </VnRow>
            <VnRow class="row q-gutter-md q-mb-md">
                <div>
                    <QCheckbox :label="t('Bill destination client')" v-model="checked" />
                    <QIcon name="info" class="cursor-info q-ml-sm" size="sm">
                        <QTooltip>{{ t('checkInfo') }}</QTooltip>
                    </QIcon>
                </div>
            </VnRow>
        </template>
    </FormPopup>
</template>

<i18n>
en:
    checkInfo: New tickets from the destination customer will be generated in the consignee by default.
    confirmationInfo: Destination customer is marked to bill in the consignee, do you want to continue?
es:
    Transfer invoice: Transferir factura
    Transfer client: Transferir cliente
    Client: Cliente
    Rectificative type: Tipo rectificativa
    Class: Clase
    Type: Tipo
    Transferred invoice: Factura transferida
    Bill destination client: Facturar cliente destino
    checkInfo: Los nuevos tickets del cliente destino, serán generados en el consignatario por defecto.
    confirmationInfo: El cliente destino tiene marcado facturar por consignatario, desea continuar?
</i18n>
