<script setup>
import axios from 'axios';
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { toCurrency, toDate } from 'src/filters';

import VnTable from 'components/VnTable/VnTable.vue';

const { t } = useI18n();
const route = useRoute();
const tableRef = ref();
const filter = computed(() => {
    return {
        where: { clientFk: route.params.id },
    };
});
const componentColumn = (type) => {
    return {
        columnFilter: {
            component: type,
        },
        columnCreate: {
            component: type,
        },
    };
};
const columns = computed(() => [
    {
        align: 'left',
        label: t('globals.since'),
        name: 'started',
        format: ({ started }) => toDate(started),
        create: true,
        ...componentColumn('date'),
    },
    {
        align: 'left',
        name: 'finished',
        label: t('globals.to'),
        format: ({ finished }) => toDate(finished),
        create: true,
        ...componentColumn('date'),
    },
    {
        align: 'left',
        name: 'amount',
        label: t('globals.amount'),
        format: ({ amount }) => toCurrency(amount),
        create: true,
        ...componentColumn('number'),
    },
    {
        align: 'left',
        name: 'period',
        label: t('Period'),
        create: true,
        ...componentColumn('number'),
    },
    {
        align: 'left',
        name: 'tableActions',
        actions: [
            {
                title: t('Finish that recovery period'),
                icon: 'lock',
                show: (row) => !row.finished,
                action: ({ id }) => setFinished(id),
                isPrimary: true,
            },
        ],
    },
]);

function setFinished(id) {
    axios.patch(`Recoveries/${id}`, { finished: Date.vnNow() });
    tableRef.value.reload();
}
</script>

<template>
    <VnTable
        ref="tableRef"
        data-key="Recoveries"
        url="Recoveries"
        search-url="recoveries"
        :filter="filter"
        order="started DESC"
        :columns="columns"
        :use-model="true"
        :right-search="false"
        :disable-option="{ card: true }"
        :create="{
            urlCreate: 'Recoveries',
            title: t('New recovery'),
            onDataSaved: () => tableRef.reload(),
            formInitialData: { clientFk: route.params.id, started: Date.vnNew() },
        }"
        auto-load
    />
</template>

<i18n>
es:
    Period: Periodo
    New recovery: Nuevo recobro
    Finish that recovery period: Terminar recobro
</i18n>
