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

import FetchData from 'components/FetchData.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import EntryDescriptorProxy from './Card/EntryDescriptorProxy.vue';
import TableVisibleColumns from 'src/components/common/TableVisibleColumns.vue';
import EditTableCellValueForm from 'src/components/EditTableCellValueForm.vue';

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

const router = useRouter();
const session = useSession();
const token = session.getToken();
const stateStore = useStateStore();
const { t } = useI18n();

const rowsFetchDataRef = ref(null);
const editTableCellDialogRef = ref(null);
const visibleColumns = ref([]);
const allColumnNames = ref([]);
const rows = ref([]);
const rowsSelected = ref([]);
const columns = computed(() => [
    {
        label: t('entry.latestBuys.picture'),
        name: 'picture',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.itemFk'),
        name: 'itemFk',
        field: 'itemFk',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.packing'),
        field: 'packing',
        name: 'packing',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.grouping'),
        field: 'grouping',
        name: 'grouping',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.quantity'),
        field: 'quantity',
        name: 'quantity',
        align: 'left',
    },
    {
        label: t('globals.description'),
        field: 'description',
        name: 'description',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.size'),
        field: 'size',
        name: 'size',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.tags'),
        name: 'tags',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.type'),
        field: 'code',
        name: 'type',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.intrastat'),
        field: 'intrastat',
        name: 'intrastat',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.origin'),
        field: 'origin',
        name: 'origin',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.weightByPiece'),
        field: 'weightByPiece',
        name: 'weightByPiece',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.isActive'),
        field: 'isActive',
        name: 'isActive',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.family'),
        field: 'family',
        name: 'family',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.entryFk'),
        field: 'entryFk',
        name: 'entryFk',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.buyingValue'),
        field: 'buyingValue',
        name: 'buyingValue',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.freightValue'),
        field: 'freightValue',
        name: 'freightValue',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.comissionValue'),
        field: 'comissionValue',
        name: 'comissionValue',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.packageValue'),
        field: 'packageValue',
        name: 'packageValue',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.isIgnored'),
        field: 'isIgnored',
        name: 'isIgnored',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.price2'),
        field: 'price2',
        name: 'price2',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.price3'),
        field: 'price3',
        name: 'price3',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.minPrice'),
        field: 'minPrice',
        name: 'minPrice',
        align: 'left',
        format: (val) => toCurrency(val),
    },
    {
        label: t('entry.latestBuys.ektFk'),
        field: 'ektFk',
        name: 'ektFk',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.weight'),
        field: 'weight',
        name: 'weight',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.packagingFk'),
        field: 'packagingFk',
        name: 'packagingFk',
        align: 'left',
    },
    {
        label: t('entry.latestBuys.packingOut'),
        field: 'packingOut',
        name: 'packingOut',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('entry.latestBuys.landing'),
        field: 'landing',
        name: 'landing',
        align: 'left',
        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 } });
};

onMounted(async () => {
    stateStore.rightDrawer = true;
    const filteredColumns = columns.value.filter((col) => col.name !== 'picture');
    allColumnNames.value = filteredColumns.map((col) => col.name);
});
</script>

<template>
    <FetchData
        ref="rowsFetchDataRef"
        url="Buys/latestBuysFilter"
        :filter="{ order: 'itemFk DESC', limit: 20 }"
        @on-fetch="(data) => (rows = data)"
        auto-load
    />
    <QToolbar class="bg-vn-dark justify-end">
        <div id="st-data">
            <TableVisibleColumns
                :all-columns="allColumnNames"
                table-code="latestBuys"
                labels-traductions-path="entry.latestBuys"
                @on-config-saved="visibleColumns = ['picture', ...$event]"
            />
        </div>
        <QSpace />
        <div id="st-actions"></div>
    </QToolbar>
    <QPage class="column items-center q-pa-md">
        <QTable
            :rows="rows"
            :columns="columns"
            hide-bottom
            selection="multiple"
            row-key="id"
            :pagination="{ rowsPerPage: 0 }"
            class="full-width q-mt-md"
            :visible-columns="visibleColumns"
            v-model:selected="rowsSelected"
            @row-click="(_, row) => redirectToEntryBuys(row.entryFk)"
        >
            <template #body-cell-picture="{ row }">
                <QTd>
                    <QImg
                        :src="`/api/Images/catalog/50x50/${row.itemFk}/download?access_token=${token}`"
                        spinner-color="primary"
                        :ratio="1"
                        height="50px"
                        width="50px"
                        class="image"
                    />
                </QTd>
            </template>
            <template #body-cell-itemFk="{ row }">
                <QTd @click.stop>
                    <QBtn flat color="blue">
                        {{ row.itemFk }}
                    </QBtn>
                </QTd>
            </template>
            <template #body-cell-tags="{ row }">
                <QTd>
                    <fetched-tags :item="row" :max-length="6" />
                </QTd>
            </template>
            <template #body-cell-entryFk="{ row }">
                <QTd @click.stop>
                    <QBtn flat color="blue">
                        <EntryDescriptorProxy :id="row.entryFk" />
                        {{ row.entryFk }}
                    </QBtn>
                </QTd>
            </template>
            <template #body-cell-isIgnored="{ row }">
                <QTd>
                    <QIcon
                        :name="row.isIgnored ? `check` : `close`"
                        :color="row.isIgnored ? `positive` : `negative`"
                        size="sm"
                    />
                </QTd>
            </template>
            <template #body-cell-isActive="{ row }">
                <QTd>
                    <QIcon
                        :name="row.isActive ? `check` : `close`"
                        :color="row.isActive ? `positive` : `negative`"
                        size="sm"
                    />
                </QTd>
            </template>
        </QTable>
        <QPageSticky v-if="rowsSelected.length > 0" :offset="[20, 20]">
            <QBtn @click="openEditTableCellDialog()" color="primary" fab icon="edit" />
            <QTooltip>
                {{ t('Edit buy(s)') }}
            </QTooltip>
        </QPageSticky>
        <QDialog ref="editTableCellDialogRef">
            <EditTableCellValueForm
                edit-url="Buys/editLatestBuys"
                :rows="rowsSelected"
                :fields-options="editTableCellFormFieldsOptions"
                @on-data-saved="onEditCellDataSaved()"
            />
        </QDialog>
    </QPage>
</template>

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