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

import { date, QBtn } from 'quasar';

import { useArrayData } from 'composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';
import { toCurrency } from 'src/filters';

import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';

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

const arrayData = ref(null);
const totalAmount = ref(0);
const workerId = ref(0);
const rows = computed(() => arrayData.value.store.data);

onBeforeMount(async () => {
    const filter = {
        include: [
            {
                relation: 'greugeType',
                scope: {
                    fields: ['id', 'name'],
                },
            },
            {
                relation: 'user',
                scope: {
                    fields: ['id', 'name'],
                },
            },
        ],
        order: 'shipped DESC, amount',
        where: {
            clientFk: `${route.params.id}`,
        },
        limit: 20,
    };

    arrayData.value = useArrayData('CustomerGreugesCard', {
        url: 'greuges',
        filter,
    });
    await arrayData.value.fetch({ append: false });
    totalAmount.value = arrayData.value.store.data.reduce((accumulator, currentValue) => {
        return accumulator + currentValue.amount;
    }, 0);
    stateStore.rightDrawer = true;
});

const tableColumnComponents = {
    date: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    createdBy: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: (prop) => {
            selectWorkerId(prop.row.clientFk);
        },
    },
    comment: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    type: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    amount: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: 'shipped',
        label: t('Date'),
        name: 'date',
        format: (value) => date.formatDate(value, 'DD/MM/YYYY hh:mm:ss'),
    },
    {
        align: 'left',
        field: (value) => value.user.name,
        label: t('Created by'),
        name: 'createdBy',
    },
    {
        align: 'left',
        field: 'description',
        label: t('Comment'),
        name: 'comment',
    },
    {
        align: 'left',
        field: (value) => value.greugeType.name,
        label: t('Type'),
        name: 'type',
    },
    {
        align: 'left',
        field: 'amount',
        label: t('Amount'),
        name: 'amount',
        format: (value) => toCurrency(value),
    },
]);

const selectWorkerId = (id) => {
    workerId.value = id;
};

const toCustomerGreugeCreate = () => {
    router.push({ name: 'CustomerGreugeCreate' });
};
</script>

<template>
    <QPage class="column items-center q-pa-md">
        <QCard class="full-width" v-if="totalAmount">
            <h6 class="flex justify-end q-my-lg q-pr-lg">
                <span class="label-color q-mr-md">{{ t('Total') }}:</span>
                {{ toCurrency(totalAmount) }}
            </h6>
        </QCard>

        <QTable
            :columns="columns"
            :pagination="{ rowsPerPage: 12 }"
            :rows="rows"
            class="full-width q-mt-md"
            row-key="id"
            v-if="rows?.length"
        >
            <template #body-cell="props">
                <QTd :props="props">
                    <QTr :props="props" class="cursor-pointer">
                        <component
                            :is="tableColumnComponents[props.col.name].component"
                            class="col-content"
                            v-bind="tableColumnComponents[props.col.name].props(props)"
                            @click="tableColumnComponents[props.col.name].event(props)"
                        >
                            {{ props.value }}
                            <WorkerDescriptorProxy :id="workerId" />
                        </component>
                    </QTr>
                </QTd>
            </template>
        </QTable>

        <QCard class="full-width" v-else>
            <h5 class="flex justify-center label-color">
                {{ t('globals.noResults') }}
            </h5>
        </QCard>
    </QPage>

    <QPageSticky :offset="[18, 18]">
        <QBtn @click.stop="toCustomerGreugeCreate()" color="primary" fab icon="add" />
        <QTooltip>
            {{ t('New greuge') }}
        </QTooltip>
    </QPageSticky>
</template>

<style lang="scss">
.consignees-card {
    border: 2px solid var(--vn-light-gray);
    border-radius: 10px;
    padding: 10px;
}

.label-color {
    color: var(--vn-label);
}
</style>

<i18n>
es:
    Total: Total
    Date: Fecha
    Created by: Creado por
    Comment: Comentario
    Type: Tipo
    Amount: Importe
    New greuge: Nuevo greuge
</i18n>
