<script setup>
import { useI18n } from 'vue-i18n';
import { computed, ref } from 'vue';
import { dashIfEmpty } from 'src/filters';
import { toDate, toDateHourMin } from 'filters/index';
import { useQuasar } from 'quasar';
import { useSummaryDialog } from 'composables/useSummaryDialog';
import toCurrency from 'filters/toCurrency';
import axios from 'axios';

import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import RoadmapSummary from 'pages/Route/Roadmap/RoadmapSummary.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputTime from 'src/components/common/VnInputTime.vue';
import VnSection from 'src/components/common/VnSection.vue';
import RoadmapFilter from './Roadmap/RoadmapFilter.vue';

const { viewSummary } = useSummaryDialog();
const { t } = useI18n();
const quasar = useQuasar();
const selectedRows = ref([]);
const dataKey = 'RoadmapList';
const columns = computed(() => [
    {
        align: 'left',
        name: 'id',
        label: 'Id',
        isId: true,
    },
    {
        align: 'left',
        name: 'name',
        label: t('Roadmap'),
        create: true,
        cardVisible: true,
        columnFilter: {
            inWhere: true,
        },
    },
    {
        align: 'left',
        name: 'etd',
        label: t('ETD'),
        component: 'date',
        columnFilter: {
            inWhere: true,
        },
        format: ({ dated }) => toDate(dated),
        cardVisible: true,
    },
    {
        align: 'left',
        name: 'supplierFk',
        label: t('Carrier'),
        component: 'select',
        attrs: {
            url: 'suppliers',
            fields: ['id', 'name'],
            optionLabel: 'name',
            optionValue: 'id',
        },
    },
    {
        name: 'tractorPlate',
        label: t('Plate'),
        field: (row) => row.tractorPlate,
        sortable: true,
        align: 'left',
    },
    {
        name: 'price',
        label: t('Price'),
        field: (row) => toCurrency(row.price),
        sortable: true,
        align: 'left',
    },
    {
        name: 'observations',
        label: t('Observations'),
        field: (row) => dashIfEmpty(row.observations),
        sortable: true,
        align: 'left',
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('Ver cmr'),
                icon: 'preview',
                isPrimary: true,
                action: (row) => viewSummary(row?.id, RoadmapSummary),
            },
        ],
    },
]);

const tableRef = ref(0);
const isCloneDialogOpen = ref(false);
const etdDate = ref(null);

const cloneSelection = async () => {
    await axios.post('Roadmaps/clone', {
        etd: etdDate.value,
        ids: selectedRows.value.map((row) => row?.id),
    });
    tableRef.value.reload();
    etdDate.value = null;
};

const removeSelection = async () => {
    await Promise.all(
        selectedRows.value.map((roadmap) => {
            axios.delete(`Roadmaps/${roadmap.id}`);
        }),
    );
};

function confirmRemove() {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                title: t('Selected roadmaps will be removed'),
                message: t('Are you sure you want to continue?'),
                promise: removeSelection,
            },
        })
        .onOk(() => tableRef.value++);
}

function exprBuilder(param, value) {
    switch (param) {
        case 'search':
            return /^\d+$/.test(value) ? { id: value } : { name: { like: `%${value}%` } };
        case 'tractorPlate':
        case 'trailerPlate':
        case 'driverName':
        case 'phone':
            return { [param]: { like: `%${value}%` } };
        case 'supplierFk':
        case 'price':
            return { [param]: value };
        case 'from':
            return { etd: { gte: value } };
        case 'to':
            return { etd: { lte: value } };
    }
}
</script>

<template>
    <QDialog v-model="isCloneDialogOpen">
        <QCard style="min-width: 350px">
            <QCardSection>
                <p class="text-h6 q-ma-none">
                    {{ t('Select the estimated date of departure (ETD)') }}
                </p>
            </QCardSection>

            <QCardSection class="q-pt-none">
                <VnInputDate :label="t('ETD')" v-model="etdDate" autofocus />
            </QCardSection>
            <QCardActions align="right">
                <QBtn flat :label="t('Cancel')" v-close-popup class="text-primary" />
                <QBtn color="primary" v-close-popup @click="cloneSelection">
                    {{ t('globals.clone') }}
                </QBtn>
            </QCardActions>
        </QCard>
    </QDialog>
    <VnSubToolbar class="justify-end">
        <template #st-actions>
            <QBtn
                icon="vn:clone"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="isCloneDialogOpen = true"
            >
                <QTooltip>{{ t('Clone Selected Routes') }}</QTooltip>
            </QBtn>
            <QBtn
                icon="delete"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="confirmRemove"
            >
                <QTooltip>{{ t('Delete roadmap(s)') }}</QTooltip>
            </QBtn>
        </template>
    </VnSubToolbar>
    <VnSection
        :data-key
        :columns="columns"
        prefix="route.roadmap"
        :array-data-props="{
            url: 'roadmaps',
            exprBuilder,
        }"
    >
        <template #advanced-menu>
            <RoadmapFilter :dataKey />
        </template>
        <template #body>
            <VnTable
                ref="tableRef"
                :data-key
                :columns="columns"
                :right-search="false"
                :use-model="true"
                default-mode="table"
                v-model:selected="selectedRows"
                table-height="85vh"
                :table="{
                    selection: 'multiple',
                }"
                redirect="route/roadmap"
                :create="{
                    urlCreate: 'Roadmaps',
                    title: t('Create routemap'),
                    onDataSaved: ({ id }) => tableRef.redirect(id),
                    formInitialData: {},
                }"
                :disable-option="{ card: true }"
            >
                <template #column-etd="{ row }">
                    {{ toDateHourMin(row.etd) }}
                </template>
                <template #column-supplierFk="{ row }">
                    {{ row.supplierFk }}
                </template>
                <template #more-create-dialog="{ data }">
                    <VnInputDate v-model="data.etd" />
                    <VnInputTime v-model="data.etd" />
                </template>
            </VnTable>
        </template>
    </VnSection>
</template>

<style lang="scss" scoped>
.route-list {
    width: 100%;
}
.table-actions {
    gap: 12px;
}
</style>
<i18n>
es:
    Create routemap: Crear troncal
    Search roadmaps: Buscar troncales
    You can search by roadmap reference: Puedes buscar por referencia del troncal
    Delete roadmap(s): Eliminar troncal(es)
    Selected roadmaps will be removed: Los troncales seleccionadas serán eliminados
    Are you sure you want to continue?: ¿Seguro que quieres continuar?
    The date can't be empty: La fecha no puede estar vacía
    Clone Selected Routes: Clonar rutas seleccionadas
    Create roadmap: Crear troncal
    Roadmap: Troncal
    Carrier: Transportista
    Plate: Matrícula
    Price: Precio
    Observations: Observaciones
    Select the estimated date of departure (ETD): Selecciona la fecha estimada de salida
</i18n>
