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

import axios from 'axios';
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';

const { t } = useI18n();
const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia();
const state = useStateStore();
const warehouses = ref([]);
const selectedRows = ref([]);
const columns = computed(() => [
    {
        align: 'left',
        name: 'cmrFk',
        label: t('route.cmr.list.cmrFk'),
        chip: {
            condition: () => true,
        },
        isId: true,
    },
    {
        align: 'left',
        name: 'hasCmrDms',
        label: t('route.cmr.list.hasCmrDms'),
        component: 'checkbox',
        cardVisible: true,
    },
    {
        label: t('route.cmr.list.ticketFk'),
        name: 'ticketFk',
    },
    {
        label: t('route.cmr.list.routeFk'),
        name: 'routeFk',
    },
    {
        label: t('route.cmr.list.clientFk'),
        name: 'clientFk',
    },
    {
        align: 'left',
        label: t('route.cmr.list.country'),
        name: 'country',
        cardVisible: true,
    },
    {
        align: 'center',
        label: t('route.cmr.list.shipped'),
        name: 'shipped',
        cardVisible: true,
        component: 'date',
        columnFilter: {
            alias: 'c',
            inWhere: true,
        },
        format: ({ date }) => toDate(date),
    },
    {
        align: 'center',
        name: 'warehouseFk',
        label: t('globals.warehouse'),
        component: 'select',
        attrs: {
            url: 'warehouses',
            fields: ['id', 'name'],
            optionLabel: 'name',
            optionValue: 'id',
        },
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('Ver cmr'),
                icon: 'visibility',
                isPrimary: true,
                action: (row) => window.open(getCmrUrl(row?.cmrFk), '_blank'),
            },
        ],
    },
]);

onBeforeMount(async () => {
    const { data } = await axios.get('Warehouses');
    warehouses.value = data;
});

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

function getApiUrl() {
    return new URL(window.location).origin;
}
function getCmrUrl(value) {
    return `${getApiUrl()}/api/Routes/${value}/cmr?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/Routes/downloadCmrsZip?ids=${cmrs.join(',')}&access_token=${token}`);
}
</script>
<template>
    <VnSubToolbar>
        <template #st-actions>
            <QBtn
                icon="cloud_download"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="downloadPdfs"
            >
                <QTooltip>{{ t('route.cmr.list.downloadCmrs') }}</QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <VnTable
        ref="tableRef"
        data-key="CmrList"
        url="Routes/cmrs"
        :columns="columns"
        :right-search="true"
        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.ticketFk }}
                <CustomerDescriptorProxy :id="row.clientFk" />
            </span>
        </template>
    </VnTable>
</template>
