<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useQuasar } from 'quasar';
import { toDate } from 'src/filters';
import { useRouter } from 'vue-router';
import { usePrintService } from 'src/composables/usePrintService';

import axios from 'axios';
import RouteSearchbar from 'pages/Route/Card/RouteSearchbar.vue';
import RouteListTicketsDialog from 'pages/Route/Card/RouteListTicketsDialog.vue';
import RouteSummary from 'pages/Route/Card/RouteSummary.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import RouteFilter from 'pages/Route/Card/RouteFilter.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnTable from 'components/VnTable/VnTable.vue';

const { openReport } = usePrintService();
const { t } = useI18n();
const { viewSummary } = useSummaryDialog();
const quasar = useQuasar();
const selectedRows = ref([]);
const tableRef = ref([]);
const confirmationDialog = ref(false);
const startingDate = ref(null);
const router = useRouter();
const routeFilter = {
    include: [
        {
            relation: 'workers',
            scope: {
                fields: ['id', 'firstName'],
            },
        },
    ],
};
const columns = computed(() => [
    {
        align: 'left',
        name: 'id',
        label: 'Id',
        chip: {
            condition: () => true,
        },
        isId: true,
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'workerFk',
        label: t('route.Worker'),
        create: true,
        component: 'select',
        attrs: {
            url: 'Workers/activeWithInheritedRole',
            fields: ['id', 'name'],
            useLike: false,
            optionFilter: 'firstName',
            find: {
                value: 'workerFk',
                label: 'workerUserName',
            },
        },
        columnFilter: {
            inWhere: true,
        },
        useLike: false,
        cardVisible: true,
        format: (row, dashIfEmpty) => dashIfEmpty(row.travelRef),
    },
    {
        align: 'left',
        name: 'agencyModeFk',
        label: t('route.Agency'),
        isTitle: true,
        cardVisible: true,
        create: true,
        component: 'select',
        attrs: {
            url: 'agencyModes',
            fields: ['id', 'name'],
            find: {
                value: 'agencyModeFk',
                label: 'agencyName',
            },
        },
        columnClass: 'expand',
    },
    {
        align: 'left',
        name: 'vehicleFk',
        label: t('route.Vehicle'),
        cardVisible: true,
        create: true,
        component: 'select',
        attrs: {
            url: 'vehicles',
            fields: ['id', 'numberPlate'],
            optionLabel: 'numberPlate',
            optionFilterValue: 'numberPlate',
            find: {
                value: 'vehicleFk',
                label: 'vehiclePlateNumber',
            },
        },
        columnFilter: {
            inWhere: true,
        },
    },
    {
        align: 'left',
        name: 'created',
        label: t('route.Date'),
        columnFilter: false,
        cardVisible: true,
        create: true,
        component: 'date',
        format: ({ date }) => toDate(date),
    },
    {
        align: 'left',
        name: 'from',
        label: t('route.From'),
        visible: false,
        cardVisible: true,
        create: true,
        component: 'date',
        format: ({ date }) => toDate(date),
    },
    {
        align: 'left',
        name: 'to',
        label: t('route.To'),
        visible: false,
        cardVisible: true,
        create: true,
        component: 'date',
        format: ({ date }) => toDate(date),
    },
    {
        align: 'center',
        name: 'm3',
        label: 'm3',
        cardVisible: true,
        columnClass: 'shrink',
    },
    {
        align: 'left',
        name: 'started',
        label: t('route.hourStarted'),
        component: 'time',
        columnFilter: false,
    },
    {
        align: 'left',
        name: 'finished',
        label: t('route.hourFinished'),
        component: 'time',
        columnFilter: false,
    },
    {
        align: 'center',
        name: 'kmStart',
        label: t('route.KmStart'),
        columnClass: 'shrink',
        create: true,
        visible: false,
    },
    {
        align: 'center',
        name: 'kmEnd',
        label: t('route.KmEnd'),
        columnClass: 'shrink',
        create: true,
        visible: false,
    },
    {
        align: 'left',
        name: 'description',
        label: t('route.Description'),
        isTitle: true,
        create: true,
        component: 'input',
        field: 'description',
    },
    {
        align: 'left',
        name: 'isOk',
        label: t('route.Served'),
        component: 'checkbox',
        columnFilter: false,
        columnClass: 'shrink',
    },
    {
        align: 'right',
        name: 'tableActions',
        actions: [
            {
                title: t('route.Add tickets'),
                icon: 'vn:ticketAdd',
                action: (row) => openTicketsDialog(row?.id),
                isPrimary: true,
            },
            {
                title: t('components.smartCard.viewSummary'),
                icon: 'preview',
                action: (row) => viewSummary(row?.id, RouteSummary),
                isPrimary: true,
            },
            {
                title: t('route.Route summary'),
                icon: 'arrow_forward',
                action: (row) => navigate(row?.id),
                isPrimary: true,
            },
        ],
    },
]);

function navigate(id) {
    router.push({ path: `/route/${id}` });
}

const cloneRoutes = () => {
    if (!selectedRows.value.length || !startingDate.value) return;
    axios.post('Routes/clone', {
        created: startingDate.value,
        ids: selectedRows.value.map((row) => row?.id),
    });
    startingDate.value = null;
    tableRef.value.reload();
};

const showRouteReport = () => {
    const ids = selectedRows.value.map((row) => row?.id);
    const idString = ids.join(',');
    let url = `Routes/${idString}/driver-route-pdf`;
    let params = {};
    if (selectedRows.value.length >= 1) {
        params = {
            id: idString,
        };
        url = `Routes/downloadZip`;
    }
    openReport(url, params, '_blank');
};

function markAsServed() {
    selectedRows.value.forEach(async (row) => {
        await axios.patch(`Routes/${row?.id}`, { isOk: true });
    });
    tableRef.value.reload();
    startingDate.value = null;
}

const openTicketsDialog = (id) => {
    quasar
        .dialog({
            component: RouteListTicketsDialog,
            componentProps: {
                id,
            },
        })
        .onOk(() => tableRef.value.reload());
};
</script>

<template>
    <RouteSearchbar />
    <QDialog v-model="confirmationDialog">
        <QCard style="min-width: 350px">
            <QCardSection>
                <p class="text-h6 q-ma-none">{{ t('route.Select the starting date') }}</p>
            </QCardSection>

            <QCardSection class="q-pt-none">
                <VnInputDate
                    :label="t('route.Stating date')"
                    v-model="startingDate"
                    autofocus
                />
            </QCardSection>
            <QCardActions align="right">
                <QBtn
                    flat
                    :label="t('route.Cancel')"
                    v-close-popup
                    class="text-primary"
                />
                <QBtn color="primary" v-close-popup @click="cloneRoutes">
                    {{ t('globals.clone') }}
                </QBtn>
            </QCardActions>
        </QCard>
    </QDialog>
    <VnSubToolbar />
    <RightMenu>
        <template #right-panel>
            <RouteFilter data-key="RouteList" />
        </template>
    </RightMenu>
    <VnTable
        class="route-list"
        ref="tableRef"
        data-key="RouteList"
        url="Routes/filter"
        :columns="columns"
        :right-search="false"
        :is-editable="true"
        :filter="routeFilter"
        redirect="route"
        :row-click="false"
        :create="{
            urlCreate: 'Routes',
            title: t('route.createRoute'),
            onDataSaved: ({ id }) => tableRef.redirect(id),
            formInitialData: {},
        }"
        save-url="Routes/crud"
        :disable-option="{ card: true }"
        table-height="85vh"
        v-model:selected="selectedRows"
        :table="{
            'row-key': 'id',
            selection: 'multiple',
        }"
    >
        <template #moreBeforeActions>
            <QBtn
                icon="vn:clone"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="confirmationDialog = true"
            >
                <QTooltip>{{ t('route.Clone Selected Routes') }}</QTooltip>
            </QBtn>
            <QBtn
                icon="cloud_download"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="showRouteReport"
            >
                <QTooltip>{{ t('route.Download selected routes as PDF') }}</QTooltip>
            </QBtn>
            <QBtn
                icon="check"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="markAsServed()"
            >
                <QTooltip>{{ t('route.Mark as served') }}</QTooltip>
            </QBtn>
        </template>
    </VnTable>
</template>
