<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useStateStore } from 'stores/useStateStore';
import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'components/ui/VnLv.vue';
import { QIcon } from 'quasar';
import { dashIfEmpty, toCurrency, toDate, toHour } from 'src/filters';
import WorkerDescriptorProxy from 'pages/Worker/Card/WorkerDescriptorProxy.vue';
import axios from 'axios';
import CustomerDescriptorProxy from 'pages/Customer/Card/CustomerDescriptorProxy.vue';
import TicketDescriptorProxy from 'pages/Ticket/Card/TicketDescriptorProxy.vue';

const $props = defineProps({
    id: {
        type: Number,
        default: 0,
    },
});
const route = useRoute();
const stateStore = useStateStore();
const { t } = useI18n();

const entityId = computed(() => $props.id || route.params.id);
const isDialog = Boolean($props.id);
const hideRightDrawer = () => {
    if (!isDialog) {
        stateStore.rightDrawer = false;
    }
};
onMounted(hideRightDrawer);
onUnmounted(hideRightDrawer);
const getTotalPackages = (tickets) => {
    return (tickets || []).reduce((sum, ticket) => sum + ticket.packages, 0);
};

const ticketColumns = ref([
    {
        name: 'order',
        label: t('route.summary.order'),
        field: (row) => dashIfEmpty(row?.priority),
        sortable: false,
        align: 'center',
    },
    {
        name: 'street',
        label: t('route.summary.street'),
        field: (row) => row?.street,
        sortable: false,
        align: 'left',
    },
    {
        name: 'city',
        label: t('route.summary.city'),
        field: (row) => row?.city,
        sortable: false,
        align: 'left',
    },
    {
        name: 'pc',
        label: t('route.summary.pc'),
        field: (row) => row?.postalCode,
        sortable: false,
        align: 'center',
    },
    {
        name: 'client',
        label: t('route.summary.client'),
        field: (row) => row?.nickname,
        sortable: false,
        align: 'left',
    },
    {
        name: 'warehouse',
        label: t('route.summary.warehouse'),
        field: (row) => row?.warehouseName,
        sortable: false,
        align: 'left',
    },
    {
        name: 'packages',
        label: t('route.summary.packages'),
        field: (row) => row?.packages,
        sortable: false,
        align: 'center',
    },
    {
        name: 'volume',
        label: t('route.summary.m3'),
        field: (row) => row?.volume,
        sortable: false,
        align: 'center',
    },
    {
        name: 'packaging',
        label: t('route.summary.packaging'),
        field: (row) => row?.ipt,
        sortable: false,
        align: 'center',
    },
    {
        name: 'ticket',
        label: t('route.summary.ticket'),
        field: (row) => row?.id,
        sortable: false,
        align: 'right',
    },
    {
        name: 'observations',
        label: '',
        field: (row) => row?.ticketObservation,
        sortable: false,
        align: 'left',
    },
]);

const openBuscaman = async (route, ticket) => {
    if (!route.vehicleFk) throw new Error(`The route doesn't have a vehicle`);
    const response = await axios.get(`Routes/${route.vehicleFk}/getDeliveryPoint`);
    if (!response.data)
        throw new Error(`The route's vehicle doesn't have a delivery point`);

    const address = `${response.data}+to:${ticket.postalCode} ${ticket.city} ${ticket.street}`;
    window.open(
        'https://gps.buscalia.com/usuario/localizar.aspx?bmi=true&addr=' +
            encodeURI(address),
        '_blank'
    );
};
</script>

<template>
    <div class="q-pa-md">
        <CardSummary ref="summary" :url="`Routes/${entityId}/summary`">
            <template #header-left>
                <RouterLink :to="{ name: `RouteSummary`, params: { id: entityId } }">
                    <QIcon name="open_in_new" color="white" size="sm" />
                </RouterLink>
            </template>
            <template #header="{ entity }">
                <span>{{ `${entity?.route.id} - ${entity?.route?.description}` }}</span>
            </template>
            <template #body="{ entity }">
                <QCard class="vn-one">
                    <VnLv :label="t('ID')" :value="entity?.route.id" />
                    <VnLv
                        :label="t('route.summary.date')"
                        :value="toDate(entity?.route.created)"
                    />
                    <VnLv
                        :label="t('route.summary.agency')"
                        :value="entity?.route?.agencyMode?.name"
                    />
                    <VnLv
                        :label="t('route.summary.vehicle')"
                        :value="entity.route?.vehicle?.numberPlate"
                    />
                    <VnLv :label="t('route.summary.driver')">
                        <template #value>
                            <span class="link">
                                {{ dashIfEmpty(entity?.route?.worker?.user?.name) }}
                                <WorkerDescriptorProxy :id="entity.route?.workerFk" />
                            </span>
                        </template>
                    </VnLv>
                    <VnLv
                        :label="t('route.summary.cost')"
                        :value="toCurrency(entity.route?.cost)"
                    />
                </QCard>
                <QCard class="vn-one">
                    <VnLv
                        :label="t('route.summary.started')"
                        :value="toHour(entity?.route.started)"
                    />
                    <VnLv
                        :label="t('route.summary.finished')"
                        :value="toHour(entity?.route.finished)"
                    />
                    <VnLv
                        :label="t('route.summary.kmStart')"
                        :value="dashIfEmpty(entity?.route?.kmStart)"
                    />
                    <VnLv
                        :label="t('route.summary.kmEnd')"
                        :value="dashIfEmpty(entity?.route?.kmEnd)"
                    />
                    <VnLv
                        :label="t('route.summary.volume')"
                        :value="`${dashIfEmpty(entity?.route?.m3)} / ${dashIfEmpty(
                            entity?.route?.vehicle?.m3
                        )} m³`"
                    />
                    <VnLv
                        :label="t('route.summary.packages')"
                        :value="getTotalPackages(entity.tickets)"
                    />
                </QCard>
                <QCard class="vn-one">
                    <div class="header">
                        {{ t('route.summary.description') }}
                    </div>
                    <p>
                        {{ dashIfEmpty(entity?.route?.description) }}
                    </p>
                </QCard>

                <QCard class="vn-max">
                    <div class="header">
                        {{ t('route.summary.tickets') }}
                    </div>
                    <QTable
                        :columns="ticketColumns"
                        :rows="entity?.tickets"
                        :rows-per-page-options="[0]"
                        row-key="id"
                        flat
                        hide-pagination
                    >
                        <template #body-cell-city="{ value, row }">
                            <QTd auto-width>
                                <span
                                    class="text-primary cursor-pointer"
                                    @click="openBuscaman(entity?.route, row)"
                                >
                                    {{ value }}
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-client="{ value, row }">
                            <QTd auto-width>
                                <span class="text-primary cursor-pointer">
                                    {{ value }}
                                    <CustomerDescriptorProxy :id="row?.clientFk" />
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-ticket="{ value, row }">
                            <QTd auto-width>
                                <span class="text-primary cursor-pointer">
                                    {{ value }}
                                    <TicketDescriptorProxy :id="row?.id" />
                                </span>
                            </QTd>
                        </template>
                        <template #body-cell-observations="{ value }">
                            <QTd auto-width>
                                <QIcon
                                    v-if="value"
                                    name="vn:notes"
                                    color="primary"
                                    class="cursor-pointer"
                                >
                                    <QTooltip>{{ value }}</QTooltip>
                                </QIcon>
                            </QTd>
                        </template>
                    </QTable>
                </QCard>
            </template>
        </CardSummary>
    </div>
</template>
<i18n>
en:
    route:
        summary:
            date: Date
            agency: Agency
            vehicle: Vehicle
            driver: Driver
            cost: Cost
            started: Started time
            finished: Finished time
            kmStart: Km start
            kmEnd: Km end
            volume: Volume
            packages: Packages
            description: Description
            tickets: Tickets
            order: Order
            street: Street
            city: City
            pc: PC
            client: Client
            warehouse: Warehouse
            m3: m³
            packaging: Packaging
            ticket: Ticket
es:
    route:
        summary:
            date: Fecha
            agency: Agencia
            vehicle: Vehículo
            driver: Conductor
            cost: Costo
            started: Hora inicio
            finished: Hora fin
            kmStart: Km inicio
            kmEnd: Km fin
            volume: Volumen
            packages: Bultos
            description: Descripción
            tickets: Tickets
            order: Orden
            street: Dirección fiscal
            city: Población
            pc: CP
            client: Cliente
            warehouse: Almacén
            packaging: Encajado
</i18n>
