<script setup>
import { onMounted, ref, computed, reactive, watchEffect } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import { toDateFormat } from 'src/filters/date.js';
import { useArrayData } from 'src/composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import { useVnConfirm } from 'composables/useVnConfirm';
import axios from 'axios';
import { useStateStore } from 'stores/useStateStore';
import VnTable from 'src/components/VnTable/VnTable.vue';

const stateStore = useStateStore();

const route = useRoute();
const { t } = useI18n();
const { notify } = useNotify();
const { openConfirmationModal } = useVnConfirm();
const tableRef = ref();
const selectedRows = ref([]);
const hasSelectedCards = computed(() => selectedRows.value.length > 0);

const exprBuilder = (param, value) => {
    switch (param) {
        case 'parking':
        case 'shelving':
        case 'label':
        case 'packing':
        case 'itemFk':
            return { [param]: value };
    }
};

const params = reactive({ itemFk: route.params.id });
const filter = reactive({
    where: {
        itemFk: route.params.id,
    },
});

const arrayData = useArrayData('ItemShelvings', {
    url: 'ItemShelvingPlacementSupplyStocks',
    userParams: params,
    exprBuilder: exprBuilder,
});
const rows = computed(() => arrayData.store.data || []);

const columns = computed(() => [
    {
        label: t('shelvings.created'),
        name: 'created',
        align: 'left',
        columnFilter: false,
        format: (row) => toDateFormat(row.created),
    },

    {
        label: t('shelvings.item'),
        name: 'itemFk',
        align: 'left',
        columnFilter: false,
    },
    {
        label: t('shelvings.concept'),
        name: 'longName',
        align: 'left',
        columnFilter: false,
    },
    {
        label: t('shelvings.parking'),
        name: 'parking',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'parkings',
            fields: ['code'],
            'sort-by': 'code ASC',
            'option-value': 'code',
            'option-label': 'code',
            dense: true,
        },
        columnField: { component: null },
    },
    {
        label: t('shelvings.shelving'),
        name: 'shelving',
        align: 'left',
        component: 'select',
        attrs: {
            url: 'shelvings',
            fields: ['code'],
            'sort-by': 'code ASC',
            'option-value': 'code',
            'option-label': 'code',
            dense: true,
        },
        columnField: { component: null },
    },
    {
        label: t('shelvings.label'),
        name: 'label',
        align: 'left',
        columnFilter: { inWhere: true },
        format: (row) => (row.stock / row.packing).toFixed(2),
    },
    {
        label: t('shelvings.packing'),
        name: 'packing',
        attrs: { inWhere: true },
        align: 'left',
    },
]);

const totalLabels = computed(() =>
    rows.value.reduce((acc, row) => acc + row.stock / row.packing, 0).toFixed(2)
);

const removeLines = async () => {
    const itemShelvingIds = selectedRows.value.map((row) => row.itemShelvingFk);
    await axios.post('ItemShelvings/deleteItemShelvings', { itemShelvingIds });
    selectedRows.value = [];
    notify('shelvings.shelvingsRemoved', 'positive');
    await tableRef.value.reload();
};
onMounted(async () => {
    await arrayData.fetch({ append: false });
});
watchEffect(selectedRows);
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#st-data">
            <div class="q-pa-md q-mr-lg q-ma-xs" style="border: 2px solid #222">
                <QCardSection horizontal>
                    <span class="text-weight-bold text-subtitle1 text-center full-width">
                        {{ t('shelvings.total') }}
                    </span>
                </QCardSection>
                <QCardSection class="column items-center" horizontal>
                    <div>
                        <span class="details-label"
                            >{{ t('shelvings.totalLabels') }}
                        </span>
                        <span>: {{ totalLabels }}</span>
                    </div></QCardSection
                >
            </div>
        </Teleport>
        <Teleport to="#st-actions">
            <QBtn
                color="primary"
                icon="delete"
                :disabled="!hasSelectedCards"
                @click="
                    openConfirmationModal(
                        t('shelvings.removeConfirmTitle'),
                        t('shelvings.removeConfirmSubtitle'),
                        removeLines
                    )
                "
            >
                <QTooltip>
                    {{ t('shelvings.removeLines') }}
                </QTooltip>
            </QBtn>
        </Teleport>
    </template>
    <QPage class="column items-center q-pa-md">
        <VnTable
            ref="tableRef"
            data-key="ItemShelving"
            :columns="columns"
            :url="`ItemShelvingPlacementSupplyStocks`"
            :filter="filter"
            :expr-builder="exprBuilder"
            :right-search="false"
            v-model:selected="selectedRows"
            :table="{
                'row-key': 'itemShelvingFk',
                selection: 'multiple',
            }"
            auto-load
        >
            <template #column-longName="{ row }">
                <span class="link" @click.stop>
                    {{ row.longName }}
                    <ItemDescriptorProxy :id="row.itemFk" />
                </span>
            </template>
        </VnTable>
    </QPage>
</template>
