<script setup>
import { useStateStore } from 'stores/useStateStore';
import { useRoute, useRouter } from 'vue-router';
import { onBeforeMount, onMounted, onUnmounted, ref, computed } from 'vue';
import axios from 'axios';
import { useI18n } from 'vue-i18n';
import VnPaginate from 'components/ui/VnPaginate.vue';
import CatalogItem from 'components/ui/CatalogItem.vue';
import OrderCatalogFilter from 'pages/Order/Card/OrderCatalogFilter.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';
import getParamWhere from 'src/filters/getParamWhere';

const route = useRoute();
const router = useRouter();
const stateStore = useStateStore();
const { t } = useI18n();
const tags = ref([]);

let catalogParams = {
    orderFk: route.params.id,
    orderBy: JSON.stringify({ field: 'relevancy DESC, name', way: 'ASC', isTag: false }),
};

onBeforeMount(() => {
    const whereParams = getParamWhere(route);
    if (whereParams) {
        const formattedWhereParams = {};
        if (whereParams.and) {
            whereParams.and.forEach((item) => {
                Object.assign(formattedWhereParams, item);
            });
        } else {
            Object.assign(formattedWhereParams, whereParams);
        }

        catalogParams = {
            ...catalogParams,
            ...formattedWhereParams,
        };
    }
});

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

async function checkOrderConfirmation() {
    const response = await axios.get(`Orders/${route.params.id}`);
    if (response.data.isConfirmed === 1) {
        router.push(`/order/${route.params.id}/line`);
    }
}

function extractTags(items) {
    const resultTags = [];
    (items || []).forEach((item) => {
        (item.tags || []).forEach((tag) => {
            const index = resultTags.findIndex((item) => item.tagFk === tag.tagFk);
            if (index === -1) {
                resultTags.push({ ...tag, priority: 1 });
            } else {
                resultTags[index].priority += 1;
            }
        });
    });
    tags.value = resultTags;
    extractValueTags(items);
}

const tagValue = ref([]);

function extractValueTags(items) {
    const resultValueTags = items.flatMap((x) =>
        Object.keys(x)
            .filter((k) => /^value\d+$/.test(k))
            .map((v) => x[v])
            .filter((v) => v)
            .sort()
    );
    tagValue.value = resultValueTags;
}
const autoLoad = computed(() => !!catalogParams.categoryFk);
</script>

<template>
    <VnSearchbar
        data-key="OrderCatalogList"
        :user-params="catalogParams"
        :static-params="['orderFk', 'orderBy']"
        :redirect="false"
        url="Orders/CatalogFilter"
        :label="t('Search items')"
        :info="t('You can search items by name or id')"
    />
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <OrderCatalogFilter
                data-key="OrderCatalogList"
                :tag-value="tagValue"
                :tags="tags"
                :initial-catalog-params="catalogParams"
            />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center q-pa-md">
        <div class="full-width">
            <VnPaginate
                data-key="OrderCatalogList"
                url="Orders/CatalogFilter"
                :limit="50"
                :user-params="catalogParams"
                @on-fetch="extractTags"
                :update-router="false"
                :auto-load="autoLoad"
            >
                <template #body="{ rows }">
                    <div class="catalog-list">
                        <div v-if="rows && !rows?.length" class="no-result">
                            {{ t('globals.noResults') }}
                        </div>
                        <CatalogItem
                            v-for="row in rows"
                            :key="row.id"
                            :item="row"
                            is-catalog
                            class="fill-icon"
                        />
                    </div>
                </template>
            </VnPaginate>
        </div>
    </QPage>
</template>

<style lang="scss" scoped>
.catalog-list {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    justify-content: center;
    gap: 16px;
}

.no-result {
    font-size: 24px;
    font-weight: bold;
    color: var(--vn-label-color);
    text-align: center;
}
</style>

<i18n>
es:
    You can search items by name or id: Puedes buscar items por nombre o id
    Search items: Buscar items
</i18n>
