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

import { QBadge, QBtn, QCheckbox } from 'quasar';

import { downloadFile } from 'src/composables/downloadFile';
import { toDateTimeFormat } from 'src/filters/date';

import FetchData from 'components/FetchData.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import CustomerFileManagementActions from 'src/pages/Customer/components/CustomerFileManagementActions.vue';

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

const ClientDmsRef = ref(null);
const rows = ref([]);

const filter = {
    include: {
        relation: 'dms',
        scope: {
            fields: [
                'dmsTypeFk',
                'reference',
                'hardCopyNumber',
                'workerFk',
                'description',
                'hasFile',
                'file',
                'created',
            ],
            include: [
                { relation: 'dmsType', scope: { fields: ['name'] } },
                {
                    relation: 'worker',
                    scope: {
                        fields: ['id'],
                        include: { relation: 'user', scope: { fields: ['name'] } },
                    },
                },
            ],
        },
    },
    where: { clientFk: route.params.id },
    order: ['dmsFk DESC'],
    limit: 20,
};

const tableColumnComponents = {
    id: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    type: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    order: {
        component: QBadge,
        props: () => {},
        event: () => {},
    },
    reference: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    description: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    original: {
        component: QCheckbox,
        props: (prop) => ({
            disable: true,
            'model-value': Boolean(prop.value),
        }),
        event: () => {},
    },
    file: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: ({ row }) => downloadFile(row.dmsFk),
    },
    employee: {
        component: QBtn,
        props: () => ({ flat: true, color: 'blue' }),
        event: () => {},
    },
    created: {
        component: 'span',
        props: () => {},
        event: () => {},
    },
    actions: {
        component: CustomerFileManagementActions,
        props: (prop) => ({
            id: prop.row.dmsFk,
            promise: setData,
        }),
        event: () => {},
    },
};

const columns = computed(() => [
    {
        align: 'left',
        field: ({ dms }) => dms.id,
        label: t('Id'),
        name: 'id',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.dmsType.name,
        label: t('Type'),
        name: 'type',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.hardCopyNumber,
        label: t('Order'),
        name: 'order',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.reference,
        label: t('Reference'),
        name: 'reference',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.description,
        label: t('Description'),
        name: 'description',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.hasFile,
        label: t('Original'),
        name: 'original',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.file,
        label: t('File'),
        name: 'file',
    },
    {
        align: 'left',
        field: ({ dms }) => dms.worker.user.name,
        label: t('Employee'),
        name: 'employee',
    },
    {
        align: 'left',
        field: (value) => value.dms.created,
        label: t('Created'),
        name: 'created',
        format: (value) => toDateTimeFormat(value),
    },
    {
        align: 'right',
        field: 'actions',
        label: '',
        name: 'actions',
    },
]);

const setData = () => {
    ClientDmsRef.value.fetch();
};

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

<template>
    <FetchData
        ref="ClientDmsRef"
        :filter="filter"
        @on-fetch="(data) => (rows = data)"
        auto-load
        url="ClientDms"
    />

    <QPage class="column items-center q-pa-md">
        <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="
                                props.col.name === 'order' && !props.value
                                    ? 'span'
                                    : tableColumnComponents[props.col.name].component
                            "
                            @click="tableColumnComponents[props.col.name].event(props)"
                            class="col-content"
                            v-bind="tableColumnComponents[props.col.name].props(props)"
                        >
                            <template v-if="props.col.name !== 'original'">
                                {{ props.value }}
                            </template>
                            <WorkerDescriptorProxy
                                :id="props.row.dms.workerFk"
                                v-if="props.col.name === 'employee'"
                            />
                        </component>
                    </QTr>
                </QTd>
            </template>
        </QTable>

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

    <QPageSticky :offset="[18, 18]">
        <QBtn
            @click.stop="toCustomerFileManagementCreate()"
            color="primary"
            fab
            shortcut="+"
            icon="add"
        />
        <QTooltip>
            {{ t('Upload file') }}
        </QTooltip>
    </QPageSticky>
</template>

<i18n>
es:
    Id: Id
    Type: Tipo
    Order: Orden
    Reference: Referencia
    Description: Descripción
    Original: Original
    File: Fichero
    Employee: Empleado
    Created: Fecha creación
    Upload file: Subir fichero
</i18n>
