<script setup>
import { onBeforeMount, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnSelectFilter from 'src/components/common/VnSelectFilter.vue';
import VnInput from 'src/components/common/VnInput.vue';

const { t } = useI18n();
const route = useRoute();

const $props = defineProps({
    companyId: {
        type: Number,
        required: true,
    },
    totalCredit: {
        type: Number,
        required: true,
    },
    promise: {
        type: Function,
        required: true,
    },
});

const closeButton = ref(null);
const urlCreate = ref([]);
const companyOptions = ref([]);
const bankOptions = ref([]);
const clientFindOne = ref([]);
const deliveredAmount = ref(null);
const amountToReturn = ref(null);
const viewRecipt = ref(true);
const sendEmail = ref(false);
const isLoading = ref(false);

const filterBanks = {
    fields: ['id', 'bank', 'accountingTypeFk'],
    include: { relation: 'accountingType' },
    order: 'id',
    limit: 30,
};

const filterClientFindOne = {
    fields: ['email'],
    where: {
        id: `${route.params.id}`,
    },
};

const initialData = reactive({
    amountPaid: $props.totalCredit,
    bankFk: null,
    clientFk: `${route.params.id}`,
    companyFk: $props.companyId,
    compensationAccount: null,
    description: null,
    email: clientFindOne.value.email,
    payed: null,
});

onBeforeMount(() => {
    urlCreate.value = `Clients/${route.params.id}/createReceipt`;
});

const setPaymentType = (id) => {
    initialData.payed = '2001-01-01T11:00:00.000Z';
    if (id === 1) initialData.description = 'Credit card';
    if (id === 2) initialData.description = 'Cash';
    if (id === 3 || id === 3117) initialData.description = '';
    if (id === 4) initialData.description = 'Transfer';
};

const calculateFromAmount = (event) => {
    amountToReturn.value = parseFloat(event) * -1 + parseFloat(deliveredAmount.value);
};

const calculateFromDeliveredAmount = (event) => {
    amountToReturn.value = parseFloat($props.totalCredit) * -1 + parseFloat(event);
};

const setClientEmail = (data) => {
    initialData.email = data.email;
};

const onDataSaved = async () => {
    isLoading.value = true;
    if ($props.promise) {
        try {
            await $props.promise();
        } finally {
            isLoading.value = false;
            if (closeButton.value) closeButton.value.click();
        }
    }
};
</script>

<template>
    <QDialog ref="dialogRef">
        <fetch-data
            @on-fetch="(data) => (companyOptions = data)"
            auto-load
            url="Companies"
        />
        <fetch-data
            :filter="filterBanks"
            @on-fetch="(data) => (bankOptions = data)"
            auto-load
            url="Accountings"
        />
        <fetch-data
            :filter="filterClientFindOne"
            @on-fetch="setClientEmail"
            auto-load
            url="Clients/findOne"
        />

        <FormModel
            :default-actions="false"
            :form-initial-data="initialData"
            :observe-form-changes="false"
            :url-create="urlCreate"
            @on-data-saved="onDataSaved()"
        >
            <template #form="{ data }">
                <span ref="closeButton" class="row justify-end close-icon" v-close-popup>
                    <QIcon name="close" size="sm" />
                </span>

                <h5 class="flex justify-center q-mt-xs">
                    {{ t('New payment') }}
                </h5>

                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnInputDate
                            :label="t('Date')"
                            :required="true"
                            v-model="data.payed"
                        />
                    </div>
                    <div class="col">
                        <VnSelectFilter
                            :label="t('Company')"
                            :options="companyOptions"
                            :required="true"
                            hide-selected
                            option-label="code"
                            option-value="id"
                            v-model="data.companyFk"
                        />
                    </div>
                </VnRow>

                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col">
                        <VnSelectFilter
                            :label="t('Bank')"
                            :options="bankOptions"
                            :required="true"
                            @update:model-value="setPaymentType($event)"
                            hide-selected
                            option-label="bank"
                            option-value="id"
                            v-model="data.bankFk"
                        >
                            <template #option="scope">
                                <QItem v-bind="scope.itemProps">
                                    <QItemSection>
                                        <QItemLabel>
                                            {{ scope.opt.id }}:&ensp;{{ scope.opt.bank }}
                                        </QItemLabel>
                                    </QItemSection>
                                </QItem>
                            </template>
                        </VnSelectFilter>
                    </div>
                    <div class="col">
                        <VnInput
                            :label="t('Amount')"
                            :required="true"
                            @update:model-value="calculateFromAmount($event)"
                            type="number"
                            v-model.number="data.amountPaid"
                        />
                    </div>
                </VnRow>

                <div class="text-h6" v-if="data.bankFk === 3 || data.bankFk === 3117">
                    {{ t('Compensation') }}
                </div>

                <VnRow class="row q-gutter-md q-mb-md">
                    <div class="col" v-if="data.bankFk === 3 || data.bankFk === 3117">
                        <VnInput
                            :label="t('Compensation account')"
                            v-model="data.compensationAccount"
                        />
                    </div>
                    <div class="col">
                        <VnInput
                            :label="t('Reference')"
                            :required="true"
                            v-model="data.description"
                        />
                    </div>
                </VnRow>

                <div class="q-mt-lg" v-if="data.bankFk === 2">
                    <div class="text-h6">{{ t('Cash') }}</div>

                    <VnRow class="row q-gutter-md q-mb-md">
                        <div class="col">
                            <VnInput
                                :label="t('Delivered amount')"
                                @update:model-value="calculateFromDeliveredAmount($event)"
                                type="number"
                                v-model="deliveredAmount"
                            />
                        </div>
                        <div class="col">
                            <VnInput
                                :label="t('Amount to return')"
                                disable
                                type="number"
                                v-model="amountToReturn"
                            />
                        </div>
                    </VnRow>

                    <VnRow class="row q-gutter-md q-mb-md">
                        <div class="col">
                            <QCheckbox v-model="viewRecipt" />
                        </div>
                        <div class="col">
                            <QCheckbox v-model="sendEmail" />
                        </div>
                    </VnRow>
                </div>

                <div class="q-mt-lg row justify-end">
                    <QBtn
                        :disabled="isLoading"
                        :label="t('globals.cancel')"
                        :loading="isLoading"
                        class="q-ml-sm"
                        color="primary"
                        flat
                        type="reset"
                        v-close-popup
                    />
                    <QBtn
                        :disabled="isLoading"
                        :label="t('globals.save')"
                        :loading="isLoading"
                        color="primary"
                        type="submit"
                    />
                </div>
            </template>
        </FormModel>
    </QDialog>
</template>

<i18n>
es:
    New payment: Añadir pago
    Date: Fecha
    Company: Empresa
    Bank: Caja
    Amount: Importe
    Reference: Referencia
    Cash: Efectivo
    Delivered amount: Cantidad entregada
    Amount to return: Cantidad a devolver
    View recipt: Ver recibido
    Send email: Enviar correo
    Compensation: Compensación
    Compensation account: Cuenta para compensar
</i18n>
