<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 FetchData from 'components/FetchData.vue';

import { useStateStore } from 'stores/useStateStore';
import { dashIfEmpty } from 'src/filters';
import axios from 'axios';
import VnTable from 'src/components/VnTable/VnTable.vue';

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

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 columns = computed(() => [
    {
        align: 'left',
        label: t('volume.item'),
        name: 'itemFk',
        chip: {
            condition: () => true,
        },
        isId: true,
    },
    {
        align: 'left',
        label: t('volume.description'),
        name: 'concept',
        columnClass: 'expand',
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('volume.packingType'),
        name: 'itemPackingTypeFk',
        cardVisible: true,
        format: (row, dashIfEmpty) => dashIfEmpty(row.item.itemPackingTypeFk),
    },
    {
        align: 'left',
        label: t('volume.quantity'),
        name: 'quantity',
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('volume.volumeQuantity'),
        name: 'volume',
        cardVisible: true,
    },
]);

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
    />
    <QDrawer
        v-if="packingTypeVolume.length"
        side="right"
        :width="265"
        v-model="stateStore.rightDrawer"
    >
        <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>
    </QDrawer>

    <VnTable
        ref="tableRef"
        data-key="TicketVolume"
        :url="`Tickets/${route.params.id}/getSales`"
        :columns="columns"
        :right-search="false"
        :column-search="false"
        :order="['itemPackingTypeFk']"
        auto-load
    >
        <template #column-itemFk="{ row }">
            <span class="link">
                {{ row.itemFk }}
                <ItemDescriptorProxy :id="row.itemFk" />
            </span>
        </template>
        <template #column-concept="{ row }">
            <span>{{ row.item.name }}</span>
            <span class="color-vn-label q-pl-md">{{ row.item.subName }}</span>
            <FetchedTags :item="row.item" />
        </template>
        <template #column-volume="{ rowIndex }">
            <span>{{ packingTypeVolume?.[rowIndex]?.volume }}</span>
        </template>
    </VnTable>
</template>
