<script setup>
import { onMounted, ref, computed, reactive, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import VnTable from 'components/VnTable/VnTable.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';

import { useStateStore } from 'stores/useStateStore';
import { toDate, toCurrency } from 'src/filters';
// import { useSession } from 'composables/useSession';
import { dashIfEmpty } from 'src/filters';
import { useArrayData } from 'composables/useArrayData';

const router = useRouter();
// const { getTokenMultimedia } = useSession();
// const token = getTokenMultimedia();
const stateStore = useStateStore();
const { t } = useI18n();

const rowsFetchDataRef = ref(null);
const itemTypesOptions = ref([]);
const originsOptions = ref([]);
const itemFamiliesOptions = ref([]);
const intrastatOptions = ref([]);
const packagingsOptions = ref([]);
const editTableCellDialogRef = ref(null);
const visibleColumns = ref([]);
const allColumnNames = ref([]);

const exprBuilder = (param, value) => {
    switch (param) {
        case 'id':
        case 'size':
        case 'weightByPiece':
        case 'isActive':
        case 'family':
        case 'minPrice':
        case 'packingOut':
            return { [`i.${param}`]: value };
        case 'name':
        case 'description':
            return { [`i.${param}`]: { like: `%${value}%` } };
        case 'code':
            return { 'it.code': value };
        case 'intrastat':
            return { 'intr.description': value };
        case 'origin':
            return { 'ori.code': value };
        case 'landing':
            return { [`lb.${param}`]: value };
        case 'packing':
        case 'grouping':
        case 'quantity':
        case 'entryFk':
        case 'buyingValue':
        case 'freightValue':
        case 'comissionValue':
        case 'packageValue':
        case 'isIgnored':
        case 'price2':
        case 'price3':
        case 'ektFk':
        case 'weight':
        case 'packagingFk':
            return { [`b.${param}`]: value };
    }
};

const params = reactive({});
const arrayData = useArrayData('EntryLatestBuys', {
    url: 'Buys/latestBuysFilter',
    order: ['itemFk DESC'],
    exprBuilder: exprBuilder,
});
const store = arrayData.store;
const rows = computed(() => store.data);
const rowsSelected = ref([]);

const getInputEvents = (col) => {
    return col.columnFilter.type === 'select'
        ? { 'update:modelValue': () => applyColumnFilter(col) }
        : {
              'keyup.enter': () => applyColumnFilter(col),
          };
};

const columns = computed(() => [
    {
        label: t('entry.latestBuys.picture'),
        name: 'picture',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.itemFk'),
        name: 'itemFk',
        field: 'itemFk',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.packing'),
        field: 'packing',
        name: 'packing',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.grouping'),
        field: 'grouping',
        name: 'grouping',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.quantity'),
        field: 'quantity',
        name: 'quantity',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.description'),
        field: 'description',
        name: 'description',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.size'),
        field: 'size',
        name: 'size',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.tags'),
        name: 'tags',
        align: 'left',
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.type'),
        field: 'code',
        name: 'type',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: itemTypesOptions.value,
                'option-value': 'code',
                'option-label': 'code',
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.intrastat'),
        field: 'intrastat',
        name: 'intrastat',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: intrastatOptions.value,
                'option-value': 'description',
                'option-label': 'description',
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.origin'),
        field: 'origin',
        name: 'origin',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: originsOptions.value,
                'option-value': 'code',
                'option-label': 'code',
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.weightByPiece'),
        field: 'weightByPiece',
        name: 'weightByPiece',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },

        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.isActive'),
        field: 'isActive',
        name: 'isActive',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.family'),
        field: 'family',
        name: 'family',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: itemFamiliesOptions.value,
                'option-value': 'code',
                'option-label': 'code',
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.entryFk'),
        field: 'entryFk',
        name: 'entryFk',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.buyingValue'),
        field: 'buyingValue',
        name: 'buyingValue',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.freightValue'),
        field: 'freightValue',
        name: 'freightValue',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.comissionValue'),
        field: 'comissionValue',
        name: 'comissionValue',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.packageValue'),
        field: 'packageValue',
        name: 'packageValue',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.isIgnored'),
        field: 'isIgnored',
        name: 'isIgnored',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.price2'),
        field: 'price2',
        name: 'price2',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },

        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.price3'),
        field: 'price3',
        name: 'price3',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.minPrice'),
        field: 'minPrice',
        name: 'minPrice',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.ektFk'),
        field: 'ektFk',
        name: 'ektFk',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.weight'),
        field: 'weight',
        name: 'weight',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.packagingFk'),
        field: 'packagingFk',
        name: 'packagingFk',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnSelect,
            type: 'select',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                options: packagingsOptions.value,
                'option-value': 'id',
                'option-label': 'id',
                dense: true,
            },
        },
    },
    {
        label: t('entry.latestBuys.packingOut'),
        field: 'packingOut',
        name: 'packingOut',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.landing'),
        field: 'landing',
        name: 'landing',
        align: 'left',
        sortable: true,
        columnFilter: {
            component: VnInput,
            type: 'text',
            filterValue: null,
            event: getInputEvents,
            attrs: {
                dense: true,
            },
        },
        format: (val) => toDate(val),
    },
]);

const editTableCellFormFieldsOptions = [
    { field: 'packing', label: t('entry.latestBuys.packing') },
    { field: 'grouping', label: t('entry.latestBuys.grouping') },
    { field: 'packageValue', label: t('entry.latestBuys.packageValue') },
    { field: 'weight', label: t('entry.latestBuys.weight') },
    { field: 'description', label: t('globals.description') },
    { field: 'size', label: t('entry.latestBuys.size') },
    { field: 'weightByPiece', label: t('entry.latestBuys.weightByPiece') },
    { field: 'packingOut', label: t('entry.latestBuys.packingOut') },
    { field: 'landing', label: t('entry.latestBuys.landing') },
];

const openEditTableCellDialog = () => {
    editTableCellDialogRef.value.show();
};

const onEditCellDataSaved = async () => {
    rowsSelected.value = [];
    await rowsFetchDataRef.value.fetch();
};

const redirectToEntryBuys = (entryFk) => {
    router.push({ name: 'EntryBuys', params: { id: entryFk } });
};

const applyColumnFilter = async (col) => {
    try {
        params[col.field] = col.columnFilter.filterValue;
        await arrayData.addFilter({ params });
    } catch (err) {
        console.error('Error applying column filter', err);
    }
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    const filteredColumns = columns.value.filter((col) => col.name !== 'picture');
    allColumnNames.value = filteredColumns.map((col) => col.name);
    await arrayData.fetch({ append: false });
});

onUnmounted(() => (stateStore.rightDrawer = false));
</script>

<template>
    <VnTable
        ref="tableRef"
        data-key="EntryLatestBuysList"
        url="EntryLatestBuys"
        url-create="EntryLatestBuys"
        save-url="EntryLatestBuys/crud"
        order="id DESC"
        :columns="columns"
        redirect="entry"
        default-mode="table"
        auto-load
        :right-search="false"
    />
</template>

<i18n>
es:
    Edit buy(s): Editar compra(s)
</i18n>
