<script setup>
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getTotal } from 'src/composables/getTotal';
import FetchData from 'src/components/FetchData.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';

const { t } = useI18n();
const route = useRoute();
const rowsSelected = ref([]);
const countries = ref([]);
const intrastats = ref([]);
const invoiceInIntrastatRef = ref();
const invoiceInId = computed(() => +route.params.id);
const filter = computed(() => ({ where: { invoiceInFk: invoiceInId.value } }));
const columns = computed(() => [
    {
        name: 'intrastatFk',
        label: t('Code'),
        component: 'select',
        columnFilter: false,
        attrs: {
            options: intrastats.value,
            optionValue: 'id',
            optionLabel: (row) => `${row.id}: ${row.description}`,
            'data-cy': 'intrastat-code',
            sortBy: 'id',
            fields: ['id', 'description'],
            filterOptions: ['id', 'description']
        },
        format: (row, dashIfEmpty) => dashIfEmpty(getCode(row)),
        create: true,
        isEditable: true,
        width: 'max-content',
    },
    {
        name: 'amount',
        label: t('amount'),
        component: 'number',
        create: true,
        isEditable: true,
        columnFilter: false,
    },
    {
        name: 'net',
        label: t('net'),
        component: 'number',
        create: true,
        isEditable: true,
        columnFilter: false,
    },
    {
        name: 'stems',
        label: t('stems'),
        component: 'number',
        create: true,
        isEditable: true,
        columnFilter: false,
    },
    {
        name: 'countryFk',
        label: t('country'),
        component: 'select',
        attrs: {
            options: countries.value,
            optionLabel: 'code',
        },
        create: true,
        isEditable: true,
        columnFilter: false,
    },
]);

const tableRows = computed(
    () => invoiceInIntrastatRef.value?.CrudModelRef?.formData || [],
);

function getCode(row) {
    const code = intrastats.value.find(({ id }) => id === row.intrastatFk);
    return code ? `${code.id}: ${code.description}` : null;
}
</script>
<template>
    <FetchData
        url="Countries"
        auto-load
        @on-fetch="(data) => (countries = data)"
        sort-by="name"
    />
    <FetchData
        url="Intrastats"
        sort-by="id"
        auto-load
        @on-fetch="(data) => (intrastats = data)"
    />
    <div class="invoice-in-intrastat">
        <VnTable
            ref="invoiceInIntrastatRef"
            data-key="InvoiceInIntrastats"
            url="InvoiceInIntrastats"
            save-url="InvoiceInIntrastats/crud"
            search-url="InvoiceInIntrastats"
            auto-load
            :filter
            :user-filter
            v-model:selected="rowsSelected"
            :columns
            :is-editable="true"
            :table="{ selection: 'multiple', 'row-key': '$index' }"
            :create="{
                urlCreate: 'InvoiceInIntrastats',
                title: t('Create Intrastat'),
                formInitialData: { invoiceInFk: invoiceInId },
                onDataSaved: () => invoiceInIntrastatRef.reload(),
            }"
            footer
            data-cy="invoice-in-intrastat-table"
            :right-search="false"
            :disable-option="{ card: true }"
        >
            <template #column-footer-amount>
                {{ getTotal(tableRows, 'amount', { currency: 'default' }) }}
            </template>
            <template #column-footer-net>
                {{ getTotal(tableRows, 'net') }}
            </template>
            <template #column-footer-stems>
                {{ getTotal(tableRows, 'stems', { decimalPlaces: 0 }) }}
            </template>
        </VnTable>
    </div>
</template>
<style lang="scss" scoped>
.invoice-in-intrastat {
    display: flex;
    flex-direction: column;
    align-items: center;
}
:deep(.full-width) {
    max-width: 900px;
}
</style>
<i18n>
    en:
        amount: Amount
        net: Net
        stems: Stems
        country: Country
    es:
        Code: Código
        amount: Valor mercancía
        net: Neto
        stems: Tallos
        country: País
        Total amount: Total importe
        Total net: Total neto
        Total stems: Total tallos
        Create Intrastat: Crear Intrastat
</i18n>
