<script setup>
import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useQuasar, useDialogPluginComponent } 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 { dialogRef } = useDialogPluginComponent();
const quasar = useQuasar();
const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();

const rectificativeTypeOptions = ref([]);
const siiTypeInvoiceOutsOptions = ref([]);
const checked = ref(true);
const transferInvoiceParams = reactive({
    id: $props.invoiceOutData?.id,
});
const invoiceCorrectionTypesOptions = ref([]);

const selectedClient = (client) => {
    transferInvoiceParams.selectedClientData = client;
};

const makeInvoice = async () => {
    const hasToInvoiceByAddress =
        transferInvoiceParams.selectedClientData.hasToInvoiceByAddress;

    const params = {
        id: transferInvoiceParams.id,
        cplusRectificationTypeFk: transferInvoiceParams.cplusRectificationTypeFk,
        siiTypeInvoiceOutFk: transferInvoiceParams.siiTypeInvoiceOutFk,
        invoiceCorrectionTypeFk: transferInvoiceParams.invoiceCorrectionTypeFk,
        newClientFk: transferInvoiceParams.newClientFk,
        makeInvoice: checked.value,
    };

    try {
        if (checked.value && hasToInvoiceByAddress) {
            const response = await new Promise((resolve) => {
                quasar
                    .dialog({
                        component: VnConfirm,
                        componentProps: {
                            title: t('Bill destination client'),
                            message: t('transferInvoiceInfo'),
                        },
                    })
                    .onOk(() => {
                        resolve(true);
                    })
                    .onCancel(() => {
                        resolve(false);
                    });
            });
            if (!response) {
                return;
            }
        }

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

<template>
    <FetchData
        url="CplusRectificationTypes"
        :filter="{ order: 'description' }"
        @on-fetch="
            (data) => (
                (rectificativeTypeOptions = data),
                (transferInvoiceParams.cplusRectificationTypeFk = data.filter(
                    (type) => type.description == 'I – Por diferencias'
                )[0].id)
            )
        "
        auto-load
    />
    <FetchData
        url="SiiTypeInvoiceOuts"
        :filter="{ where: { code: { like: 'R%' } } }"
        @on-fetch="
            (data) => (
                (siiTypeInvoiceOutsOptions = data),
                (transferInvoiceParams.siiTypeInvoiceOutFk = data.filter(
                    (type) => type.code == 'R4'
                )[0].id)
            )
        "
        auto-load
    />
    <FetchData
        url="InvoiceCorrectionTypes"
        @on-fetch="(data) => (invoiceCorrectionTypesOptions = data)"
        auto-load
    />
    <QDialog ref="dialogRef">
        <FormPopup
            @on-submit="makeInvoice()"
            :title="t('Transfer invoice')"
            :custom-submit-button-label="t('Transfer client')"
            :default-cancel-button="false"
        >
            <template #form-inputs>
                <VnRow>
                    <VnSelect
                        :label="t('Client')"
                        :options="clientsOptions"
                        hide-selected
                        option-label="name"
                        option-value="id"
                        v-model="transferInvoiceParams.newClientFk"
                        :required="true"
                        url="Clients"
                        :fields="['id', 'name', 'hasToInvoiceByAddress']"
                        auto-load
                    >
                        <template #option="scope">
                            <QItem
                                v-bind="scope.itemProps"
                                @click="selectedClient(scope.opt)"
                            >
                                <QItemSection>
                                    <QItemLabel>
                                        #{{ scope.opt?.id }} - {{ scope.opt?.name }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                    <VnSelect
                        :label="t('Rectificative type')"
                        :options="rectificativeTypeOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="transferInvoiceParams.cplusRectificationTypeFk"
                        :required="true"
                    />
                </VnRow>
                <VnRow>
                    <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>
                    <VnSelect
                        :label="t('Type')"
                        :options="invoiceCorrectionTypesOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="transferInvoiceParams.invoiceCorrectionTypeFk"
                        :required="true"
                    />
                </VnRow>
                <VnRow>
                    <div>
                        <QCheckbox
                            :label="t('Bill destination client')"
                            v-model="checked"
                        />
                        <QIcon name="info" class="cursor-info q-ml-sm" size="sm">
                            <QTooltip>{{ t('transferInvoiceInfo') }}</QTooltip>
                        </QIcon>
                    </div>
                </VnRow>
            </template>
        </FormPopup>
    </QDialog>
</template>

<i18n>
en:
    checkInfo: New tickets from the destination customer will be generated in the consignee by default.
    transferInvoiceInfo: Destination customer is marked to bill in the consignee
    confirmTransferInvoice: The destination customer has selected 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
    transferInvoiceInfo: Los nuevos tickets del cliente destino, serán generados en el consignatario por defecto.
    confirmTransferInvoice: El cliente destino tiene marcado facturar por consignatario, desea continuar?
</i18n>
