<script setup>
import { onBeforeMount, onMounted, computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Notify } from 'quasar';
import { useRoute } from 'vue-router';
import { useSession } from 'src/composables/useSession';
import { toDateHourMin } from 'filters/index';
import { useStateStore } from 'src/stores/useStateStore';

import TicketDescriptorProxy from 'pages/Ticket/Card/TicketDescriptorProxy.vue';
import CustomerDescriptorProxy from 'pages/Customer/Card/CustomerDescriptorProxy.vue';

import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import VnSearchbar from 'src/components/ui/VnSearchbar.vue';

const route = useRoute();
const { t } = useI18n();
const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia();
const state = useStateStore();
const selectedRows = ref([]);
const dataKey = 'CmrList';
const shipped = Date.vnNew();
shipped.setHours(0, 0, 0, 0);
shipped.setDate(shipped.getDate() - 1);
const userParams = {
    shipped: null,
};


const columns = computed(() => [
    {
        align: 'left',
        name: 'cmrFk',
        label: t('route.cmr.params.cmrFk'),
        chip: {
            condition: () => true,
        },
        isId: true,
    },
    {
        align: 'center',
        name: 'hasCmrDms',
        label: t('route.cmr.params.hasCmrDms'),
        component: 'checkbox',
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('route.cmr.params.ticketFk'),
        name: 'ticketFk',
    },
    {
        align: 'left',
        label: t('route.cmr.params.routeFk'),
        name: 'routeFk',
    },
    {
        align: 'left',
        label: t('route.cmr.params.clientFk'),
        name: 'clientFk',
    },
    {
        align: 'right',
        label: t('route.cmr.params.countryFk'),
        name: 'countryFk',
        component: 'select',
        attrs: {
            url: 'countries',
            fields: ['id', 'name'],
        },
        columnFilter: {
            name: 'countryFk',
            attrs: {
                url: 'countries',
                fields: ['id', 'name'],
            },
        },
        format: ({ countryName }) => countryName,
    },
    {
        align: 'right',
        label: t('route.cmr.params.shipped'),
        name: 'shipped',
        cardVisible: true,
        component: 'date',
        format: ({ shipped }) => toDateHourMin(shipped),
    },
    {
        align: 'right',
        label: t('route.cmr.params.warehouseFk'),
        name: 'warehouseFk',
        component: 'select',
        attrs: {
            url: 'warehouses',
            fields: ['id', 'name'],
        },
        columnFilter: {
            inWhere: true,
            name: 'warehouseFk',
            attrs: {
                url: 'warehouses',
                fields: ['id', 'name'],
            },
        },
        format: ({ warehouseName }) => warehouseName,
    },
    {
        align: 'center',
        name: 'tableActions',
        actions: [
            {
                title: t('route.cmr.params.viewCmr'),
                icon: 'visibility',
                isPrimary: true,
                action: (row) => window.open(getCmrUrl(row?.cmrFk), '_blank'),
            },
        ],
    },
]);

onBeforeMount(() => {
    initializeFromQuery();
});

onMounted(() => (state.rightDrawer = true));

const initializeFromQuery = () => {
    const query = route.query.table ? JSON.parse(route.query.table) : {};
    shipped.value = query.shipped || shipped.toISOString();
    Object.assign(userParams, { shipped });
};
function getApiUrl() {
    return new URL(window.location).origin;
}
function getCmrUrl(value) {
    return `${getApiUrl()}/api/Cmrs/${value}/print?access_token=${token}`;
}
function downloadPdfs() {
    if (!selectedRows.value.length) {
        Notify.create({
            message: t('globals.noSelectedRows'),
            type: 'warning',
        });
        return;
    }
    let cmrs = [];
    for (let value of selectedRows.value) cmrs.push(value.cmrFk);
    // prettier-ignore
    return window.open(`${getApiUrl()}/api/Cmrs/downloadZip?ids=${cmrs.join(',')}&access_token=${token}`);
}
</script>
<template>
    <VnSearchbar
        :data-key
        :label="t('route.cmr.search')"
        :info="t('route.cmr.searchInfo')"
    />
    <VnSubToolbar>
        <template #st-actions>
            <QBtn
                icon="cloud_download"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="downloadPdfs"
            >
                <QTooltip>{{ t('route.cmr.params.downloadCmrs') }}</QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <VnTable
        ref="tableRef"
        :data-key
        url="Cmrs/filter"
        :columns="columns"
        :user-params="userParams"
        default-mode="table"
        v-model:selected="selectedRows"
        table-height="85vh"
        :table="{
            'row-key': 'cmrFk',
            selection: 'multiple',
        }"
        :disable-option="{ card: true }"
    >
        <template #column-ticketFk="{ row }">
            <span class="link" @click.stop>
                {{ row.ticketFk }}
                <TicketDescriptorProxy :id="row.ticketFk" />
            </span>
        </template>
        <template #column-clientFk="{ row }">
            <span class="link" @click.stop>
                {{ row.clientFk }}
                <CustomerDescriptorProxy :id="row.clientFk" />
            </span>
        </template>
    </VnTable>
</template>
