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

import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import FetchData from 'components/FetchData.vue';

import { useStateStore } from 'stores/useStateStore';
import { dashIfEmpty } from 'src/filters';
import axios from 'axios';

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

watch(
    () => route.params.id,
    async () => {
        await nextTick();
        salesRef.value?.fetch();
    }
);

const salesFilter = computed(() => ({
    include: { relation: 'item' },
    order: 'concept',
    where: { ticketFk: route.params.id },
    limit: 20,
}));

const sales = ref([]);
const packingTypeVolume = ref([]);
const rows = computed(() => sales.value);

const columns = computed(() => [
    {
        label: t('volume.item'),
        name: 'item',
        align: 'left',
    },
    {
        label: t('volume.description'),
        name: 'description',
        align: 'left',
    },
    {
        label: t('volume.packingType'),
        name: 'quantity',
        field: (row) => row.item.itemPackingTypeFk,
        align: 'left',
        format: (val) => dashIfEmpty(val),
    },
    {
        label: t('volume.quantity'),
        name: 'quantity',
        field: 'quantity',
        align: 'left',
    },
    {
        label: t('volume.volumeQuantity'),
        name: 'quantity',
        field: (row) => row.saleVolume?.volume,
        align: 'left',
    },
]);

const applyVolumes = async (salesData) => {
    try {
        if (!salesData.length) return;

        sales.value = salesData;
        const ticket = sales.value[0].ticketFk;
        const { data } = await axios.get(`Tickets/${ticket}/getVolume`);
        const volumes = new Map(data.saleVolume.map((volume) => [volume.saleFk, volume]));

        sales.value.forEach((sale) => {
            sale.saleVolume = volumes.get(sale.id);
        });

        packingTypeVolume.value = data.packingTypeVolume;
    } catch (error) {
        console.error(error);
    }
};

onMounted(() => {
    stateStore.rightDrawer = true;
});

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

<template>
    <FetchData
        ref="salesRef"
        url="sales"
        :filter="salesFilter"
        @on-fetch="(data) => applyVolumes(data)"
        auto-load
    />
    <RightMenu v-if="packingTypeVolume.length">
        <template #right-panel>
            <QCard
                v-for="(packingType, index) in packingTypeVolume"
                :key="index"
                class="q-pa-md q-mb-md q-ma-md color-vn-text"
                bordered
                flat
                style="border-color: black"
            >
                <QCardSection class="column items-center" horizontal>
                    <span>
                        {{ t('volume.type') }}:
                        {{ dashIfEmpty(packingType.description) }}
                    </span>
                </QCardSection>
                <QCardSection class="column items-center" horizontal>
                    <span> {{ t('volume.volume') }}: {{ packingType.volume }} </span>
                </QCardSection>
            </QCard>
        </template>
    </RightMenu>
    <QTable
        :rows="rows"
        :columns="columns"
        row-key="id"
        :pagination="{ rowsPerPage: 0 }"
        class="full-width q-mt-md"
        :no-data-label="t('globals.noResults')"
    >
        <template #body-cell-item="{ row }">
            <QTd>
                <QBtn flat color="primary">
                    {{ row.itemFk }}
                    <ItemDescriptorProxy :id="row.itemFk" />
                </QBtn>
            </QTd>
        </template>
        <template #body-cell-description="{ row }">
            <QTd>
                <div class="column">
                    <span>{{ row.item.name }}</span>
                    <span class="color-vn-label">{{ row.item.subName }}</span>
                    <FetchedTags :item="row.item" />
                </div>
            </QTd>
        </template>
    </QTable>
</template>
