<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { toCurrency, toDateHourMin } from 'src/filters';
import VnTable from 'components/VnTable/VnTable.vue';
import VnUserLink from 'src/components/ui/VnUserLink.vue';

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

const filter = computed(() => {
    return {
        include: [
            {
                relation: 'worker',
                scope: {
                    fields: ['id'],
                    include: { relation: 'user', scope: { fields: ['name'] } },
                },
            },
        ],
        where: { clientFk: +route.params.id },
    };
});

const tableRef = ref();
const tableData = ref([]);
const columns = computed(() => [
    {
        align: 'left',
        name: 'created',
        label: t('Since'),
        format: ({ created }) => toDateHourMin(created),
    },
    {
        align: 'left',
        label: t('Employee'),
        name: 'employee',
    },
    {
        align: 'left',
        label: t('Credit'),
        name: 'amount',
        format: ({ amount }) => toCurrency(amount),
    },
    {
        label: t('Credit'),
        name: 'credit',
        create: true,
        visible: false,
        attrs: {
            autofocus: true,
        },
    },
]);
</script>
<template>
    <VnTable
        ref="tableRef"
        data-key="ClientCredit"
        url="ClientCredits"
        search-url="credits"
        :filter="filter"
        :order="['created DESC']"
        :columns="columns"
        auto-load
        :right-search="false"
        :is-editable="false"
        :use-model="true"
        :column-search="false"
        :disable-option="{ card: true }"
        @on-fetch="(data) => (tableData = data)"
        :create="{
            urlUpdate: `Clients/${route.params.id}`,
            title: t('New credit'),
            onDataSaved: () => tableRef.reload(),
            formInitialData: { credit: tableData.at(0)?.amount },
        }"
    >
        <template #column-employee="{ row }">
            <VnUserLink :name="row?.worker?.user?.name" :worker-id="row.worker?.id" />
        </template>
    </VnTable>
</template>
<i18n>
es:
    Since: Desde
    Employee: Empleado
    Credit: Credito
    New credit: Nuevo credito
</i18n>
