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

import VnPaginate from 'src/components/ui/VnPaginate.vue';
import VnConfirm from 'components/ui/VnConfirm.vue';
import FetchData from 'src/components/FetchData.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import { toDate } from 'src/filters';
import { downloadFile } from 'src/composables/downloadFile';

const route = useRoute();
const quasar = useQuasar();
const router = useRouter();
const { t } = useI18n();
const { notify } = useNotify();

const thermographPaginateRef = ref(null);
const warehouses = ref([]);

const thermographFilter = {
    include: {
        relation: 'warehouse',
        scope: {
            fields: ['id', 'name'],
        },
    },
    where: { travelFk: route.params.id },
    order: ['created'],
};

const TableColumns = computed(() => {
    return [
        {
            label: t('travel.thermographs.code'),
            field: 'thermographFk',
            name: 'thermographFk',
            align: 'left',
        },
        {
            label: t('travel.thermographs.temperature'),
            field: 'temperatureFk',
            name: 'temperatureFk',
            align: 'left',
        },
        {
            label: t('travel.thermographs.state'),
            field: 'result',
            name: 'result',
            align: 'left',
        },
        {
            label: t('travel.thermographs.destination'),
            field: 'warehouseFk',
            name: 'destination',
            align: 'left',
            format: (val) =>
                warehouses.value.find((warehouse) => warehouse.id === val)?.name,
        },
        {
            label: t('travel.thermographs.created'),
            field: 'created',
            name: 'created',
            align: 'left',
            format: (val) => toDate(val),
        },
        {
            name: 'downloadFile',
            align: 'left',
        },
        {
            name: 'editFile',
            align: 'left',
        },
        {
            name: 'removeThermograph',
            align: 'left',
        },
    ];
});

const openRemoveDialog = async (id) => {
    quasar
        .dialog({
            component: VnConfirm,
            componentProps: {
                message: t('Are you sure you want to remove the thermograph?'),
            },
        })
        .onOk(async () => {
            try {
                await removeThermograph(id);
            } catch (err) {
                console.error('Error removing thermograph');
            }
        });
};

const redirectToThermographForm = (action, id) => {
    const routeDetails = {
        name: action === 'create' ? 'TravelThermographsCreate' : 'TravelThermographsEdit',
    };

    if (action === 'edit' && id) {
        const params = {};
        params.thermographId = id;
        routeDetails.params = params;
    }
    router.push(routeDetails);
};

const removeThermograph = async (id) => {
    try {
        await axios.delete(`Travels/deleteThermograph?id=${id}`);
        await thermographPaginateRef.value.fetch();
        notify(t('Thermograph removed'), 'positive');
    } catch (err) {
        console.error('Error removing termograph');
    }
};
</script>

<template>
    <FetchData
        url="Warehouses"
        :filter="{ fields: ['id', 'name'] }"
        order="name"
        @on-fetch="(data) => (warehouses = data)"
        auto-load
    />
    <VnPaginate
        ref="thermographPaginateRef"
        data-key="TravelThermographs"
        url="TravelThermographs"
        :filter="thermographFilter"
        :params="{ travelFk: route.params.id }"
        auto-load
    >
        <template #body="{ rows }">
            <QTable
                :rows="rows"
                :columns="TableColumns"
                :no-data-label="t('No results')"
                :rows-per-page-options="[0]"
                row-key="id"
                class="full-width q-mt-md"
            >
                <template #body-cell-downloadFile="{ row }">
                    <QTd auto-width>
                        <QIcon
                            name="cloud_download"
                            color="primary"
                            size="sm"
                            class="cursor-pointer"
                            @click="downloadFile(row.dmsFk)"
                        >
                            <QTooltip>{{ t('Download file') }}</QTooltip>
                        </QIcon>
                    </QTd>
                </template>
                <template #body-cell-editFile="{ row }">
                    <QTd auto-width>
                        <QIcon
                            name="edit"
                            color="primary"
                            size="sm"
                            class="cursor-pointer"
                            @click="redirectToThermographForm('edit', row.id)"
                        >
                            <QTooltip>{{ t('Edit file') }}</QTooltip>
                        </QIcon>
                    </QTd>
                </template>
                <template #body-cell-removeThermograph="{ row }">
                    <QTd auto-width>
                        <QIcon
                            name="delete"
                            color="primary"
                            size="sm"
                            class="cursor-pointer"
                            @click="openRemoveDialog(row.id)"
                        >
                            <QTooltip>{{ t('Remove thermograph') }}</QTooltip>
                        </QIcon>
                    </QTd>
                </template>
            </QTable>
        </template>
    </VnPaginate>
    <QPageSticky :offset="[20, 20]">
        <QBtn
            fab
            icon="add"
            color="primary"
            @click="redirectToThermographForm('create')"
        />
        <QTooltip class="text-no-wrap">
            {{ t('Add thermograph') }}
        </QTooltip>
    </QPageSticky>
</template>

<i18n>
es:
    Add thermograph: Añadir termógrafo
    Download file: Descargar fichero
    Edit file: Editar fichero
    Remove thermograph: Eliminar termógrafo
    Thermograph removed: Termógrafo eliminado
    Are you sure you want to remove the thermograph?: ¿Seguro que quieres quitar el termógrafo?
    No results: Sin resultados
</i18n>
