<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import VnInputDate from 'components/common/VnInputDate.vue';
import FormModel from 'components/FormModel.vue';
import FetchData from 'components/FetchData.vue';
import VnInputNumber from 'src/components/common/VnInputNumber.vue';
import VnRow from 'components/ui/VnRow.vue';
const formModelRef = ref(false);

const { t } = useI18n();
const route = useRoute();
const amountInputRef = ref(null);

const initialData = ref({
    dated: Date.vnNew(),
    amount: null,
});

const filterClientFindOne = {
    fields: ['unpaid', 'dated', 'amount'],
    where: {
        clientFk: route.params.id,
    },
};
</script>

<template>
    <FetchData
        :filter="filterClientFindOne"
        auto-load
        url="ClientUnpaids"
        @on-fetch="
            (data) => {
                const unpaid = data.length == 1;
                initialData = { ...data[0], unpaid };
            }
        "
    />
    <QCard>
        <FormModel
            v-if="'unpaid' in initialData"
            :observe-form-changes="false"
            ref="formModelRef"
            model="unpaid"
            url-update="ClientUnpaids"
            :mapper="(formData) => ({ ...formData, clientFk: route.params.id })"
            :form-initial-data="initialData"
        >
            <template #form="{ data }">
                <VnRow>
                    <QCheckbox :label="t('Unpaid client')" v-model="data.unpaid" />
                </VnRow>

                <VnRow class="row q-gutter-md q-mb-md" v-show="data.unpaid">
                    <div class="col">
                        <VnInputDate
                            data-cy="customerUnpaidDate"
                            :label="t('Date')"
                            v-model="data.dated"
                        />
                    </div>
                    <div class="col">
                        <VnInputNumber
                            data-cy="customerUnpaidAmount"
                            ref="amountInputRef"
                            :label="t('Amount')"
                            clearable
                            v-model="data.amount"
                            autofocus
                        >
                            <template #append>€</template></VnInputNumber
                        >
                    </div>
                </VnRow>
            </template>
        </FormModel>
    </QCard>
</template>

<i18n>
es:
    Unpaid client: Cliente impagado
    Date: Fecha
    Amount: Importe
</i18n>
