<script setup>
import { onMounted, computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { dateRange } from 'src/filters';
import EntryDescriptorProxy from 'src/pages/Entry/Card/EntryDescriptorProxy.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import VnDateBadge from 'src/components/common/VnDateBadge.vue';
import { dashIfEmpty } from 'src/filters';
import { toCurrency } from 'filters/index';
import { useArrayData } from 'composables/useArrayData';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import SupplierDescriptorProxy from 'src/pages/Supplier/Card/SupplierDescriptorProxy.vue';
const { t } = useI18n();
const route = useRoute();
const from = ref();
const to = ref();

const exprBuilder = (param, value) => {
    switch (param) {
        case 'id':
        case 'quantity':
        case 'packagingFk':
            return { [`b.${param}`]: value };
        case 'supplierFk':
            return { [`s.id`]: value };
        case 'warehouseFk':
            return { 'tr.warehouseInFk': value };
        case 'landed':
            return {
                'tr.landed': {
                    between: dateRange(value),
                },
            };
    }
};

let arrayData = useArrayData('ItemLastEntries');
const itemLastEntries = ref([]);

const columns = computed(() => [
    {
        label: 'NV',
        name: 'ig',
        align: 'center',
    },
    {
        label: t('itemDiary.warehouse'),
        name: 'warehouse',
        field: 'warehouse',
        align: 'left',
    },
    {
        label: t('lastEntries.landed'),
        name: 'date',
        field: 'landed',
        align: 'center',
    },
    {
        label: t('lastEntries.entry'),
        name: 'entry',
        field: 'stateName',
        align: 'right',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('lastEntries.pvp'),
        name: 'pvp',
        field: 'reference',
        align: 'center',
        format: (_, row) => toCurrency(row.price2) + ' / ' + toCurrency(row.price3),
        style: (row) => highlightedRow(row),
    },
    {
        label: t('lastEntries.printedStickers'),
        name: 'printedStickers',
        field: 'printedStickers',
        align: 'right',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('lastEntries.label'),
        name: 'stickers',
        field: 'stickers',
        align: 'right',
        format: (val) => dashIfEmpty(val),
        style: (row) => highlightedRow(row),
    },
    {
        label: 'Packing',
        name: 'packing',
        field: 'packing',
        align: 'right',
    },
    {
        label: t('lastEntries.grouping'),
        name: 'grouping',
        field: 'grouping',
        align: 'right',
    },
    {
        label: t('itemBasicData.stems'),
        name: 'stems',
        field: 'stems',
        align: 'right',
        style: (row) => highlightedRow(row),
    },
    {
        label: t('lastEntries.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'right',
        style: (row) => highlightedRow(row),
    },
    {
        label: t('lastEntries.cost'),
        name: 'cost',
        field: 'right',
        align: 'right',
    },
    {
        label: 'Kg',
        name: 'weight',
        field: 'weight',
        align: 'right',
        style: (row) => highlightedRow(row),
    },
    {
        label: t('lastEntries.cube'),
        name: 'cube',
        field: 'packagingFk',
        align: 'center',
        style: (row) => highlightedRow(row),
    },
    {
        label: t('lastEntries.supplier'),
        name: 'supplier',
        field: 'supplier',
        align: 'left',
    },
]);

const fetchItemLastEntries = async () => {
    const { data } = await arrayData.fetch({ append: false });
    itemLastEntries.value = data;
};

const getDate = (date, type) => {
    if (type == 'from') {
        date.setHours(0, 0, 0, 0);
    } else if (type == 'to') {
        date.setHours(23, 59, 59, 999);
    }
    return date.toISOString();
};

const updateFilter = async () => {
    let landed;
    if (!from.value && to.value) landed = { lte: to.value };
    else if (from.value && !to.value) landed = { gte: from.value };
    else if (from.value && to.value) landed = { between: [from.value, to.value] };

    arrayData.store.filter.where.landed = landed;
    await fetchItemLastEntries();
};

onMounted(async () => {
    const landed = arrayData.store.filter.where?.landed;
    arrayData = useArrayData('ItemLastEntries', {
        url: 'Items/lastEntriesFilter',
        order: ['landed DESC', 'buyFk DESC'],
        exprBuilder: exprBuilder,
        filter: {
            where: {
                itemFk: route.params.id,
                landed,
            },
        },
    });

    if (landed) {
        const key = Object.keys(landed)[0];
        switch (key) {
            case 'gte':
                from.value = landed.gte;
                break;
            case 'lte':
                to.value = landed.lte;
                break;
            case 'between':
                from.value = landed.between[0];
                to.value = landed.between[1];
                break;
        }
    } else {
        const _from = Date.vnNew();
        _from.setDate(_from.getDate() - 75);
        from.value = getDate(_from, 'from');
        const _to = Date.vnNew();
        _to.setDate(_to.getDate() + 10);
        to.value = getDate(_to, 'to');
    }

    updateFilter();

    watch([from, to], ([nFrom, nTo], [oFrom, oTo]) => {
        if (nFrom && nFrom != oFrom) nFrom = getDate(new Date(nFrom), 'from');
        if (nTo && nTo != oTo) nTo = getDate(new Date(nTo), 'to');
        updateFilter();
    });
});

function getBadgeClass(groupingMode, expectedGrouping) {
    return groupingMode === expectedGrouping ? 'accent-badge' : 'simple-badge';
}

function highlightedRow(row) {
    return row?.isInventorySupplier
        ? {
              'background-color': 'var(--vn-section-hover-color)',
          }
        : '';
}
</script>
<template>
    <VnSubToolbar>
        <template #st-data>
            <VnInputDate
                :label="t('itemDiary.since')"
                dense
                v-model="from"
                class="q-mr-lg"
                data-cy="from"
            />
            <VnInputDate
                :label="t('lastEntries.to')"
                v-model="to"
                dense
                class="q-mr-lg"
                data-cy="to"
            />
        </template>
    </VnSubToolbar>
    <QPage class="column items-center q-pa-xd">
        <QTable
            :rows="itemLastEntries"
            :columns="columns"
            class="table full-width q-mt-md"
            :no-data-label="t('globals.noResults')"
        >
            <template #body-cell-ig="{ row }">
                <QTd class="text-center" :style="highlightedRow(row)">
                    <QIcon
                        :name="row.isIgnored ? 'check_box' : 'check_box_outline_blank'"
                        style="color: var(--vn-label-color)"
                        size="sm"
                    />
                </QTd>
            </template>
            <template #body-cell-warehouse="{ row }">
                <QTd :style="highlightedRow(row)">
                    <span>{{ row.warehouse }}</span>
                </QTd>
            </template>
            <template #body-cell-date="{ row }">
                <QTd class="text-center" :style="highlightedRow(row)">
                    <VnDateBadge :date="row.landed" />
                </QTd>
            </template>
            <template #body-cell-entry="{ row }">
                <QTd @click.stop :style="highlightedRow(row)">
                    <div class="full-width text-right">
                        <EntryDescriptorProxy :id="row.entryFk" class="q-ma-none" dense />
                        <span class="link">{{ row.entryFk }}</span>
                    </div>
                </QTd>
            </template>
            <template #body-cell-pvp="{ row, value }">
                <QTd @click.stop class="text-center" :style="highlightedRow(row)">
                    <span> {{ value }}</span>
                    <QTooltip> {{ t('lastEntries.grouping') }}/Packing </QTooltip>
                </QTd>
            </template>
            <template #body-cell-printedStickers="{ row }">
                <QTd @click.stop class="text-right" :style="highlightedRow(row)">
                    <span style="color: var(--vn-label-color)">
                        {{ row.printedStickers }}</span
                    >
                </QTd>
            </template>
            <template #body-cell-packing="{ row }">
                <QTd @click.stop :style="highlightedRow(row)" class="text-right">
                    <QBadge
                        class="grouping-badge"
                        :class="getBadgeClass(row.groupingMode, 'packing')"
                        rounded
                    >
                        {{ dashIfEmpty(row.packing) }}
                        <QTooltip>Packing</QTooltip>
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-grouping="{ row }">
                <QTd @click.stop :style="highlightedRow(row)" class="text-right">
                    <QBadge
                        class="grouping-badge"
                        :class="getBadgeClass(row.groupingMode, 'grouping')"
                        rounded
                    >
                        {{ dashIfEmpty(row.grouping) }}
                        <QTooltip>{{ t('lastEntries.grouping') }}</QTooltip>
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-cost="{ row }">
                <QTd @click.stop class="text-right" :style="highlightedRow(row)">
                    <span>
                        {{ toCurrency(row.cost, 'EUR', 3) }}
                        <QTooltip>
                            {{ t('lastEntries.cost') }}:
                            {{ toCurrency(dashIfEmpty(row.buyingValue), 'EUR', 3) }}<br />
                            {{ t('lastEntries.package') }}:
                            {{ toCurrency(dashIfEmpty(row.packageValue), 'EUR', 3)
                            }}<br />
                            {{ $t('lastEntries.freight') }}:
                            {{ toCurrency(dashIfEmpty(row.freightValue), 'EUR', 3)
                            }}<br />
                            {{ t('lastEntries.comission') }}:
                            {{ toCurrency(dashIfEmpty(row.comissionValue), 'EUR', 3) }}
                        </QTooltip>
                    </span>
                </QTd>
            </template>
            <template #body-cell-supplier="{ row }">
                <QTd @click.stop :style="highlightedRow(row)">
                    <div class="full-width flex justify-left">
                        <QBadge
                            :class="
                                row.isInventorySupplier ? 'bg-vn-page' : 'transparent'
                            "
                            dense
                        >
                            <SupplierDescriptorProxy :id="row.supplierFk" />
                            <span class="link">{{ row.supplier }}</span>
                        </QBadge>
                    </div>
                </QTd>
            </template>
        </QTable>
    </QPage>
</template>
<i18n>
    es:
        Hide inventory supplier: Ocultar proveedor inventario
</i18n>
<style lang="scss" scoped>
.q-badge--rounded {
    border-radius: 50%;
}
.grouping-badge {
    padding: 0 11px;
    height: 28px;
}
.th :first-child {
    .td {
        text-align: center;
    }
}
.accent-badge {
    background-color: var(--vn-label-color);
    color: var(--vn-text-color-contrast);
}
.simple-badge {
    background-color: transparent;
    color: var(--vn-text-color);
    font-size: 14px;
}
</style>
