<script setup>
import { useArrayData } from 'composables/useArrayData';
import { dashIfEmpty, toHour } from 'src/filters';
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useValidator } from 'composables/useValidator';
import { useSession } from 'composables/useSession';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useQuasar } from 'quasar';

import axios from 'axios';
import RouteSearchbar from 'pages/Route/Card/RouteSearchbar.vue';
import FetchData from 'components/FetchData.vue';
import RouteListTicketsDialog from 'pages/Route/Card/RouteListTicketsDialog.vue';
import { useRouter } from 'vue-router';
import TableVisibleColumns from 'src/components/common/TableVisibleColumns.vue';
import RouteFilter from 'pages/Route/Card/RouteFilter.vue';
import RightMenu from 'src/components/common/RightMenu.vue';
import RouteSummary from 'pages/Route/Card/RouteSummary.vue';

import VnPaginate from 'components/ui/VnPaginate.vue';
import VnInput from 'components/common/VnInput.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import VnTable from 'components/VnTable/VnTable.vue';
import { useStateStore } from 'src/stores/useStateStore';

const { t } = useI18n();
const { validate } = useValidator();
const { viewSummary } = useSummaryDialog();
const quasar = useQuasar();
const session = useSession();
const paginate = ref();
const visibleColumns = ref([]);
const selectedRows = ref([]);
const workers = ref([]);
const agencyList = ref([]);
const vehicleList = ref([]);
const allColumnNames = ref([]);
const confirmationDialog = ref(false);
const startingDate = ref(null);
const refreshKey = ref(0);
const router = useRouter();
const stateStore = useStateStore();
const columns = computed(() => [
    {
        align: 'left',
        name: 'id',
        label: 'Id',
        chip: {
            condition: () => true,
        },
        isId: true,
        columnFilter: {
            name: 'search',
        },
    },
    {
        align: 'left',
        name: 'worker',
        label: t('Worker'),
        create: true,
        component: 'select',
        attrs: {
            url: 'payrollComponents',
            fields: ['id', 'name'],
        },
        cardVisible: true,
    },
    {
        name: 'agency',
        label: t('Agency'),
        align: 'left',
        isTitle: true,
        cardVisible: true,
        create: true,
    },
    {
        name: 'vehicle',
        label: t('Vehicle'),
        align: 'left',
        cardVisible: true,
        create: true,
    },
    {
        name: 'date',
        label: t('Date'),
        align: 'left',
        cardVisible: true,
        create: true,
    },
    {
        name: 'volume',
        label: 'm³',
        align: 'center',
        cardVisible: true,
    },
    {
        name: 'description',
        label: t('Description'),
        align: 'left',
        isTitle: true,
        create: true,
    },
    {
        name: 'started',
        label: t('hourStarted'),
        align: 'left',
    },
    {
        name: 'finished',
        label: t('hourFinished'),
        align: 'left',
    },
    {
        name: 'isServed',
        label: t('Served'),
        align: 'left',
    },
    {
        align: 'right',
        label: 'asdasd',
        name: 'tableActions',
        actions: [
            {
                title: t('Client ticket list'),
                icon: 'preview',
                action: (row) => navigate(row.id),
            },
        ],
    },
]);

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

const updateRoute = async (route) => {
    try {
        return await axios.patch(`Routes/${route.id}`, route);
    } catch (err) {
        return err;
    }
};

const cloneRoutes = () => {
    axios.post('Routes/clone', {
        created: startingDate.value,
        ids: selectedRows.value.map((row) => row?.id),
    });
    refreshKey.value++;
    startingDate.value = null;
    paginate.value.fetch();
};

const showRouteReport = () => {
    const ids = selectedRows.value.map((row) => row?.id);
    const idString = ids.join(',');
    let url;

    if (selectedRows.value.length <= 1) {
        url = `api/Routes/${idString}/driver-route-pdf?access_token=${session.getTokenMultimedia()}`;
    } else {
        const params = new URLSearchParams({
            access_token: session.getTokenMultimedia(),
            id: idString,
        });
        url = `api/Routes/downloadZip?${params.toString()}`;
    }
    window.open(url, '_blank');
};

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

const openTicketsDialog = (id) => {
    if (!id) {
        return;
    }
    quasar
        .dialog({
            component: RouteListTicketsDialog,
            componentProps: {
                id,
            },
        })
        .onOk(() => refreshKey.value++);
};
</script>

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

            <QCardSection class="q-pt-none">
                <VnInputDate
                    :label="t('Stating date')"
                    v-model="startingDate"
                    autofocus
                />
            </QCardSection>
            <QCardActions align="right">
                <QBtn flat :label="t('Cancel')" v-close-popup class="text-primary" />
                <QBtn color="primary" v-close-popup @click="cloneRoutes">
                    {{ t('globals.clone') }}
                    <VnLv
                        :label="t('route.summary.packages')"
                        :value="getTotalPackages(entity.tickets)"
                    />
                </QBtn>
            </QCardActions>
        </QCard>
    </QDialog>
    <FetchData
        url="Workers/activeWithInheritedRole"
        @on-fetch="(data) => (workers = data)"
        auto-load
    />
    <FetchData url="AgencyModes" @on-fetch="(data) => (agencyList = data)" auto-load />
    <FetchData url="Vehicles" @on-fetch="(data) => (vehicleList = data)" auto-load />
    <VnSubToolbar />
    <VnTable
        ref="tableRef"
        data-key="RouteList"
        url="Routes/filter"
        :columns="columns"
        :right-search="true"
        :is-editable="true"
        :create="{
            urlCreate: 'Routes',
            title: t('Create route'),
            onDataSaved: () => tableRef.reload(),
        }"
        save-url="routes"
        :disable-option="{ card: true }"
    >
        <template #moreBeforeActions>
            <QBtn
                icon="vn:clone"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="confirmationDialog = true"
            >
                <QTooltip>{{ t('Clone Selected Routes') }}</QTooltip>
            </QBtn>
            <QBtn
                icon="cloud_download"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="showRouteReport"
            >
                <QTooltip>{{ t('Download selected routes as PDF') }}</QTooltip>
            </QBtn>
            <QBtn
                icon="check"
                color="primary"
                class="q-mr-sm"
                :disable="!selectedRows?.length"
                @click="markAsServed()"
            >
                <QTooltip>{{ t('Mark as served') }}</QTooltip>
            </QBtn>
        </template>
    </VnTable>
</template>

<style lang="scss" scoped>
.table-input-cell {
    max-width: 143px;
}

.route-list {
    width: 100%;
    max-height: 100%;
}

.table-actions {
    gap: 12px;
}
th:last-child,
td:last-child {
    background-color: var(--vn-section-color);
    position: sticky;
    right: 0;
}
</style>
<i18n>
en:
    newRoute: New Route
    hourStarted: Started hour
    hourFinished: Finished hour
es:
    Worker: Trabajador
    Agency: Agencia
    Vehicle: Vehículo
    Date: Fecha
    Description: Descripción
    Hour started: Hora inicio
    Hour finished: Hora fin
    Served: Servida
    newRoute: Nueva Ruta
    Clone Selected Routes: Clonar rutas seleccionadas
    Select the starting date: Seleccione la fecha de inicio
    Stating date: Fecha de inicio
    Cancel: Cancelar
    Mark as served: Marcar como servidas
    Download selected routes as PDF: Descargar rutas seleccionadas como PDF
    Add ticket: Añadir tickets
    Preview: Vista previa
    Summary: Resumen
    Route is closed: La ruta está cerrada
    Route is not served: La ruta no está servida
    hourStarted: Hora de inicio
    hourFinished: Hora de fin
</i18n>
