<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 axios from 'axios';
import SupplierDescriptorProxy from 'src/pages/Supplier/Card/SupplierDescriptorProxy.vue';

const { t } = useI18n();
const route = useRoute();
const from = ref();
const to = ref();
const hideInventory = ref(true);
const inventorySupplierFk = ref();

async function getInventorySupplier() {
    inventorySupplierFk.value = (
        await axios.get(`InventoryConfigs`)
    )?.data[0]?.supplierFk;
}

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 where = {
    itemFk: route.params.id,
};

if (hideInventory.value) {
    where.supplierFk = { neq: inventorySupplierFk };
}

const arrayData = useArrayData('ItemLastEntries', {
    url: 'Items/lastEntriesFilter',
    order: ['landed DESC', 'buyFk DESC'],
    exprBuilder: exprBuilder,
    userFilter: {
        where: where,
    },
});
const itemLastEntries = ref([]);

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

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] };

    const userFilter = arrayData.store.userFilter.where;

    userFilter.landed = filter;
    if (hideInventory.value) userFilter.supplierFk = { neq: inventorySupplierFk };
    else delete userFilter.supplierFk;

    await fetchItemLastEntries();
};

onMounted(async () => {
    await getInventorySupplier();

    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, hideInventory], ([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();
    });
});
</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"
            />
            <QCheckbox
                :label="t('Hide inventory supplier')"
                v-model="hideInventory"
                dense
                class="q-mr-lg"
                data-cy="hideInventory"
            />
        </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">
                    <QIcon
                        :name="row.isIgnored ? 'check_box' : 'check_box_outline_blank'"
                        style="color: var(--vn-label-color)"
                        size="sm"
                    />
                </QTd>
            </template>
            <template #body-cell-date="{ row }">
                <QTd class="text-center">
                    <VnDateBadge :date="row.landed" />
                </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 class="text-center">
                    <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 class="text-center">
                    <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>
                    <div class="full-width flex justify-center">
                        <SupplierDescriptorProxy
                            :id="row.supplierFk"
                            class="q-ma-none"
                            dense
                        />
                        <span class="link">{{ row.supplier }}</span>
                    </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%;
}
.center-content {
    display: flex;
    max-width: max-content;
    margin: auto;
    padding: 0 11px;
    height: 28px;
}
.th :first-child {
    .td {
        text-align: center;
        background-color: red;
    }
}
</style>
