<script setup>
import { onMounted, computed, onUnmounted, 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 { useStateStore } from 'stores/useStateStore';
import { toDateTimeFormat } from 'src/filters/date.js';
import { dashIfEmpty } from 'src/filters';
import { toCurrency } from 'filters/index';
import { useArrayData } from 'composables/useArrayData';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';

const { t } = useI18n();
const route = useRoute();
const stateStore = useStateStore();

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),
                },
            };
    }
};

const from = ref();
const to = ref();

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

const itemLastEntries = ref([]);

const columns = computed(() => [
    {
        label: t('lastEntries.ig'),
        name: 'ig',
        align: 'center',
    },
    {
        label: t('lastEntries.warehouse'),
        name: 'warehouse',
        field: 'warehouse',
        align: 'left',
    },
    {
        label: t('lastEntries.landed'),
        name: 'id',
        field: 'landed',
        align: 'left',
        format: (val) => toDateTimeFormat(val),
    },
    {
        label: t('lastEntries.entry'),
        name: 'entry',
        field: 'stateName',
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('lastEntries.pvp'),
        name: 'pvp',
        field: 'reference',
        align: 'left',
        format: (_, row) => toCurrency(row.price2) + ' / ' + toCurrency(row.price3),
    },

    {
        label: t('lastEntries.label'),
        name: 'label',
        field: 'stickers',
        align: 'center',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('lastEntries.packing'),
        name: 'packing',
        align: 'center',
    },
    {
        label: t('lastEntries.grouping'),
        name: 'grouping',
        align: 'center',
    },
    {
        label: t('lastEntries.stems'),
        name: 'stems',
        field: 'stems',
        align: 'center',
    },
    {
        label: t('lastEntries.quantity'),
        name: 'stems',
        field: 'quantity',
        align: 'center',
    },
    {
        label: t('lastEntries.cost'),
        name: 'cost',
        align: 'left',
    },
    {
        label: t('lastEntries.kg'),
        name: 'stems',
        field: 'weight',
        align: 'center',
    },
    {
        label: t('lastEntries.cube'),
        name: 'cube',
        field: 'packagingFk',
        align: 'center',
    },
    {
        label: t('lastEntries.supplier'),
        name: 'stems',
        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 filter;
    if (!from.value && to.value) filter = { lte: to.value };
    else if (from.value && !to.value) filter = { gte: from.value };
    else if (from.value && to.value) filter = { between: [from.value, to.value] };

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

onMounted(async () => {
    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(Date.vnNew(), '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();
    });
});

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

<template>
    <VnSubToolbar>
        <template #st-data>
            <VnInputDate
                :label="t('lastEntries.since')"
                dense
                v-model="from"
                class="q-mr-lg"
            />
            <VnInputDate :label="t('lastEntries.to')" dense v-model="to" />
        </template>
    </VnSubToolbar>
    <QPage class="column items-center q-pa-xd">
        <QTable
            :rows="itemLastEntries"
            :columns="columns"
            class="full-width q-mt-md"
            :no-data-label="t('globals.noResults')"
        >
            <template #body-cell-ig="{ row }">
                <QTd @click.stop>
                    <QCheckbox
                        v-model="row.isIgnored"
                        :disable="true"
                        :false-value="0"
                        :true-value="1"
                    />
                </QTd>
            </template>
            <template #body-cell-entry="{ row }">
                <QTd @click.stop>
                    <div class="full-width flex justify-center">
                        <EntryDescriptorProxy :id="row.entryFk" class="q-ma-none" dense />
                        <span class="link">{{ row.entryFk }}</span>
                    </div>
                </QTd>
            </template>
            <template #body-cell-packing="{ row }">
                <QTd @click.stop>
                    <QBadge
                        class="center-content"
                        rounded
                        :color="row.groupingMode == 'packing' ? 'grey-13' : 'black'"
                    >
                        {{ dashIfEmpty(row.packing) }}
                        <QTooltip>{{ t('lastEntries.packing') }}</QTooltip>
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-pvp="{ value }">
                <QTd @click.stop
                    ><span> {{ value }}</span>
                    <QTooltip>
                        {{ t('lastEntries.grouping') }}/{{ t('lastEntries.packing') }}
                    </QTooltip></QTd
                >
            </template>
            <template #body-cell-grouping="{ row }">
                <QTd @click.stop>
                    <QBadge
                        class="center-content"
                        rounded
                        :color="row.groupingMode == 'grouping' ? 'grey-13' : 'black'"
                    >
                        {{ dashIfEmpty(row.grouping) }}
                        <QTooltip>{{ t('lastEntries.grouping') }}</QTooltip>
                    </QBadge>
                </QTd>
            </template>
            <template #body-cell-cost="{ row }">
                <QTd @click.stop>
                    <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>
        </QTable>
    </QPage>
</template>

<style lang="scss" scoped>
.q-badge--rounded {
    border-radius: 50%;
}
.center-content {
    display: flex;
    max-width: max-content;
    margin: auto;
    padding: 0 11px;
    height: 28px;
}
</style>
