<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 { toDateHourMin } 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: 'center',
        name: 'hasCmrDms',
        label: t('route.cmr.list.hasCmrDms'),
        component: 'checkbox',
        cardVisible: true,
    },
    {
        align: 'left',
        label: t('route.cmr.list.ticketFk'),
        name: 'ticketFk',
    },
    {
        align: 'left',
        label: t('route.cmr.list.routeFk'),
        name: 'routeFk',
    },
    {
        align: 'left',
        label: t('route.cmr.list.clientFk'),
        name: 'clientFk',
    },
    {
        align: 'right',
        label: t('route.cmr.list.country'),
        name: 'countryFk',
        cardVisible: true,
        attrs: {
            url: 'countries',
            fields: ['id', 'name'],
            optionLabel: 'name',
            optionValue: 'id',
        },
        columnFilter: {
            inWhere: true,
            component: 'select',
        },
        format: ({ countryName }) => countryName,
    },
    {
        align: 'right',
        label: t('route.cmr.list.shipped'),
        name: 'shipped',
        cardVisible: true,
        columnFilter: {
            component: 'date',
            inWhere: true,
        },
        format: ({ shipped }) => toDateHourMin(shipped),
    },
    {
        align: 'right',
        name: 'warehouseFk',
        label: t('globals.warehouse'),
        columnFilter: {
            component: 'select',
        },
        attrs: {
            options: warehouses.value,
        },
        format: ({ warehouseName }) => warehouseName,
    },
    {
        align: 'center',
        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.clientFk }}
                <CustomerDescriptorProxy :id="row.clientFk" />
            </span>
        </template>
    </VnTable>
</template>
