<script setup>
import { useStateStore } from 'stores/useStateStore';
import { useRoute } from 'vue-router';
import { onMounted, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import VnPaginate from 'components/ui/VnPaginate.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import OrderCatalogItem from 'pages/Order/Card/OrderCatalogItem.vue';
import OrderCatalogFilter from 'pages/Order/Card/OrderCatalogFilter.vue';

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

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

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

function exprBuilder(param, value) {
    switch (param) {
        case 'search':
            return { 'i.name': { like: `%${value}%` } };
    }
}
</script>

<template>
    <Teleport to="#searchbar" v-if="stateStore.isHeaderMounted()">
        <VnSearchbar
            data-key="OrderCatalogList"
            url="Orders/CatalogFilter"
            :limit="50"
            :user-params="catalogParams"
            :expr-builder="exprBuilder"
            :static-params="['orderFk', 'orderBy']"
        />
    </Teleport>
    <Teleport v-if="stateStore.isHeaderMounted()" to="#actions-append">
        <div class="row q-gutter-x-sm">
            <QBtn
                flat
                @click.stop="stateStore.toggleRightDrawer()"
                round
                dense
                icon="menu"
            >
                <QTooltip bottom anchor="bottom right">
                    {{ t('globals.collapseMenu') }}
                </QTooltip>
            </QBtn>
        </div>
    </Teleport>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <OrderCatalogFilter data-key="OrderCatalogList" />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center q-pa-md">
        <div class="card-list">
            <VnPaginate
                data-key="OrderCatalogList"
                url="Orders/CatalogFilter"
                :limit="50"
                :user-params="catalogParams"
                auto-load
            >
                <template #body="{ rows }">
                    <div class="catalog-list">
                        <OrderCatalogItem v-for="row in rows" :key="row.id" :item="row" />
                    </div>
                </template>
            </VnPaginate>
        </div>
    </QPage>
</template>

<style lang="scss">
.card-list {
    width: 100%;
}

.catalog-list {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    justify-content: center;
    gap: 16px;
}
</style>
