<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { QBtn, date } from 'quasar';

import { toCurrency } from 'src/filters';

import FetchData from 'components/FetchData.vue';
import CustomerSummaryTableActions from './CustomerSummaryTableActions.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import RouteDescriptorProxy from 'src/pages/Route/Card/RouteDescriptorProxy.vue';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();

const rows = ref([]);

const filter = {
    include: [
        {
            relation: 'ticketState',
            scope: {
                fields: ['stateFk', 'code', 'alertLevel'],
                include: { relation: 'state' },
            },
        },
        { relation: 'invoiceOut', scope: { fields: ['id'] } },
        { relation: 'agencyMode', scope: { fields: ['name'] } },
    ],
    where: { clientFk: route.params.id },
    order: ['shipped DESC', 'id'],
    limit: 10,
};

const tableColumnComponents = {
    id: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    nickname: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue', noCaps: true }),
        event: () => {},
    },
    agency: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    route: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: () => {},
    },
    packages: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    date: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    state: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    total: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    actions: {
        component: CustomerSummaryTableActions,
        props: (prop) => ({
            id: prop.row.id,
        }),
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: 'id',
        label: t('Id'),
        name: 'id',
    },
    {
        align: 'left',
        field: 'nickname',
        label: t('Nickname'),
        name: 'nickname',
    },
    {
        align: 'left',
        field: (row) => row?.agencyMode?.name,
        label: t('Agency'),
        name: 'agency',
    },
    {
        align: 'left',
        field: 'routeFk',
        label: t('Route'),
        name: 'route',
    },
    {
        align: 'left',
        field: 'packages',
        label: t('Packages'),
        name: 'packages',
    },
    {
        align: 'left',
        field: (row) => date.formatDate(row?.shipped, 'DD/MM/YYYY'),
        label: t('Date'),
        name: 'date',
    },
    {
        align: 'left',
        field: (row) => row?.ticketState?.state?.name,
        label: t('State'),
        name: 'state',
    },
    {
        align: 'left',
        field: 'totalWithVat',
        label: t('Total'),
        name: 'total',
    },
    {
        align: 'left',
        field: 'totalWithVat',
        label: '',
        name: 'actions',
    },
]);

const setStateColor = (ticket) => {
    const { ticketState } = ticket;
    if (!ticketState) return;
    const codeColorMap = { OK: 'success', FREE: 'notice' };
    const alertLevelColorMap = { 0: 'alert', 1: 'warning' };
    if (codeColorMap[ticketState.code]) return codeColorMap[ticketState.code];
    return alertLevelColorMap[ticketState.alertLevel];
};

const setTotalPriceColor = (ticket) => {
    const total = parseInt(ticket.totalWithVat);
    if (total > 0 && total < 50) return 'warning';
};

const navigateToticketSummary = (id) => {
    router.push({
        name: 'TicketSummary',
        params: { id },
    });
};
const commonColumns = (col) => ['date', 'state', 'total'].includes(col);
</script>

<template>
    <FetchData
        :filter="filter"
        @on-fetch="(data) => (rows = data)"
        auto-load
        url="Tickets"
    />
    <QCard class="vn-one q-py-sm flex justify-between">
        <QTable
            :columns="columns"
            :pagination="{ rowsPerPage: 12 }"
            :rows="rows"
            class="full-width"
            row-key="id"
        >
            <template #body-cell="props">
                <QTd :props="props" @click="navigateToticketSummary(props.row.id)">
                    <QTr :props="props" class="cursor-pointer">
                        <component
                            :is="tableColumnComponents[props.col.name].component"
                            @click="tableColumnComponents[props.col.name].event(props)"
                            class="rounded-borders"
                            v-bind="tableColumnComponents[props.col.name].props(props)"
                        >
                            <template v-if="!commonColumns(props.col.name)">
                                <span
                                    :class="{
                                        link:
                                            props.col.name === 'route' ||
                                            props.col.name === 'nickname',
                                    }"
                                >
                                    {{ props.value }}
                                </span>
                            </template>
                            <template v-if="props.col.name === 'date'">
                                <QBadge class="q-pa-sm" color="warning">
                                    {{ props.value }}
                                </QBadge>
                            </template>
                            <template v-if="props.col.name === 'state'">
                                <QBadge :color="setStateColor(props.row)" class="q-pa-sm">
                                    {{ props.value }}
                                </QBadge>
                            </template>
                            <template v-if="props.col.name === 'total'">
                                <QBadge
                                    :color="setTotalPriceColor(props.row)"
                                    class="q-pa-sm"
                                    v-if="setTotalPriceColor(props.row)"
                                >
                                    {{ toCurrency(props.value) }}
                                </QBadge>
                                <div v-else>{{ toCurrency(props.value) }}</div>
                            </template>
                            <CustomerDescriptorProxy
                                :id="props.row.clientFk"
                                v-if="props.col.name === 'nickname'"
                            />
                            <RouteDescriptorProxy
                                :id="props.row.routeFk"
                                v-if="props.col.name === 'route'"
                            />
                        </component>
                    </QTr>
                </QTd>
            </template>
        </QTable>
    </QCard>
</template>

<i18n>
es:
    Id: Id
    Nickname: Alias
    Agency: Agencia
    Route: Ruta
    Packages: Bultos
    Date: Fecha
    State: Estado
    Total: Total
</i18n>
