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

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

const refund = async () => {
    const params = {
        id: invoiceParams.id,
        withWarehouse: invoiceParams.inheritWarehouse,
        cplusRectificationTypeFk: invoiceParams.cplusRectificationTypeFk,
        siiTypeInvoiceOutFk: invoiceParams.siiTypeInvoiceOutFk,
        invoiceCorrectionTypeFk: invoiceParams.invoiceCorrectionTypeFk,
    };

    try {
        const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params);
        notify(t('Refunded invoice'), 'positive');
        const [id] = data?.refundId || [];
        if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
    } catch (err) {
        console.error('Error refunding invoice', err);
    }
};
</script>

<template>
    <FetchData
        url="CplusRectificationTypes"
        :filter="{ order: 'description' }"
        @on-fetch="
            (data) => (
                (rectificativeTypeOptions = data),
                (invoiceParams.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),
                (invoiceParams.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="refund()"
            :custom-submit-button-label="t('Accept')"
            :default-cancel-button="false"
        >
            <template #form-inputs>
                <VnRow>
                    <VnSelect
                        :label="t('Rectificative type')"
                        :options="rectificativeTypeOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="invoiceParams.cplusRectificationTypeFk"
                        :required="true"
                    />
                </VnRow>
                <VnRow>
                    <VnSelect
                        :label="t('Class')"
                        :options="siiTypeInvoiceOutsOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="invoiceParams.siiTypeInvoiceOutFk"
                        :required="true"
                    >
                        <template #option="scope">
                            <QItem v-bind="scope.itemProps">
                                <QItemSection>
                                    <QItemLabel>
                                        {{ scope.opt?.code }} -
                                        {{ scope.opt?.description }}
                                    </QItemLabel>
                                </QItemSection>
                            </QItem>
                        </template>
                    </VnSelect>
                </VnRow>

                <VnRow>
                    <VnSelect
                        :label="t('Type')"
                        :options="invoiceCorrectionTypesOptions"
                        hide-selected
                        option-label="description"
                        option-value="id"
                        v-model="invoiceParams.invoiceCorrectionTypeFk"
                        :required="true"
                    /> </VnRow
                ><VnRow>
                    <div>
                        <QCheckbox
                            :label="t('Inherit warehouse')"
                            v-model="inheritWarehouse"
                        />
                        <QIcon name="info" class="cursor-info q-ml-sm" size="sm">
                            <QTooltip>{{ t('Inherit warehouse tooltip') }}</QTooltip>
                        </QIcon>
                    </div>
                </VnRow>
            </template>
        </FormPopup>
    </QDialog>
</template>

<i18n>
en:
    Refund invoice: Refund invoice
    Rectificative type: Rectificative type
    Class: Class
    Type: Type
    Refunded invoice: Refunded invoice
    Inherit warehouse: Inherit the warehouse
    Inherit warehouse tooltip: Select this option to inherit the warehouse when refunding the invoice
    Accept: Accept
    Error refunding invoice: Error refunding invoice
es:
    Refund invoice: Abonar factura
    Rectificative type: Tipo rectificativa
    Class: Clase
    Type: Tipo
    Refunded invoice: Factura abonada
    Inherit warehouse: Heredar el almacén
    Inherit warehouse tooltip: Seleccione esta opción para heredar el almacén al abonar la factura.
    Accept: Aceptar
    Error refunding invoice: Error abonando factura
</i18n>
